repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
decidim/decidim
decidim-participatory_processes/app/cells/decidim/participatory_processes/process_cell.rb
544
# frozen_string_literal: true module Decidim module ParticipatoryProcesses # This cell renders the process card for an instance of a Process # the default size is the Medium Card (:m) class ProcessCell < Decidim::ViewModel def show cell card_size, model, options end private def card_size case @options[:size] when :s "decidim/participatory_processes/process_s" else "decidim/participatory_processes/process_m" end end end end end
agpl-3.0
knmkr/dbsnp-pg
web/dbsnp/templatetags/extra.py
400
from django import template register = template.Library() @register.filter def css_class(value, arg): return value.as_widget(attrs={'class': arg}) @register.filter def na(value): return 'N/A' if value is None or value == '' else value @register.filter def fwd_or_rev(value): if value == 0: return 'Fwd' elif value == 1: return 'Rev' else: return 'N/A'
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Nursing/src/ims/nursing/domain/base/impl/BaseClinicalNoteDialogImpl.java
2195
//############################################################################# //# # //# 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.nursing.domain.base.impl; import ims.domain.impl.DomainImpl; public abstract class BaseClinicalNoteDialogImpl extends DomainImpl implements ims.nursing.domain.ClinicalNoteDialog, ims.domain.impl.Transactional { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public void validatesaveClinicalNotes(ims.nursing.vo.NursingClinicalNotesVo voNotes) { } @SuppressWarnings("unused") public void validategetHcpLite(Integer idHcp) { } }
agpl-3.0
kerr-huang/openss7
src/java/javax/jain/ss7/GlobalTitle.java
6942
/* @(#) src/java/javax/jain/ss7/GlobalTitle.java <p> Copyright &copy; 2008-2015 Monavacon Limited <a href="http://www.monavacon.com/">&lt;http://www.monavacon.com/&gt;</a>. <br> Copyright &copy; 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/">&lt;http://www.openss7.com/&gt;</a>. <br> Copyright &copy; 1997-2001 Brian F. G. Bidulock <a href="mailto:bidulock@openss7.org">&lt;bidulock@openss7.org&gt;</a>. <p> All Rights Reserved. <p> 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, version 3 of the license. <p> This program is distributed in the hope that it will be useful, but <b>WITHOUT ANY WARRANTY</b>; without even the implied warranty of <b>MERCHANTABILITY</b> or <b>FITNESS FOR A PARTICULAR PURPOSE</b>. See the GNU Affero General Public License for more details. <p> You should have received a copy of the GNU Affero General Public License along with this program. If not, see <a href="http://www.gnu.org/licenses/">&lt;http://www.gnu.org/licenses/&gt</a>, or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. <p> <em>U.S. GOVERNMENT RESTRICTED RIGHTS</em>. If you are licensing this Software on behalf of the U.S. Government ("Government"), the following provisions apply to you. If the Software is supplied by the Department of Defense ("DoD"), it is classified as "Commercial Computer Software" under paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition Regulations ("DFARS") (or any successor regulations) and the Government is acquiring only the license rights granted herein (the license rights customarily provided to non-Government users). If the Software is supplied to any unit or agency of the Government other than DoD, it is classified as "Restricted Computer Software" and the Government's rights in the Software are defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR") (or any successor regulations) or, in the cases of NASA, in paragraph 18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). <p> Commercial licensing and support of this software is available from OpenSS7 Corporation at a fee. See <a href="http://www.openss7.com/">http://www.openss7.com/</a> */ package javax.jain.ss7; import javax.jain.*; /** * When instantiated this class represents a Global Title format which * informs the user that the GlobalTitle is not included, its Global * Title Indicator is of value '0000'. * * The various Global Title Indicators that extend this class are: <ul> * <li>{@link GTIndicator#GTINDICATOR_0000 GTINDICATOR_0000} * <li>{@link GTIndicator#GTINDICATOR_0001 GTINDICATOR_0001} * <li>{@link GTIndicator#GTINDICATOR_0010 GTINDICATOR_0010} * <li>{@link GTIndicator#GTINDICATOR_0011 GTINDICATOR_0011} * <li>{@link GTIndicator#GTINDICATOR_0100 GTINDICATOR_0100} </ul> * * The complete combination of GlobalTitles included support the * following standards: <ul> * <li>ANSI SCCP T1.112 (1992) * <li>ANSI SCCP T1.112 (1996) * <li>ITU SCCP Q711-716 (03/1993) * <li>ITU SCCP Q711-716 (07/1996) </ul> * * @author Monavacon Limited * @version 1.2.2 */ public class GlobalTitle implements java.io.Serializable { /** * Constructs a new Global Title of format * {@link GTIndicator#GTINDICATOR_0000 GTINDICATOR_0000}, which indicates that * the GlobalTitle is not included. * That is no Address Information included. */ public GlobalTitle() { } /** * Construct a new Global Title supplying the address information. * @param addressInformation * Address information with which to create the Global Title. */ protected GlobalTitle(byte[] addressInformation) { super(); setAddressInformation(addressInformation); } /** * Sets the Address Information of this Global Title of the * subclassed GTIndicators. <p> * <em>Note to developers:-</em> An Address Information is * forbidden an instantiation of this class, that is * GTindicator-0000. * @param addressInformation * The new Address Information. */ public void setAddressInformation(byte[] addressInformation) { m_addressInformation = addressInformation; m_addressInformationIsSet = (m_addressInformation != null); } /** * Gets the format of the Global Title. * The Global Title format of this class is * {@link GTIndicator#GTINDICATOR_0000 GTINDICATOR_0000}. * @return * The Global Title Indicator value. */ public GTIndicator getGTIndicator() { return GTIndicator.GTINDICATOR_0000; } /** * Gets the Address Information of the sub-classed Global Title * Indicators. <p> * <em>Note to developers:-</em> An Address Information is * forbidden an instantiation of this class, that is * GTindicator-0000. * @return * The GlobalTitle Address Information subparameter is composed of * digits in the form of Binary Coded Decimal(BCD). * @exception MandatoryParameterNotSetException * This exception is thrown if this parameter has not been set. * @exception ParameterNotSetException * This exception is thrown if this method is invoked when the * GlobalTitle is of type GTIndicator0000, that is an instantiation * of the GlobalTitle class. */ public byte[] getAddressInformation() throws ParameterNotSetException, MandatoryParameterNotSetException { if (m_addressInformationIsSet) return m_addressInformation; throw new ParameterNotSetException("Address Information: not set."); } /** * java.lang.String representation of class GlobalTitle * @return * java.lang.String provides description of class GlobalTitle. */ public java.lang.String toString() { StringBuffer b = new StringBuffer(512); b.append(super.toString()); b.append("\njain.protocol.ss7.GlobalTitle:"); b.append("\n\tGlobal Title Indicator: = GTINDICATOR_0000"); b.append("\n\tm_addressInformation = "); if (m_addressInformation != null) b.append(m_addressInformation.toString()); else b.append("(null)"); b.append("\n\tm_addressInformationIsSet = " + m_addressInformationIsSet); return b.toString(); } protected byte[] m_addressInformation = null; protected boolean m_addressInformationIsSet = false; } // vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Admin/src/ims/admin/domain/Hl7Admin.java
4789
//############################################################################# //# # //# 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.admin.domain; // Generated from form domain impl public interface Hl7Admin extends ims.domain.DomainInterface { // Generated from form domain interface definition public ims.admin.vo.HL7AdminVo getInboundInfo() throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public ims.admin.vo.HL7AdminVo getOutboundInfo() throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public void startInbound() throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public void stopInbound() throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public void startOutbound() throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public void stopOutbound() throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public ims.admin.vo.QryOrderMsgVoCollection listOrdersByDateTimeRange(ims.core.vo.PatientId patIdVo, ims.framework.utils.DateTime dtFrom, ims.framework.utils.DateTime dtTo); // Generated from form domain interface definition public void setInboundFlag(Boolean bStart) throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public void setOutboundFlag(Boolean bStart) throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public void clearOutboundRegistration(); // Generated from form domain interface definition public String getIpAddress() throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition /** * Returns a list of Outbound Feed records */ public ims.admin.vo.DemographicFeedVoCollection getOBFeedEntries(ims.framework.utils.DateTime startDate, ims.framework.utils.DateTime endDate, ims.core.vo.PatientId patientId, ims.core.vo.lookups.MsgEventType msgType, ims.core.admin.vo.ProviderSystemRefVo providerSystem); // Generated from form domain interface definition /** * Lists the Provider Systems */ public ims.ocrr.vo.ProviderSystemLiteVoCollection listProviderSystems(); // Generated from form domain interface definition /** * Saves a ConfigFlag */ public String saveConfigFlag(ims.configuration.IFlag flag, String flagValue) throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public ims.ocs_if.vo.OutboundTriggersVoCollection listOutboundTriggers(); // Generated from form domain interface definition public void saveOutBoundTriggers(ims.ocs_if.vo.OutboundTriggersVo outboundTriggers) throws ims.domain.exceptions.StaleObjectException; // Generated from form domain interface definition public void deleteOutBoundTriggers(ims.ocs_if.vo.OutboundTriggersVo outBoundTriggers) throws ims.domain.exceptions.ForeignKeyViolationException; }
agpl-3.0
aihua/opennms
features/events/syslog/src/test/java/org/opennms/netmgt/syslogd/SyslogMessageTest.java
22606
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2010-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.syslogd; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.opennms.core.test.ConfigurationTestUtils; import org.opennms.core.test.MockLogAppender; import org.opennms.core.time.ZonedDateTimeBuilder; import org.opennms.netmgt.config.SyslogdConfigFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SyslogMessageTest { private static final Logger LOG = LoggerFactory.getLogger(SyslogMessageTest.class); private final SyslogdConfigFactory m_config; public SyslogMessageTest() throws Exception { InputStream stream = null; try { stream = ConfigurationTestUtils.getInputStreamForResource(this, "/etc/syslogd-configuration.xml"); m_config = new SyslogdConfigFactory(stream); } finally { if (stream != null) { IOUtils.closeQuietly(stream); } } } @Before public void setUp() { MockLogAppender.setupLogging(true, "TRACE"); } @Test public void testCustomParserWithProcess() throws Exception { final SyslogParser parser = new CustomSyslogParser(m_config, SyslogdTestUtils.toByteBuffer("<6>test: 2007-01-01 127.0.0.1 OpenNMS[1234]: A SyslogNG style message")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); assertEquals(SyslogFacility.KERNEL, message.getFacility()); assertEquals(SyslogSeverity.INFORMATIONAL, message.getSeverity()); assertEquals("test", message.getMessageID()); assertEquals("127.0.0.1", message.getHostName()); assertEquals("OpenNMS", message.getProcessName()); assertEquals("1234", message.getProcessId()); assertEquals("A SyslogNG style message", message.getMessage()); } @Test public void testCustomParserWithSimpleForwardingRegexAndSyslog21Message() throws Exception { // see: http://searchdatacenter.techtarget.com/tip/Turn-aggregated-syslog-messages-into-OpenNMS-events final InputStream stream = new ByteArrayInputStream(("<syslogd-configuration>" + "<configuration " + "syslog-port=\"10514\" " + "new-suspect-on-message=\"false\" " + "forwarding-regexp=\"^((.+?) (.*))\\r?\\n?$\" " + "matching-group-host=\"2\" " + "matching-group-message=\"3\" " + "discard-uei=\"DISCARD-MATCHING-MESSAGES\" " + "/></syslogd-configuration>").getBytes()); final SyslogdConfigFactory config = new SyslogdConfigFactory(stream); final SyslogParser parser = new CustomSyslogParser(config, SyslogdTestUtils.toByteBuffer("<173>Dec 7 12:02:06 10.13.110.116 mgmtd[8326]: [mgmtd.NOTICE]: Configuration saved to database initial")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); final Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.YEAR, ZonedDateTimeBuilder.getBestYearForMonth(Month.DECEMBER.getValue())); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DATE, 7); calendar.set(Calendar.HOUR_OF_DAY, 12); calendar.set(Calendar.MINUTE, 2); calendar.set(Calendar.SECOND, 6); calendar.set(Calendar.MILLISECOND, 0); final Date date = calendar.getTime(); LOG.debug("got message: {}", message); assertEquals(SyslogFacility.LOCAL5, message.getFacility()); assertEquals(SyslogSeverity.NOTICE, message.getSeverity()); assertEquals(null, message.getMessageID()); assertEquals(date, message.getDate()); assertEquals("10.13.110.116", message.getHostName()); assertEquals("mgmtd", message.getProcessName()); assertEquals("8326", message.getProcessId()); assertEquals("[mgmtd.NOTICE]: Configuration saved to database initial", message.getMessage()); } @Test public void testCustomParserNms5242() throws Exception { final Locale startLocale = Locale.getDefault(); try { Locale.setDefault(Locale.FRANCE); final InputStream stream = new ByteArrayInputStream( ( "<?xml version=\"1.0\"?>\n" + "<syslogd-configuration>\n" + " <configuration\n" + " syslog-port=\"10514\"\n" + " new-suspect-on-message=\"false\"\n" + " parser=\"org.opennms.netmgt.syslogd.CustomSyslogParser\"\n" + " forwarding-regexp=\"^((.+?) (.*))\\n?$\"\n" + " matching-group-host=\"2\"\n" + " matching-group-message=\"3\"\n" + " discard-uei=\"DISCARD-MATCHING-MESSAGES\"\n" + " />\n" + "\n" + " <hideMessage>\n" + " <hideMatch>\n" + " <match type=\"substr\" expression=\"TEST\"/>\n" + " </hideMatch>\n" + " </hideMessage>\n" + "</syslogd-configuration>\n" ).getBytes() ); final SyslogdConfigFactory config = new SyslogdConfigFactory(stream); final SyslogParser parser = new CustomSyslogParser(config, SyslogdTestUtils.toByteBuffer("<0>Mar 14 17:10:25 petrus sudo: cyrille : user NOT in sudoers ; TTY=pts/2 ; PWD=/home/cyrille ; USER=root ; COMMAND=/usr/bin/vi /etc/aliases")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); LOG.debug("message = {}", message); final Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, ZonedDateTimeBuilder.getBestYearForMonth(Month.MARCH.getValue())); cal.set(Calendar.MONTH, Calendar.MARCH); cal.set(Calendar.DAY_OF_MONTH, 14); cal.set(Calendar.HOUR_OF_DAY, 17); cal.set(Calendar.MINUTE, 10); cal.set(Calendar.SECOND, 25); cal.set(Calendar.MILLISECOND, 0); assertEquals(SyslogFacility.KERNEL, message.getFacility()); assertEquals(SyslogSeverity.EMERGENCY, message.getSeverity()); assertNull(message.getMessageID()); assertEquals(cal.getTime(), message.getDate()); assertEquals("petrus", message.getHostName()); assertEquals("sudo", message.getProcessName()); assertEquals(null, message.getProcessId()); assertEquals("cyrille : user NOT in sudoers ; TTY=pts/2 ; PWD=/home/cyrille ; USER=root ; COMMAND=/usr/bin/vi /etc/aliases", message.getMessage()); } finally { Locale.setDefault(startLocale); } } @Test public void testSyslogNGParserWithProcess() throws Exception { final SyslogParser parser = new SyslogNGParser(m_config, SyslogdTestUtils.toByteBuffer("<6>test: 2007-01-01 127.0.0.1 OpenNMS[1234]: A SyslogNG style message")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); final Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.YEAR, 2007); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DATE, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.clear(Calendar.MINUTE); calendar.clear(Calendar.SECOND); calendar.clear(Calendar.MILLISECOND); final Date date = calendar.getTime(); assertEquals(SyslogFacility.KERNEL, message.getFacility()); assertEquals(SyslogSeverity.INFORMATIONAL, message.getSeverity()); assertEquals("test", message.getMessageID()); assertEquals(date, message.getDate()); assertEquals("127.0.0.1", message.getHostName()); assertEquals("OpenNMS", message.getProcessName()); assertEquals("1234", message.getProcessId()); assertEquals("A SyslogNG style message", message.getMessage()); } @Test public void testSyslogNGParserWithoutProcess() throws Exception { final SyslogParser parser = new SyslogNGParser(m_config, SyslogdTestUtils.toByteBuffer("<6>test: 2007-01-01 127.0.0.1 A SyslogNG style message")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); final Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.YEAR, 2007); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DATE, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.clear(Calendar.MINUTE); calendar.clear(Calendar.SECOND); calendar.clear(Calendar.MILLISECOND); final Date date = calendar.getTime(); assertEquals(SyslogFacility.KERNEL, message.getFacility()); assertEquals(SyslogSeverity.INFORMATIONAL, message.getSeverity()); assertEquals("test", message.getMessageID()); assertEquals(date, message.getDate()); assertEquals("127.0.0.1", message.getHostName()); assertEquals(null, message.getProcessName()); assertEquals(null, message.getProcessId()); assertEquals("A SyslogNG style message", message.getMessage()); } @Test public void testSyslogNGParserWithSyslog21Message() throws Exception { final SyslogParser parser = new SyslogNGParser(m_config, SyslogdTestUtils.toByteBuffer("<173>Dec 7 12:02:06 10.13.110.116 mgmtd[8326]: [mgmtd.NOTICE]: Configuration saved to database initial")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); final Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.YEAR, ZonedDateTimeBuilder.getBestYearForMonth(Month.DECEMBER.getValue())); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DATE, 7); calendar.set(Calendar.HOUR_OF_DAY, 12); calendar.set(Calendar.MINUTE, 2); calendar.set(Calendar.SECOND, 6); calendar.clear(Calendar.MILLISECOND); final Date date = calendar.getTime(); assertEquals(SyslogFacility.LOCAL5, message.getFacility()); assertEquals(SyslogSeverity.NOTICE, message.getSeverity()); assertEquals(null, message.getMessageID()); assertEquals(date, message.getDate()); assertEquals("10.13.110.116", message.getHostName()); assertEquals("mgmtd", message.getProcessName()); assertEquals("8326", message.getProcessId()); assertEquals("[mgmtd.NOTICE]: Configuration saved to database initial", message.getMessage()); } @Test public void testRfc5424ParserExample1() throws Exception { final SyslogParser parser = new Rfc5424SyslogParser(m_config, SyslogdTestUtils.toByteBuffer("<34>1 2003-10-11T22:14:15.000Z mymachine.example.com su - ID47 - 'su root' failed for lonvick on /dev/pts/8")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); final Date date = new Date(1065910455000L); assertEquals(1, message.getVersion().intValue()); assertEquals(SyslogFacility.AUTH, message.getFacility()); assertEquals(SyslogSeverity.CRITICAL, message.getSeverity()); assertEquals(date, message.getDate()); assertEquals("mymachine.example.com", message.getHostName()); assertEquals("su", message.getProcessName()); assertEquals("ID47", message.getMessageID()); assertEquals("'su root' failed for lonvick on /dev/pts/8", message.getMessage()); } @Test @Ignore("We cannot handle byte order mark (BOM) characters yet because we always decode the message buffer as US_ASCII in SyslogParser.fromByteBuffer()") public void testRfc5424ParserExampleWithByteOrderMark() throws Exception { final SyslogParser parser = new Rfc5424SyslogParser(m_config, SyslogdTestUtils.toByteBuffer("<34>1 2003-10-11T22:14:15.000Z mymachine.example.com su - ID47 - \uFEFF'su root' failed for lonvick on /dev/pts/8", StandardCharsets.UTF_16)); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); final Date date = new Date(1065910455000L); assertEquals(1, message.getVersion().intValue()); assertEquals(SyslogFacility.AUTH, message.getFacility()); assertEquals(SyslogSeverity.CRITICAL, message.getSeverity()); assertEquals(date, message.getDate()); assertEquals("mymachine.example.com", message.getHostName()); assertEquals("su", message.getProcessName()); assertEquals("ID47", message.getMessageID()); assertEquals("'su root' failed for lonvick on /dev/pts/8", message.getMessage()); } @Test public void testRfc5424ParserExample2() throws Exception { final SyslogParser parser = new Rfc5424SyslogParser(m_config, SyslogdTestUtils.toByteBuffer("<165>1 2003-10-11T22:14:15.000003-00:00 192.0.2.1 myproc 8710 - - %% It's time to make the do-nuts.")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); final Date date = new Date(1065910455003L); assertEquals(SyslogFacility.LOCAL4, message.getFacility()); assertEquals(SyslogSeverity.NOTICE, message.getSeverity()); assertEquals(1, message.getVersion().intValue()); assertEquals(date, message.getDate()); assertEquals("192.0.2.1", message.getHostName()); assertEquals("myproc", message.getProcessName()); assertEquals("8710", message.getProcessId()); assertEquals(null, message.getMessageID()); assertEquals("%% It's time to make the do-nuts.", message.getMessage()); } @Test public void testRfc5424ParserExample3() throws Exception { final SyslogParser parser = new Rfc5424SyslogParser(m_config, SyslogdTestUtils.toByteBuffer("<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut=\"3\" eventSource=\"Application\" eventID=\"1011\"] An application event log entry...")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); assertEquals(SyslogFacility.LOCAL4, message.getFacility()); assertEquals(SyslogSeverity.NOTICE, message.getSeverity()); assertEquals(1, message.getVersion().intValue()); assertEquals("mymachine.example.com", message.getHostName()); assertEquals("evntslog", message.getProcessName()); assertEquals(null, message.getProcessId()); assertEquals("ID47", message.getMessageID()); assertEquals("An application event log entry...", message.getMessage()); } @Test @Ignore("We cannot handle byte order mark (BOM) characters yet because we always decode the message buffer as US_ASCII in SyslogParser.fromByteBuffer()") public void testRfc5424ParserExampleWithStructuredDataAndByteOrderMark() throws Exception { final SyslogParser parser = new Rfc5424SyslogParser(m_config, SyslogdTestUtils.toByteBuffer("<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut=\"3\" eventSource=\"Application\" eventID=\"1011\"] \uFEFFAn application event log entry...", StandardCharsets.UTF_16)); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); assertEquals(SyslogFacility.LOCAL4, message.getFacility()); assertEquals(SyslogSeverity.NOTICE, message.getSeverity()); assertEquals(1, message.getVersion().intValue()); assertEquals("mymachine.example.com", message.getHostName()); assertEquals("evntslog", message.getProcessName()); assertEquals(null, message.getProcessId()); assertEquals("ID47", message.getMessageID()); assertEquals("An application event log entry...", message.getMessage()); } @Test public void testRfc5424ParserExample4() throws Exception { final SyslogParser parser = new Rfc5424SyslogParser(m_config, SyslogdTestUtils.toByteBuffer("<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut=\"3\" eventSource=\"Application\" eventID=\"1011\"][examplePriority@32473 class=\"high\"]")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); assertEquals(SyslogFacility.LOCAL4, message.getFacility()); assertEquals(SyslogSeverity.NOTICE, message.getSeverity()); assertEquals(1, message.getVersion().intValue()); assertEquals("mymachine.example.com", message.getHostName()); assertEquals("evntslog", message.getProcessName()); assertEquals(null, message.getProcessId()); assertEquals("ID47", message.getMessageID()); } @Test public void testRfc5424Nms5051() throws Exception { final SyslogParser parser = new Rfc5424SyslogParser(m_config, SyslogdTestUtils.toByteBuffer("<85>1 2011-11-15T14:42:18+01:00 hostname sudo - - - pam_unix(sudo:auth): authentication failure; logname=username uid=0 euid=0 tty=/dev/pts/0 ruser=username rhost= user=username")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); assertEquals(SyslogFacility.AUTHPRIV, message.getFacility()); assertEquals(SyslogSeverity.NOTICE, message.getSeverity()); assertEquals(1, message.getVersion().intValue()); assertEquals("hostname", message.getHostName()); assertEquals("sudo", message.getProcessName()); assertEquals(null, message.getProcessId()); assertEquals(null, message.getMessageID()); } @Test public void testJuniperCFMFault() throws Exception { final SyslogParser parser = new Rfc5424SyslogParser(m_config, SyslogdTestUtils.toByteBuffer("<27>1 2012-04-20T12:33:13.946Z junos-mx80-2-space cfmd 1317 CFMD_CCM_DEFECT_RMEP - CFM defect: Remote CCM timeout detected by MEP on Level: 6 MD: MD_service_level MA: PW_126 Interface: ge-1/3/2.1")); assertTrue(parser.find()); final SyslogMessage message = parser.parse(); assertNotNull(message); assertEquals(SyslogFacility.SYSTEM, message.getFacility()); assertEquals(SyslogSeverity.ERROR, message.getSeverity()); assertEquals("junos-mx80-2-space", message.getHostName()); assertEquals("cfmd", message.getProcessName()); assertEquals("1317", message.getProcessId()); assertEquals("CFMD_CCM_DEFECT_RMEP", message.getMessageID()); } @Test public void shouldHonorTimezoneWithConfiguredDefault() throws IOException { checkDateParserWith(TimeZone.getTimeZone("CET"), "timezone=\"CET\" "); } @Test public void shouldHonorTimezoneWithoutConfiguredDefault() throws IOException { checkDateParserWith(TimeZone.getDefault(), ""); } private void checkDateParserWith(TimeZone expectedTimeZone, String timezoneProperty) throws IOException { String configuration = "<syslogd-configuration>" + "<configuration " + "syslog-port=\"10514\" " + timezoneProperty + "/></syslogd-configuration>"; final InputStream stream = new ByteArrayInputStream((configuration).getBytes()); final SyslogdConfigFactory config = new SyslogdConfigFactory(stream); final SyslogParser parser = new SyslogParser(config, SyslogdTestUtils.toByteBuffer("something")); assertTrue(parser.find()); // Date Format 1: int currentYear = ZonedDateTime.now(expectedTimeZone.toZoneId()).getYear(); LocalDateTime expectedLocalDateTime = LocalDateTime.of(currentYear, 2, 3 , 12, 21, 20); ZonedDateTime expectedDateTime = ZonedDateTime.of(expectedLocalDateTime, expectedTimeZone.toZoneId()); Date parsedDate = parser.parseDate("Feb 03 12:21:20"); assertEquals(expectedDateTime.toInstant(), parsedDate.toInstant()); // Date Format 2: LocalDate expectedLocalDate = LocalDate.of(currentYear, 2, 3 ); expectedDateTime = expectedLocalDate.atStartOfDay(expectedTimeZone.toZoneId()); parsedDate = parser.parseDate(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(expectedDateTime)); assertEquals(expectedDateTime.toInstant(), parsedDate.toInstant()); } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/beans/InvestigationIndexListVoBean.java
3889
//############################################################################# //# # //# 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.ocrr.vo.beans; public class InvestigationIndexListVoBean extends ims.vo.ValueObjectBean { public InvestigationIndexListVoBean() { } public InvestigationIndexListVoBean(ims.ocrr.vo.InvestigationIndexListVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.name = vo.getName(); this.category = vo.getCategory() == null ? null : (ims.vo.LookupInstanceBean)vo.getCategory().getBean(); this.nointerface = vo.getNoInterface(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.ocrr.vo.InvestigationIndexListVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.name = vo.getName(); this.category = vo.getCategory() == null ? null : (ims.vo.LookupInstanceBean)vo.getCategory().getBean(); this.nointerface = vo.getNoInterface(); } public ims.ocrr.vo.InvestigationIndexListVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.ocrr.vo.InvestigationIndexListVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.ocrr.vo.InvestigationIndexListVo vo = null; if(map != null) vo = (ims.ocrr.vo.InvestigationIndexListVo)map.getValueObject(this); if(vo == null) { vo = new ims.ocrr.vo.InvestigationIndexListVo(); 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 String getName() { return this.name; } public void setName(String value) { this.name = value; } public ims.vo.LookupInstanceBean getCategory() { return this.category; } public void setCategory(ims.vo.LookupInstanceBean value) { this.category = value; } public Boolean getNoInterface() { return this.nointerface; } public void setNoInterface(Boolean value) { this.nointerface = value; } private Integer id; private int version; private String name; private ims.vo.LookupInstanceBean category; private Boolean nointerface; }
agpl-3.0
mitechie/juju-gui
jujugui/static/gui/src/app/components/help/tour/tour.js
5639
/* Copyright (C) 2017 Canonical Ltd. */ 'use strict'; const PropTypes = require('prop-types'); const React = require('react'); const Lightbox = require('../../lightbox/lightbox'); const SvgIcon = require('../../svg-icon/svg-icon'); class Tour extends React.PureComponent { render() { const staticURL = this.props.staticURL; const basePath = `${staticURL}/static/gui/build/app/assets/images/non-sprites/tour`; return ( <div> <span className="back-to-help" onClick={this.props.endTour.bind(this)}> <SvgIcon className="back-to-help__icon" name="chevron_down_16" size="16" /> Back to GUI help </span> <Lightbox close={this.props.close.bind(this)} extraClasses={['tour']}> <div className="tour__slide"> <img className="tour__slide-image" src={`${basePath}/welcome@1x.png`} srcSet={`${basePath}/welcome@2x.png 2x`} /> <div className="tour__slide-description clearfix"> <p className="ten-col"> Welcome to JAAS. You've arrived at the empty canvas. Click on the green button to visit the store and start building your application. </p> </div> </div> <div className="tour__slide"> <img className="tour__slide-image" sizes="(max-width: 768px) 347w" src={`${basePath}/store@1x.png`} srcSet={` ${basePath}/store@2x.png 2x, ${basePath}/store-mobile@1x.png 347w, `} /> <div className="tour__slide-description clearfix"> <p className="ten-col"> Browse the store to find charms for the applications you use and pre-configured bundles that build the solutions you need. </p> </div> </div> <div className="tour__slide"> <img className="tour__slide-image" sizes="(max-width: 768px) 335w" src={`${basePath}/relations@1x.png`} srcSet={` ${basePath}/relations@2x.png 2x, ${basePath}/relations-mobile@1x.png 335w, `} /> <div className="tour__slide-description clearfix"> <p className="ten-col"> Juju relations allow individual applications to share information, request resources, and coordinate operations. To create one, select one of the applications and grab the 'connect' symbol that appears above it. Then drag it to the other applications to make the relation. </p> </div> </div> <div className="tour__slide"> <img className="tour__slide-image" sizes="(max-width: 768px) 307w" src={`${basePath}/inspector@1x.png`} srcSet={` ${basePath}/inspector@2x.png 2x, ${basePath}/inspector-mobile@1x.png 307w, `} /> <div className="tour__slide-description clearfix"> <p className="ten-col"> The inspector shows a list of all the applications in your model. Use it to scale, expose, and configure your applications. </p> </div> </div> <div className="tour__slide"> <img className="tour__slide-image" sizes="(max-width: 768px) 431w" src={`${basePath}/machine-app-view@1x.png`} srcSet={` ${basePath}/machine-app-view@2x.png 2x, ${basePath}/machine-app-view-mobile@1x.png 431w, `} /> <div className="tour__slide-description clearfix"> <p className="ten-col"> Use the inspector to switch between application view, where you can see a visual representation of your workload, and machine view, where you can see and manage all of the instances your model is using. </p> </div> </div> <div className="tour__slide"> <img className="tour__slide-image" sizes="(max-width: 768px) 341w" src={`${basePath}/deploy@1x.png`} srcSet={` ${basePath}/deploy@2x.png 2x, ${basePath}/deploy-mobile@1x.png 341w, `} /> <div className="tour__slide-description clearfix"> <p className="ten-col"> Ready to deploy your workload? Click the blue Deploy button shown on the bottom right. </p> </div> </div> <div className="tour__slide"> <img className="tour__slide-image" sizes="(max-width: 768px) 375w" src={`${basePath}/post-deploy@1x.png`} srcSet={` ${basePath}/post-deploy@2x.png 2x, ${basePath}/post-deploy-mobile@1x.png 375w, `} /> <div className="tour__slide-description clearfix"> <p className="ten-col"> Creating instances, deploying applications, and performing configuration can sometimes take several minutes. Pending units are outlined in <span className="u-pending">orange</span> &mdash; These are still in progress. Your model will be fully up and running once all application icons are outlined in gery. </p> </div> </div> </Lightbox> </div> ); } } Tour.propTypes = { close: PropTypes.func.isRequired, endTour: PropTypes.func, staticURL: PropTypes.string.isRequired }; module.exports = Tour;
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Correspondence/src/ims/correspondence/forms/glossarydialog/IFormUILogicCode.java
2215
//############################################################################# //# # //# 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.correspondence.forms.glossarydialog; public interface IFormUILogicCode { // No methods yet. }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Therapies/src/ims/therapies/forms/adaptations/Handlers.java
8828
//############################################################################# //# # //# 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.therapies.forms.adaptations; import ims.framework.delegates.*; abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode { abstract protected void bindcomboBoxSupplierLookup(); abstract protected void defaultcomboBoxSupplierLookupValue(); abstract protected void bindcomboBoxLoanLookup(); abstract protected void defaultcomboBoxLoanLookupValue(); abstract protected void bindcomboBoxSuppliedForLookup(); abstract protected void defaultcomboBoxSuppliedForLookupValue(); abstract protected void bindcomboBoxFundedLookup(); abstract protected void defaultcomboBoxFundedLookupValue(); abstract protected void bindgrdListColSupplierLookup(); abstract protected void bindgrdListColSuppliedforLookup(); abstract protected void bindgrdListColLoanLookup(); abstract protected void onFormModeChanged(); abstract protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException; abstract protected void oncomboBoxSupplierValueSet(Object value); abstract protected void onComboBoxAdapt1ValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void oncomboBoxLoanValueSet(Object value); abstract protected void oncomboBoxSuppliedForValueSet(Object value); abstract protected void oncomboBoxFundedValueSet(Object value); abstract protected void onBtnUpdateClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onGrdListSelectionChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onContextMenuItemClick(int menuItemID, ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException; public final void setContext(ims.framework.UIEngine engine, GenForm form) { this.engine = engine; this.form = form; this.form.setFormModeChangedEvent(new FormModeChanged() { private static final long serialVersionUID = 1L; public void handle() { onFormModeChanged(); } }); this.form.setFormOpenEvent(new FormOpen() { private static final long serialVersionUID = 1L; public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException { bindLookups(); onFormOpen(); } }); this.form.ctnDetail().comboBoxSupplier().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncomboBoxSupplierValueSet(value); } }); this.form.ctnDetail().comboBoxAdapt1().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onComboBoxAdapt1ValueChanged(); } }); this.form.ctnDetail().comboBoxLoan().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncomboBoxLoanValueSet(value); } }); this.form.ctnDetail().comboBoxSuppliedFor().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncomboBoxSuppliedForValueSet(value); } }); this.form.ctnDetail().comboBoxFunded().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncomboBoxFundedValueSet(value); } }); this.form.btnUpdate().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnUpdateClick(); } }); this.form.btnNew().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnNewClick(); } }); this.form.btnSave().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnSaveClick(); } }); this.form.btnCancel().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnCancelClick(); } }); this.form.grdList().setSelectionChangedEvent(new GridSelectionChanged() { private static final long serialVersionUID = 1L; public void handle(ims.framework.enumerations.MouseButton mouseButton) throws ims.framework.exceptions.PresentationLogicException { onGrdListSelectionChanged(); } }); this.form.getContextMenus().getLIPNewItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LIP.New, sender); } }); this.form.getContextMenus().getLIPUpdateItem().setClickEvent(new ims.framework.delegates.MenuItemClick() { private static final long serialVersionUID = 1L; public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException { onContextMenuItemClick(GenForm.ContextMenus.LIP.Update, sender); } }); } protected void bindLookups() { bindcomboBoxSupplierLookup(); bindcomboBoxLoanLookup(); bindcomboBoxSuppliedForLookup(); bindcomboBoxFundedLookup(); bindgrdListColSupplierLookup(); bindgrdListColSuppliedforLookup(); bindgrdListColLoanLookup(); } protected void rebindAllLookups() { bindcomboBoxSupplierLookup(); bindcomboBoxLoanLookup(); bindcomboBoxSuppliedForLookup(); bindcomboBoxFundedLookup(); bindgrdListColSupplierLookup(); bindgrdListColSuppliedforLookup(); bindgrdListColLoanLookup(); } protected void defaultAllLookupValues() { defaultcomboBoxSupplierLookupValue(); defaultcomboBoxLoanLookupValue(); defaultcomboBoxSuppliedForLookupValue(); defaultcomboBoxFundedLookupValue(); } public void free() { this.engine = null; this.form = null; } protected ims.framework.UIEngine engine; protected GenForm form; }
agpl-3.0
enjaz/enjaz
clubs/migrations/0001_initial.py
6392
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Club', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200, verbose_name='\u0627\u0644\u0627\u0633\u0645')), ('english_name', models.CharField(max_length=200, verbose_name='\u0627\u0644\u0627\u0633\u0645 \u0627\u0644\u0625\u0646\u062c\u0644\u064a\u0632\u064a')), ('description', models.TextField(verbose_name='\u0627\u0644\u0648\u0635\u0641')), ('email', models.EmailField(max_length=254, verbose_name='\u0627\u0644\u0628\u0631\u064a\u062f \u0627\u0644\u0625\u0644\u0643\u062a\u0631\u0648\u0646\u064a')), ('creation_date', models.DateTimeField(auto_now_add=True, verbose_name='\u062a\u0627\u0631\u064a\u062e \u0627\u0644\u0625\u0646\u0634\u0627\u0621')), ('edit_date', models.DateTimeField(auto_now=True, verbose_name='\u062a\u0627\u0631\u064a\u062e \u0627\u0644\u062a\u0639\u062f\u064a\u0644')), ('special', models.BooleanField(default=False, verbose_name='\u0646\u0627\u062f\u064a \u0645\u0645\u064a\u0632\u061f')), ('city', models.CharField(max_length=1, verbose_name='\u0627\u0644\u0645\u062f\u064a\u0646\u0629', choices=[(b'R', '\u0627\u0644\u0631\u064a\u0627\u0636'), (b'J', '\u062c\u062f\u0629'), (b'A', '\u0627\u0644\u0623\u062d\u0633\u0627\u0621')])), ], options={ 'verbose_name': '\u0646\u0627\u062f\u064a', 'verbose_name_plural': '\u0627\u0644\u0623\u0646\u062f\u064a\u0629', 'permissions': (('view_members', 'Can view club members list.'),), }, bases=(models.Model,), ), migrations.CreateModel( name='College', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('section', models.CharField(max_length=2, verbose_name='\u0627\u0644\u0642\u0633\u0645', choices=[(b'NG', '\u0627\u0644\u062d\u0631\u0633 \u0627\u0644\u0648\u0637\u0646\u064a'), (b'KF', '\u0645\u062f\u064a\u0646\u0629 \u0627\u0644\u0645\u0644\u0643 \u0641\u0647\u062f \u0627\u0644\u0637\u0628\u064a\u0629')])), ('name', models.CharField(max_length=1, verbose_name='\u0627\u0644\u0627\u0633\u0645', choices=[(b'M', '\u0643\u0644\u064a\u0629 \u0627\u0644\u0637\u0628'), (b'A', '\u0643\u0644\u064a\u0629 \u0627\u0644\u0639\u0644\u0648\u0645 \u0627\u0644\u0637\u0628\u064a\u0629 \u0627\u0644\u062a\u0637\u0628\u064a\u0642\u064a\u0629'), (b'P', '\u0643\u0644\u064a\u0629 \u0627\u0644\u0635\u064a\u062f\u0644\u0629'), (b'D', '\u0643\u0644\u064a\u0629 \u0637\u0628 \u0627\u0644\u0623\u0633\u0646\u0627\u0646'), (b'B', '\u0643\u0644\u064a\u0629 \u0627\u0644\u0639\u0644\u0648\u0645 \u0648 \u0627\u0644\u0645\u0647\u0646 \u0627\u0644\u0635\u062d\u064a\u0629'), (b'N', '\u0643\u0644\u064a\u0629 \u0627\u0644\u062a\u0645\u0631\u064a\u0636'), (b'I', ' \u0643\u0644\u064a\u0629 \u0627\u0644\u0635\u062d\u0629 \u0627\u0644\u0639\u0627\u0645\u0629 \u0648\u0627\u0644\u0645\u0639\u0644\u0648\u0645\u0627\u062a\u064a\u0629 \u0627\u0644\u0635\u062d\u064a\u0629')])), ('city', models.CharField(max_length=1, verbose_name='\u0627\u0644\u0645\u062f\u064a\u0646\u0629', choices=[(b'R', '\u0627\u0644\u0631\u064a\u0627\u0636'), (b'J', '\u062c\u062f\u0629'), (b'A', '\u0627\u0644\u0623\u062d\u0633\u0627\u0621')])), ('gender', models.CharField(max_length=1, verbose_name='\u0627\u0644\u062c\u0646\u0633', choices=[(b'F', '\u0637\u0627\u0644\u0628\u0627\u062a'), (b'M', '\u0637\u0644\u0627\u0628')])), ], options={ 'verbose_name': '\u0643\u0644\u064a\u0629', 'verbose_name_plural': '\u0627\u0644\u0643\u0644\u064a\u0627\u062a', }, bases=(models.Model,), ), migrations.AddField( model_name='club', name='college', field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, default=None, blank=True, to='clubs.College', null=True, verbose_name='\u0627\u0644\u0643\u0644\u064a\u0629'), preserve_default=True, ), migrations.AddField( model_name='club', name='coordinator', field=models.ForeignKey(related_name='coordination', on_delete=django.db.models.deletion.SET_NULL, verbose_name='\u0627\u0644\u0645\u0646\u0633\u0642', blank=True, to=settings.AUTH_USER_MODEL, null=True), preserve_default=True, ), migrations.AddField( model_name='club', name='deputies', field=models.ManyToManyField(related_name='deputyships', null=True, verbose_name='\u0627\u0644\u0646\u0648\u0627\u0628', to=settings.AUTH_USER_MODEL, blank=True), preserve_default=True, ), migrations.AddField( model_name='club', name='employee', field=models.ForeignKey(related_name='employee', on_delete=django.db.models.deletion.SET_NULL, default=None, blank=True, to=settings.AUTH_USER_MODEL, null=True, verbose_name='\u0627\u0644\u0645\u0648\u0638\u0641 \u0627\u0644\u0645\u0633\u0624\u0648\u0644'), preserve_default=True, ), migrations.AddField( model_name='club', name='members', field=models.ManyToManyField(related_name='memberships', null=True, verbose_name='\u0627\u0644\u0623\u0639\u0636\u0627\u0621', to=settings.AUTH_USER_MODEL, blank=True), preserve_default=True, ), migrations.AddField( model_name='club', name='parent', field=models.ForeignKey(related_name='parenthood', on_delete=django.db.models.deletion.SET_NULL, default=None, blank=True, to='clubs.Club', null=True, verbose_name='\u0627\u0644\u0646\u0627\u062f\u064a \u0627\u0644\u0623\u0628'), preserve_default=True, ), ]
agpl-3.0
armlfs/XiuzLegends
src/net/sf/odinms/server/MapleShop.java
10034
package net.sf.odinms.server; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import net.sf.odinms.client.IItem; import net.sf.odinms.client.Item; import net.sf.odinms.client.MapleClient; import net.sf.odinms.client.MapleInventoryType; import net.sf.odinms.client.MaplePet; import net.sf.odinms.database.DatabaseConnection; import net.sf.odinms.net.PacketProcessor; import net.sf.odinms.tools.MaplePacketCreator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MapleShop { private static final Set<Integer> rechargeableItems = new LinkedHashSet<Integer>(); private int id; private int npcId; private List<MapleShopItem> items; private int tokenvalue = 1000000000; private int token = 4000313; private static Logger log = LoggerFactory.getLogger(PacketProcessor.class); static { for (int i = 2070000; i <= 2070018; i++) { rechargeableItems.add(i); } rechargeableItems.add(2331000);//Blaze Capsule rechargeableItems.add(2332000);//Glaze Capsule rechargeableItems.remove(2070014); rechargeableItems.remove(2070017); for (int i = 2330000; i <= 2330005; i++) { rechargeableItems.add(i); } } private MapleShop(int id, int npcId) { this.id = id; this.npcId = npcId; items = new LinkedList<MapleShopItem>(); } public void addItem(MapleShopItem item) { items.add(item); } public void sendShop(MapleClient c) { c.getPlayer().setShop(this); c.getSession().write(MaplePacketCreator.getNPCShop(c, getNpcId(), items)); } public void buy(MapleClient c, int itemId, short quantity) { MapleShopItem item = findById(itemId); MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance(); if (item != null && item.getPrice() > 0) { if (c.getPlayer().getMeso() >= item.getPrice() * quantity) { if (MapleInventoryManipulator.checkSpace(c, itemId, quantity, "")) { if (!ii.isRechargable(itemId)) { if (itemId >= 5000000 && itemId <= 5000100) { int petId = MaplePet.createPet(itemId); MapleInventoryManipulator.addById(c, petId, quantity, "Pet was purchased."); } else { MapleInventoryManipulator.addById(c, itemId, quantity); } c.getPlayer().gainMeso(-(item.getPrice() * quantity), false); } else { short slotMax = ii.getSlotMax(c, item.getItemId()); quantity = slotMax; MapleInventoryManipulator.addById(c, itemId, quantity, "Rechargable item purchased."); c.getPlayer().gainMeso(-(item.getPrice()), false); } } else { c.getSession().write(MaplePacketCreator.serverNotice(1, "Your Inventory is full")); } c.getSession().write(MaplePacketCreator.confirmShopTransaction((byte) 0)); } else { if (c.getPlayer().getInventory(MapleInventoryType.CASH).countById(token) != 0) { int amount = c.getPlayer().getInventory(MapleInventoryType.CASH).countById(token); int value = amount * tokenvalue; int cost = item.getPrice() * quantity; if (c.getPlayer().getMeso() + value >= cost) { int cardreduce = value - cost; int diff = cardreduce + c.getPlayer().getMeso(); if (MapleInventoryManipulator.checkSpace(c, itemId, quantity, "")) { if (itemId >= 5000000 && itemId <= 5000100) { int petId = MaplePet.createPet(itemId); MapleInventoryManipulator.addById(c, petId, quantity, "Pet was purchased."); } else { MapleInventoryManipulator.addById(c, itemId, quantity); } c.getPlayer().gainMeso(diff, false); } else { c.getSession().write(MaplePacketCreator.serverNotice(1, "Your Inventory is full")); } c.getSession().write(MaplePacketCreator.confirmShopTransaction((byte) 0)); } } } } } public void sell(MapleClient c, MapleInventoryType type, byte slot, short quantity) { if (quantity == 0xFFFF || quantity == 0) { quantity = 1; } MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance(); IItem item = c.getPlayer().getInventory(type).getItem(slot); if (ii.isThrowingStar(item.getItemId()) || ii.isBullet(item.getItemId())) { quantity = item.getQuantity(); } if (quantity < 0) { return; } short iQuant = item.getQuantity(); if (iQuant == 0xFFFF) { iQuant = 1; } if (quantity <= iQuant && iQuant > 0) { MapleInventoryManipulator.removeFromSlot(c, type, slot, quantity, false); double price; if (ii.isThrowingStar(item.getItemId()) || ii.isBullet(item.getItemId())) { price = ii.getWholePrice(item.getItemId()) / (double) ii.getSlotMax(c, item.getItemId()); } else { price = ii.getPrice(item.getItemId()); } int recvMesos = (int) Math.max(Math.ceil(price * quantity), 0); if (price != -1 && recvMesos > 0) { c.getPlayer().gainMeso(recvMesos, false); } c.getSession().write(MaplePacketCreator.confirmShopTransaction((byte) 0x8)); } } public void recharge(MapleClient c, byte slot) { MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance(); IItem item = c.getPlayer().getInventory(MapleInventoryType.USE).getItem(slot); if (item == null || (!ii.isThrowingStar(item.getItemId()) && !ii.isBullet(item.getItemId()))) { if (item != null && (!ii.isThrowingStar(item.getItemId()) || !ii.isBullet(item.getItemId()))) { log.warn(c.getPlayer().getName() + " is trying to recharge " + item.getItemId()); } return; } short slotMax = ii.getSlotMax(c, item.getItemId()); if (item.getQuantity() < 0) { log.warn(c.getPlayer().getName() + " is trying to recharge " + item.getItemId() + " with quantity " + item.getQuantity()); } if (item.getQuantity() < slotMax) { int price = (int) Math.round(ii.getPrice(item.getItemId()) * (slotMax - item.getQuantity())); if (c.getPlayer().getMeso() >= price) { item.setQuantity(slotMax); c.getSession().write(MaplePacketCreator.updateInventorySlot(MapleInventoryType.USE, (Item) item)); c.getPlayer().gainMeso(-price, false, true, false); c.getSession().write(MaplePacketCreator.confirmShopTransaction((byte) 0x8)); } } } protected MapleShopItem findById(int itemId) { for (MapleShopItem item : items) { if (item.getItemId() == itemId) { return item; } } return null; } public static MapleShop createFromDB(int id, boolean isShopId) { MapleShop ret = null; MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance(); int shopId; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps; if (isShopId) { ps = con.prepareStatement("SELECT * FROM shops WHERE shopid = ?"); } else { ps = con.prepareStatement("SELECT * FROM shops WHERE npcid = ?"); } ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { shopId = rs.getInt("shopid"); ret = new MapleShop(shopId, rs.getInt("npcid")); rs.close(); ps.close(); } else { rs.close(); ps.close(); return null; } ps = con.prepareStatement("SELECT * FROM shopitems WHERE shopid = ? ORDER BY position ASC"); ps.setInt(1, shopId); rs = ps.executeQuery(); List<Integer> recharges = new ArrayList<Integer>(rechargeableItems); while (rs.next()) { if (ii.isThrowingStar(rs.getInt("itemid")) || ii.isBullet(rs.getInt("itemid"))) { MapleShopItem starItem = new MapleShopItem((short) 1, rs.getInt("itemid"), rs.getInt("price")); ret.addItem(starItem); if (rechargeableItems.contains(starItem.getItemId())) { recharges.remove(Integer.valueOf(starItem.getItemId())); } } else { ret.addItem(new MapleShopItem((short) 1000, rs.getInt("itemid"), rs.getInt("price"))); } } for (Integer recharge : recharges) { ret.addItem(new MapleShopItem((short) 1000, recharge.intValue(), 0)); } rs.close(); ps.close(); } catch (SQLException e) { log.error("Could not load shop", e); } return ret; } public int getNpcId() { return npcId; } public int getId() { return id; } }
agpl-3.0
freyes/juju
worker/raft/raftclusterer/manifold.go
1132
// Copyright 2018 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package raftclusterer import ( "github.com/hashicorp/raft" "github.com/juju/errors" "github.com/juju/pubsub/v2" "github.com/juju/worker/v2" "github.com/juju/worker/v2/dependency" ) // ManifoldConfig holds the information necessary to run a worker for // maintaining the raft cluster configuration in a dependency.Engine. type ManifoldConfig struct { RaftName string CentralHubName string NewWorker func(Config) (worker.Worker, error) } func (config ManifoldConfig) start(context dependency.Context) (worker.Worker, error) { var r *raft.Raft if err := context.Get(config.RaftName, &r); err != nil { return nil, errors.Trace(err) } var hub *pubsub.StructuredHub if err := context.Get(config.CentralHubName, &hub); err != nil { return nil, errors.Trace(err) } return config.NewWorker(Config{ Raft: r, Hub: hub, }) } func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.RaftName, config.CentralHubName, }, Start: config.start, } }
agpl-3.0
scalien/keyspace
src/Application/Keyspace/Client/Java/keyspace_client.java
10921
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.31 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.scalien.keyspace; public class keyspace_client { public static long imaxabs(long n) { return keyspace_clientJNI.imaxabs(n); } public static imaxdiv_t imaxdiv(long numer, long denom) { return new imaxdiv_t(keyspace_clientJNI.imaxdiv(numer, denom), true); } public static long strtoimax(String nptr, SWIGTYPE_p_p_char endptr, int base) { return keyspace_clientJNI.strtoimax(nptr, SWIGTYPE_p_p_char.getCPtr(endptr), base); } public static java.math.BigInteger strtoumax(String nptr, SWIGTYPE_p_p_char endptr, int base) { return keyspace_clientJNI.strtoumax(nptr, SWIGTYPE_p_p_char.getCPtr(endptr), base); } public static void Keyspace_ResultBegin(SWIGTYPE_p_void result) { keyspace_clientJNI.Keyspace_ResultBegin(SWIGTYPE_p_void.getCPtr(result)); } public static void Keyspace_ResultNext(SWIGTYPE_p_void result) { keyspace_clientJNI.Keyspace_ResultNext(SWIGTYPE_p_void.getCPtr(result)); } public static boolean Keyspace_ResultIsEnd(SWIGTYPE_p_void result) { return keyspace_clientJNI.Keyspace_ResultIsEnd(SWIGTYPE_p_void.getCPtr(result)); } public static void Keyspace_ResultClose(SWIGTYPE_p_void result) { keyspace_clientJNI.Keyspace_ResultClose(SWIGTYPE_p_void.getCPtr(result)); } public static String Keyspace_ResultKey(SWIGTYPE_p_void result) { return keyspace_clientJNI.Keyspace_ResultKey(SWIGTYPE_p_void.getCPtr(result)); } public static String Keyspace_ResultValue(SWIGTYPE_p_void result) { return keyspace_clientJNI.Keyspace_ResultValue(SWIGTYPE_p_void.getCPtr(result)); } public static int Keyspace_ResultTransportStatus(SWIGTYPE_p_void result) { return keyspace_clientJNI.Keyspace_ResultTransportStatus(SWIGTYPE_p_void.getCPtr(result)); } public static int Keyspace_ResultConnectivityStatus(SWIGTYPE_p_void result) { return keyspace_clientJNI.Keyspace_ResultConnectivityStatus(SWIGTYPE_p_void.getCPtr(result)); } public static int Keyspace_ResultTimeoutStatus(SWIGTYPE_p_void result) { return keyspace_clientJNI.Keyspace_ResultTimeoutStatus(SWIGTYPE_p_void.getCPtr(result)); } public static int Keyspace_ResultCommandStatus(SWIGTYPE_p_void result) { return keyspace_clientJNI.Keyspace_ResultCommandStatus(SWIGTYPE_p_void.getCPtr(result)); } public static SWIGTYPE_p_void Keyspace_Create() { long cPtr = keyspace_clientJNI.Keyspace_Create(); return (cPtr == 0) ? null : new SWIGTYPE_p_void(cPtr, false); } public static int Keyspace_Init(SWIGTYPE_p_void client, Keyspace_NodeParams params) { return keyspace_clientJNI.Keyspace_Init(SWIGTYPE_p_void.getCPtr(client), Keyspace_NodeParams.getCPtr(params), params); } public static void Keyspace_Destroy(SWIGTYPE_p_void client) { keyspace_clientJNI.Keyspace_Destroy(SWIGTYPE_p_void.getCPtr(client)); } public static SWIGTYPE_p_void Keyspace_GetResult(SWIGTYPE_p_void arg0) { long cPtr = keyspace_clientJNI.Keyspace_GetResult(SWIGTYPE_p_void.getCPtr(arg0)); return (cPtr == 0) ? null : new SWIGTYPE_p_void(cPtr, false); } public static void Keyspace_SetGlobalTimeout(SWIGTYPE_p_void client, java.math.BigInteger timeout) { keyspace_clientJNI.Keyspace_SetGlobalTimeout(SWIGTYPE_p_void.getCPtr(client), timeout); } public static void Keyspace_SetMasterTimeout(SWIGTYPE_p_void client, java.math.BigInteger timeout) { keyspace_clientJNI.Keyspace_SetMasterTimeout(SWIGTYPE_p_void.getCPtr(client), timeout); } public static java.math.BigInteger Keyspace_GetGlobalTimeout(SWIGTYPE_p_void client) { return keyspace_clientJNI.Keyspace_GetGlobalTimeout(SWIGTYPE_p_void.getCPtr(client)); } public static java.math.BigInteger Keyspace_GetMasterTimeout(SWIGTYPE_p_void client) { return keyspace_clientJNI.Keyspace_GetMasterTimeout(SWIGTYPE_p_void.getCPtr(client)); } public static int Keyspace_GetMaster(SWIGTYPE_p_void client) { return keyspace_clientJNI.Keyspace_GetMaster(SWIGTYPE_p_void.getCPtr(client)); } public static void Keyspace_DistributeDirty(SWIGTYPE_p_void client, boolean dd) { keyspace_clientJNI.Keyspace_DistributeDirty(SWIGTYPE_p_void.getCPtr(client), dd); } public static int Keyspace_Get(SWIGTYPE_p_void client, String key) { return keyspace_clientJNI.Keyspace_Get(SWIGTYPE_p_void.getCPtr(client), key); } public static int Keyspace_DirtyGet(SWIGTYPE_p_void client, String key) { return keyspace_clientJNI.Keyspace_DirtyGet(SWIGTYPE_p_void.getCPtr(client), key); } public static int Keyspace_Count(SWIGTYPE_p_void client, String prefix, String startKey, java.math.BigInteger count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_Count(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_CountStr(SWIGTYPE_p_void client, String prefix, String startKey, String count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_CountStr(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_DirtyCount(SWIGTYPE_p_void client, String prefix, String startKey, java.math.BigInteger count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_DirtyCount(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_DirtyCountStr(SWIGTYPE_p_void client, String prefix, String startKey, String count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_DirtyCountStr(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_ListKeys(SWIGTYPE_p_void client, String prefix, String startKey, java.math.BigInteger count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_ListKeys(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_ListKeysStr(SWIGTYPE_p_void client, String prefix, String startKey, String count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_ListKeysStr(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_DirtyListKeys(SWIGTYPE_p_void client, String prefix, String startKey, java.math.BigInteger count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_DirtyListKeys(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_DirtyListKeysStr(SWIGTYPE_p_void client, String prefix, String startKey, String count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_DirtyListKeysStr(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_ListKeyValues(SWIGTYPE_p_void client, String prefix, String startKey, java.math.BigInteger count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_ListKeyValues(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_ListKeyValuesStr(SWIGTYPE_p_void client, String prefix, String startKey, String count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_ListKeyValuesStr(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_DirtyListKeyValues(SWIGTYPE_p_void client, String prefix, String startKey, java.math.BigInteger count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_DirtyListKeyValues(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_DirtyListKeyValuesStr(SWIGTYPE_p_void client, String prefix, String startKey, String count, boolean next, boolean forward) { return keyspace_clientJNI.Keyspace_DirtyListKeyValuesStr(SWIGTYPE_p_void.getCPtr(client), prefix, startKey, count, next, forward); } public static int Keyspace_Set(SWIGTYPE_p_void client, String key, String value) { return keyspace_clientJNI.Keyspace_Set(SWIGTYPE_p_void.getCPtr(client), key, value); } public static int Keyspace_TestAndSet(SWIGTYPE_p_void client, String key, String test, String value) { return keyspace_clientJNI.Keyspace_TestAndSet(SWIGTYPE_p_void.getCPtr(client), key, test, value); } public static int Keyspace_Add(SWIGTYPE_p_void client, String key, long num) { return keyspace_clientJNI.Keyspace_Add(SWIGTYPE_p_void.getCPtr(client), key, num); } public static int Keyspace_AddStr(SWIGTYPE_p_void client, String key, String num) { return keyspace_clientJNI.Keyspace_AddStr(SWIGTYPE_p_void.getCPtr(client), key, num); } public static int Keyspace_Delete(SWIGTYPE_p_void client, String key) { return keyspace_clientJNI.Keyspace_Delete(SWIGTYPE_p_void.getCPtr(client), key); } public static int Keyspace_Remove(SWIGTYPE_p_void client, String key) { return keyspace_clientJNI.Keyspace_Remove(SWIGTYPE_p_void.getCPtr(client), key); } public static int Keyspace_Rename(SWIGTYPE_p_void client, String from, String to) { return keyspace_clientJNI.Keyspace_Rename(SWIGTYPE_p_void.getCPtr(client), from, to); } public static int Keyspace_Prune(SWIGTYPE_p_void client, String prefix) { return keyspace_clientJNI.Keyspace_Prune(SWIGTYPE_p_void.getCPtr(client), prefix); } public static int Keyspace_SetExpiry(SWIGTYPE_p_void client, String key, int exptime) { return keyspace_clientJNI.Keyspace_SetExpiry(SWIGTYPE_p_void.getCPtr(client), key, exptime); } public static int Keyspace_RemoveExpiry(SWIGTYPE_p_void client, String key) { return keyspace_clientJNI.Keyspace_RemoveExpiry(SWIGTYPE_p_void.getCPtr(client), key); } public static int Keyspace_ClearExpiries(SWIGTYPE_p_void client) { return keyspace_clientJNI.Keyspace_ClearExpiries(SWIGTYPE_p_void.getCPtr(client)); } public static int Keyspace_Begin(SWIGTYPE_p_void client) { return keyspace_clientJNI.Keyspace_Begin(SWIGTYPE_p_void.getCPtr(client)); } public static int Keyspace_Submit(SWIGTYPE_p_void client) { return keyspace_clientJNI.Keyspace_Submit(SWIGTYPE_p_void.getCPtr(client)); } public static int Keyspace_Cancel(SWIGTYPE_p_void client) { return keyspace_clientJNI.Keyspace_Cancel(SWIGTYPE_p_void.getCPtr(client)); } public static boolean Keyspace_IsBatched(SWIGTYPE_p_void client) { return keyspace_clientJNI.Keyspace_IsBatched(SWIGTYPE_p_void.getCPtr(client)); } public static void Keyspace_SetTrace(boolean trace) { keyspace_clientJNI.Keyspace_SetTrace(trace); } }
agpl-3.0
nanaya/osu-web
resources/assets/lib/user-multiplayer-index/room.tsx
4962
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import DifficultyBadge from 'difficulty-badge'; import Img2x from 'img2x'; import RoomJson from 'interfaces/room-json'; import { route } from 'laroute'; import { maxBy, minBy } from 'lodash'; import { computed, makeObservable } from 'mobx'; import { observer } from 'mobx-react'; import * as moment from 'moment'; import * as React from 'react'; import StringWithComponent from 'string-with-component'; import { UserLink } from 'user-link'; import { getDiffColour } from 'utils/beatmap-helper'; import { classWithModifiers } from 'utils/css'; import MultiplayerHistoryStore from './multiplayer-history-store'; interface Props { room: RoomJson & Required<Pick<RoomJson, 'playlist'>>; store: MultiplayerHistoryStore; } const endingSoonDiffMs = 60 * 60 * 1000; // 60 minutes. @observer export default class Room extends React.Component<Props> { @computed private get status() { if (!this.props.room.active) { return 'ended'; } const diff = new Date(this.props.room.ends_at).getTime() - new Date().getTime(); return diff < endingSoonDiffMs ? 'soon' : 'active'; } @computed private get maxDifficulty() { const max = maxBy(this.props.room.playlist, (playlist) => this.props.store.beatmaps.get(playlist.beatmap_id)?.difficulty_rating); return this.props.store.beatmaps.get(max?.beatmap_id ?? 0)?.difficulty_rating ?? 0; } @computed private get minDifficulty() { const min = minBy(this.props.room.playlist, (playlist) => this.props.store.beatmaps.get(playlist.beatmap_id)?.difficulty_rating); return this.props.store.beatmaps.get(min?.beatmap_id ?? 0)?.difficulty_rating ?? 0; } private get background() { const beatmap = this.props.store.beatmaps.get(this.props.room.playlist[0].beatmap_id); const beatmapset = this.props.store.beatmapsets.get(beatmap?.beatmapset_id ?? 0); if (beatmapset == null) return undefined; return beatmapset.covers.cover; } constructor(props: Props) { super(props); makeObservable(this); } render() { const endsAt = moment(this.props.room.ends_at); return ( <div className='multiplayer-room'> {this.renderCover()} <div className='multiplayer-room__content'> <div className='multiplayer-room__badge-container'> <div className={classWithModifiers('multiplayer-room__badge', [this.status])}>{osu.trans(`multiplayer.room.status.${this.status}`)}</div> <time className='js-tooltip-time u-hover' title={this.props.room.ends_at}> {this.status === 'ended' ? endsAt.fromNow() : osu.trans('multiplayer.room.time_left', { time: endsAt.fromNow(true) })} </time> </div> <div className='multiplayer-room__details'> <div className='multiplayer-room__name'>{this.props.room.name}</div> {this.renderMembers()} </div> <div className='multiplayer-room__badge-container multiplayer-room__badge-container--bottom'> <div className={classWithModifiers('multiplayer-room__badge', ['map-count'])}>{osu.transChoice('multiplayer.room.map_count', this.props.room.playlist.length)}</div> <div className='multiplayer-room__difficulty' style={{ '--max-difficulty': getDiffColour(this.maxDifficulty), '--min-difficulty': getDiffColour(this.minDifficulty), } as React.CSSProperties} > <DifficultyBadge rating={this.minDifficulty} /> {this.minDifficulty !== this.maxDifficulty && <DifficultyBadge rating={this.maxDifficulty} />} </div> </div> </div> </div> ); } private renderCover() { return ( <a className='multiplayer-room__cover-container' href={route('multiplayer.rooms.show', { room: this.props.room.id })}> <div className='multiplayer-room__cover multiplayer-room__cover--default' /> <Img2x className='multiplayer-room__cover' hideOnError src={this.background} /> </a> ); } private renderHost() { return ( <div className='multiplayer-room__host'> <StringWithComponent mappings={{ user: <UserLink className='u-hover' user={this.props.room.host} /> }} pattern={osu.trans('multiplayer.room.hosted_by')} /> </div> ); } private renderMembers() { return ( <div className='multiplayer-room__members'> {this.renderHost()} {this.renderParticipants()} </div> ); } private renderParticipants() { return ( <div className='multiplayer-room__participants'> {osu.transChoice('multiplayer.room.player_count', this.props.room.participant_count)} </div> ); } }
agpl-3.0
lkundrak/scraperwiki
scraperlibs/php/scraperwiki/stacktrace.php
3718
<?php function traceToSWStackDump($trace, $script, $scriptlines, $skipa = 1, $skipb = 0) { $stackdump = array(); for ($i = count($trace) - 1 - $skipa; $i >= $skipb; $i--) { $stackPoint = $trace[$i]; $linenumber = $stackPoint["line"]; $stackentry = array("linenumber" => $linenumber, "duplicates" => 1); $stackentry["file"] = (realpath($stackPoint["file"]) == realpath($script) ? "<string>" : $stackPoint["file"]); $stackentry["linetext"] = ""; if (($linenumber >= 0) && ($linenumber < count($scriptlines))) { $stackentry["linetext"] = $scriptlines[$linenumber - 1]; } else { # XXX bit of a hack to show the line number in third party libraries $stackentry["file"] .= ":" . $linenumber; } if (array_key_exists("args", $stackPoint) and count($stackPoint["args"]) != 0) { $args = array(); foreach ($stackPoint["args"] as $arg => $val) $args[] = $arg."=>".$val; $stackentry["furtherlinetext"] = " param values: (".implode(", ", $args).")"; } $stackdump[] = $stackentry; } return $stackdump; } function exceptionHandler($exception, $script) { $scriptlines = explode("\n", file_get_contents($script)); $trace = $exception->getTrace(); $stackdump = traceToSWStackDump($trace, $script, $scriptlines, 1, 0); $linenumber = $exception->getLine(); $finalentry = array("linenumber" => $linenumber, "duplicates" => 1); $finalentry["file"] = (realpath($exception->getFile()) == realpath($script) ? "<string>" : $exception->getFile()); if (($linenumber >= 0) && ($linenumber < count($scriptlines))) { $finalentry["linetext"] = $scriptlines[$linenumber - 1]; } else { # XXX bit of a hack to show the line number in third party libraries $finalentry["file"] .= ":" . $linenumber; } $finalentry["furtherlinetext"] = $exception->getMessage(); $stackdump[] = $finalentry; return array('message_type' => 'exception', 'exceptiondescription' => $exception->getMessage(), "stackdump" => $stackdump); } $php_error_codes = Array( 1 => "E_ERROR", 2 => "E_WARNING", 4 => "E_PARSE", 8 => "E_NOTICE", 16 => "E_CORE_ERROR", 32 => "E_CORE_WARNING", 64 => "E_COMPILE_ERROR", 128 => "E_COMPILE_WARNING", 256 => "E_USER_ERROR", 512 => "E_USER_WARNING", 1024 => "E_USER_NOTICE", 2048 => "E_STRICT", 4096 => "E_RECOVERABLE_ERROR", 8192 => "E_DEPRECATED", 16384 => "E_USER_DEPRECATED", ); function errorParserNoStack($errno, $errstr, $errfile, $errline) { $scriptlines = explode("\n", file_get_contents($errfile)); $linenumber = $errline; $errorentry = array("linenumber" => $linenumber, "duplicates" => 1); $errorentry["file"] = "<string>"; if (($linenumber >= 0) && ($linenumber < count($scriptlines))) $errorentry["linetext"] = $scriptlines[$linenumber - 1]; global $php_error_codes; $errcode = $php_error_codes[$errno]; $stackdump = array(); $stackdump[] = $errorentry; return array('message_type' => 'exception', 'exceptiondescription' => $errcode." ".$errstr, "stackdump" => $stackdump); } function errorParserStack($errno, $errstr, $script) { $scriptlines = explode("\n", file_get_contents($script)); $trace = debug_backtrace(); $stackdump = traceToSWStackDump($trace, $script, $scriptlines, 1, 2); global $php_error_codes; $errcode = $php_error_codes[$errno]; return array('message_type' => 'exception', 'exceptiondescription' => $errcode." ".$errstr, "stackdump" => $stackdump); } ?>
agpl-3.0
agoravoting/agora-ciudadana
agora_site/static/js/agora/views/election_form.js
25257
(function() { Agora.AnswerModel = Backbone.AssociatedModel.extend({ defaults: { 'a': 'ballot/answer', 'url': '', 'details': '', 'value': '' } }); Agora.QuestionModel = Backbone.AssociatedModel.extend({ relations: [{ type: Backbone.Many, key: 'answers', relatedModel: Agora.AnswerModel }], defaults: { 'a': 'ballot/question', 'tally_type': 'ONE_CHOICE', 'question_num': 0, 'max': 1, 'min': 0, 'num_seats': 1, 'question': '', 'randomize_answer_order': true, 'answers': [] } }); Agora.ElectionModel = Backbone.AssociatedModel.extend({ relations: [{ type: Backbone.Many, key: 'questions', relatedModel: Agora.QuestionModel }], defaults: { 'pretty_name': '', 'description': '', 'is_vote_secret': true, 'questions': [], 'from_date': '', 'to_date': '' } }); Agora.AnswerView = Backbone.View.extend({ tagName: 'tr', events: { 'click td': 'editValue', 'keyup .input-edit-value': 'keyUpSaveValue' }, initialize: function() { _.bindAll(this); this.render(); this.listenTo(this.model, 'destroy', this.remove); return this.$el; }, render: function() { // render template this.template = _.template($("#template-election_form_question_answer").html()); this.$el.html(this.template(this.model.toJSON())); // handle some dom events this.$el.find(".input-edit-value").focusout(this.focusOutValue); return this; }, editValue: function(e) { if ($(e.target).hasClass("remove_option")) { return; } var val = this.$el.find('.the-value').html(); this.$el.find('.input-edit-value').val(val); this.$el.find('.view-value').hide(); this.$el.find('.edit-value').show(); this.$el.find('.input-edit-value').focus(); }, keyUpSaveValue: function(e) { if (e.keyCode == 13) // <Enter> { var value = this.$el.find('.input-edit-value').val(); // check that the value is non empty and not already used if (!value) { this.$el.find('.view-value').show(); this.$el.find('.edit-value').hide(); return; } // save the value this.model.set('value', value); this.$el.find('.the-value').html(value) this.$el.find('.view-value').show(); this.$el.find('.edit-value').hide(); } else if (e.keyCode == 27) // <Esc> { this.$el.find('.view-value').show(); this.$el.find('.edit-value').hide(); } }, focusOutValue: function() { this.$el.find('.view-value').show(); this.$el.find('.edit-value').hide(); } }); Agora.QuestionEditView = Backbone.View.extend({ tagName: 'div', className: 'tab-pane', events: { 'click .dropdown-menu li a': 'selectVotingSystem', 'click .add_option_btn': 'userAddAnswer', 'keyup .add_option': 'userAddAnswerEnter', 'click .remove_option': 'userRemoveAnswer', 'click .create_question_btn': 'createQuestion' }, getMetrics: function() { var self = this; var checkNumWinners = function(val) { var num_answers = self.model.get('answers').length; if (num_answers < 2) { return true; } return num_answers > val; }; var checkMax = function(val) { var num_answers = self.model.get('answers').length; if (num_answers < 2) { return true; } return num_answers > val; }; var checkMin = function(val) { return val >= 0 && val <= self.$el.find('.max_num_choices').val(); }; var checkNumAnswers = function(val) { var num_answers = self.model.get('answers').length; return num_answers >= 2; } return [ ['.name', 'presence', gettext('This field is required')], ['.name', 'min-length:4', gettext('Must have at least 4 characters')], ['.num_winners', 'presence', gettext('This field is required')], ['.min_num_choices', 'presence', gettext('This field is required')], ['.max_num_choices', 'presence', gettext('This field is required')], ['.num_winners', 'integer', gettext('This field must be an integer')], ['.min_num_choices', 'integer', gettext('This field must be an integer')], ['.max_num_choices', 'integer', gettext('This field must be an integer')], ['.num_winners', checkNumWinners, gettext('Invalid value')], ['.min_num_choices', checkMax, gettext('Invalid value')], ['.add_option', checkNumAnswers, gettext('Add at least two choices')], ]; }, id: function() { return "question-tab-" + this.model.get('question_num'); }, updateModel: function() { this.model.set('question', this.$el.find('.name').val()); this.model.set('num_seats', parseInt(this.$el.find('.num_winners').val())); this.model.set('min', parseInt(this.$el.find('.min_num_choices').val())); this.model.set('max', parseInt(this.$el.find('.max_num_choices').val())); }, initialize: function() { _.bindAll(this); this.template = _.template($("#template-election_form_question_tab_pane").html()); this.model.questionView = this; this.render(); this.listenTo(this.model.get("answers"), 'add', this.addAnswer); this.listenTo(this.model.get("answers"), 'remove', this.removeAnswer); this.listenTo(this.model.get("answers"), 'reset', this.resetAnswers); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'change:question_num', this.render); this.listenTo(this.model.get("answers"), 'change:value', this.answerChanged); return this.$el; }, render: function() { var json = this.model.toJSON(); json.edit_election = (!ajax_data) ? false : true; this.$el.html(this.template(json)); this.$el.attr("id", this.id); // init voting system combo box var self = this; this.$el.find(".votingsystem-dropdown li").each(function () { var id = $(this).data("id"); if (id == self.$el.find(".votingsystem").data('id')) { var usertext = $(this).data("usertext"); self.$el.find(".votingsystem").html(usertext); if (id == "MEEK-STV") { self.$el.find(".num_winners_opts").css('display', 'inline-block'); } else { self.$el.find(".num_winners_opts").hide(); self.$el.find(".max_num_choices").attr('readonly', 'readonly'); } } }); this.resetAnswers(); this.$el.find("form").nod(this.getMetrics(), { silentSubmit: true, broadcastError: true, submitBtnSelector: ".hidden-input" }); this.$el.find("form").submit(function (e) { e.preventDefault(); }); return this; }, userRemoveAnswer: function(e) { var value = $(e.target).closest("a").data('value'); var model = this.model.get('answers').find(function (answer) { return answer.get('value') == value; }); this.model.get('answers').remove(model); model.destroy(); }, userAddAnswerEnter: function(e) { e.preventDefault(); e.stopPropagation(); if (e.keyCode == 13) { // <Enter> this.userAddAnswer(); } return false; }, userAddAnswer: function() { var val = this.$el.find(".add_option").val(); // do not add if text is empty if (!val) { return; } // do not add if answer is already listed var model = this.model.get('answers').find(function (answer) { return answer.get('value') == val; }); if (model) { return; } this.$el.find(".add_option").val(''); var newAnswer = new Agora.AnswerModel({value: val}); this.model.get('answers').add(newAnswer); }, addAnswer: function(answerModel) { var view = new Agora.AnswerView({model: answerModel}); this.$el.find('.option-list').append(view.render().el); if (this.model.get('answers').length > 0) { this.$el.find('.atleastwooptions').hide(); } }, removeAnswer: function() { if (this.model.get('answers').length < 1) { this.$el.find('.atleastwooptions').show(); } }, answerChanged: function(answer) { var answers = this.model.get('answers').filter(function (answer2) { return answer.get('value') == answer2.get('value'); }); if (answers.length > 1) { answer.destroy(); } }, resetAnswers: function() { this.$el.find('.option-list').empty(); this.model.get("answers").each(this.addAnswer); }, resetForm: function() { this.stopListening(); this.model.clear().set(this.model.defaults); this.initialize(); }, selectVotingSystem: function(e) { var id = $(e.target).closest("li").data('id'); var usertext = $(e.target).closest("li").data('usertext'); this.$el.find(".votingsystem").data('id', id); this.$el.find(".votingsystem").html(usertext); if (id == "MEEK-STV") { this.$el.find(".num_winners_opts").css('display', 'inline-block'); this.$el.find(".max_num_choices").removeAttr('readonly'); } else { this.$el.find(".num_winners_opts input").val('1'); this.$el.find(".num_winners_opts").hide(); this.$el.find(".max_num_choices").val('1'); this.$el.find(".max_num_choices").attr('readonly', 'readonly'); } this.model.set('tally_type', id); }, createQuestion: function(e) { if (!this.$el.find("form").nod().formIsErrorFree()) { return; } // create the question this.updateModel(); var model = this.model.clone(); model.set("question_num", app.currentView.model.get('questions').length + 1); app.currentView.model.get('questions').add(model); // reset the add question tab this.resetForm(); }, }); Agora.ElectionCreateForm = Backbone.View.extend({ el: "div.top-form", initData: {}, __initialLoading: false, getMetrics: function() { var self = this; var checkIntervalDate = function() { if (self.$el.find("#schedule_voting:checked").length == 0) { return true; } var val_end = self.$el.find("#end_voting_date").val(); var end_date = moment(val_end, "MM/DD/YYYY HH:mm"); var val_start = self.$el.find("#start_voting_date").val(); var start_date = moment(val_start, "MM/DD/YYYY HH:mm"); return end_date != null && start_date != null && end_date - start_date >= 3600*1000; }; return [ ['#pretty_name', 'presence', gettext('This field is required')], ['#pretty_name', 'min-length:4', gettext('Must have at least 4 characters')], ['#description', 'presence', gettext('This field is required')], ['#description', 'min-length:4', gettext('Must be at least 4 characters long')], ['[name=is_vote_secret]', 'presence', gettext('You must choose if vote is secret')], ['#start_voting_date', checkIntervalDate, gettext('Invalid dates')], ['#end_voting_date', checkIntervalDate, gettext('Invalid dates')], ]; }, events: { 'click #schedule_voting': 'toggleScheduleVoting', 'click #show_add_question_tab_btn': 'showAddQuestionTab', 'click #schedule_voting_label': 'checkSchedule', 'click .remove_question_btn': 'removeQuestion', 'click .create_election_btn': 'saveElection', }, getInitModel: function() { // ElectionModel contains a default return new Agora.ElectionModel(); }, modelToJsonForTemplate: function() { var json = this.model.toJSON(); json.edit_election = false; return json; }, initialize: function() { var log_error = function( event, data ) { console.log( data.el ); console.log( data.msg ); } $( window ).on( 'nod_error_fired', log_error ); this.template = _.template($("#template-election_form").html()); this.templateNavtab = _.template($("#template-election_form_question_navtab").html()); _.bindAll(this); this.model = this.getInitModel(); // render initial template this.$el.html(this.template(this.modelToJsonForTemplate())); // add question tab-content this.addQuestionView = new Agora.QuestionEditView({ model: new Agora.QuestionModel({'question_num': 0}), electionFormView: this }); this.$el.find('.tab-content').append(this.addQuestionView.render().el); // load initial models and listen to new ones this.listenTo(this.model.get('questions'), 'add', this.addQuestion); // prevents tabs to be shown as they are being added this.__initialLoading = true; this.model.get('questions').each(this.addQuestion); this.__initialLoading = false; // update button on model changes and initialize this.listenTo(this.model, 'change', this.updateButtonsShown); this.listenTo(this.model.get('questions'), 'add', this.updateButtonsShown); this.listenTo(this.model.get('questions'), 'remove', this.updateButtonsShown); this.updateButtonsShown(); // do various setup calls this.$el.find("#create_election_form").nod(this.getMetrics(), {silentSubmit: true, submitBtnSelector: ".hidden-input"}); this.$el.find("form").submit(function (e) { e.preventDefault(); }); $('.datetimepicker').datetimepicker(); if (this.model.get("from_date")) { this.$el.find("#schedule_voting").click(); $('div.top-form #schedule_voting_controls').toggle(); } }, removeQuestion: function(e) { var question_num = $(e.target).data('id'); var question = this.model.get('questions').at(question_num - 1); var length = this.model.get('questions').length; question.destroy(); this.model.get('questions').remove(question); this.$el.find("#question-navtab-" + length).remove(); var i = 1; this.model.get('questions').each(function (model) { model.set('question_num', i); i++; }); var selector = "#add-question-navtab a"; this.$el.find(selector).tab('show'); }, checkSchedule: function(e) { if ($("#schedule_voting:checked").length == 0) { $(e.target).closest(".error").removeClass('error'); } }, addQuestion: function(questionModel) { var i = questionModel.get('question_num'); var newTab = this.templateNavtab({question_num: i}); this.$el.find('#add-question-navtab').before(newTab); var view = new Agora.QuestionEditView({ model: questionModel, electionFormView: this }); this.$el.find('.tab-content').append(view.render().el); // if we're not loading the initial tabs, show the added question if (!this.__initialLoading) { $("#question-navtab-" + i +" a").tab('show'); } }, toggleScheduleVoting: function(e) { $('div.top-form #schedule_voting_controls').toggle(e.target.checked); }, updateModel: function() { var start_date = this.$el.find("#start_voting_date").val(); var end_date = this.$el.find("#end_voting_date").val(); if ($("#schedule_voting:checked").length == 0) { this.model.set('from_date', ''); this.model.set('to_date', ''); } else { this.model.set('from_date', new Date(start_date).toJSON()); this.model.set('to_date', new Date(end_date).toJSON()); } this.model.set('pretty_name', this.$el.find('#pretty_name').val()); this.model.set('description', this.$el.find('#description').val()); this.model.set('short_description', this.model.get('description').substr(0, 140)); var is_vote_secret = $("#is_vote_secret_yes").attr('checked') == 'checked'; this.model.set('is_vote_secret', is_vote_secret); }, sendingData: false, saveElection: function(e) { e.preventDefault(); // if we are already sending do nothing if (this.sendingData) { return; } // check that main election tab is being shown if (!$("#main-election-tab").hasClass("active")) { $("#main-election-tab a").tab('show'); } // check that form is error free if (!this.$el.find("#create_election_form").nod().formIsErrorFree()) { return; } this.updateModel(); // look for a question whose data is invalid, if any var failingQuestion = this.model.get('questions').find(function (question) { question.questionView.updateModel(); return !question.questionView.$el.find("form").nod().formIsErrorFree(); }); // if found, switch to that question and return if (failingQuestion) { var question_num =failingQuestion.get('question_num'); var selector = "#question-navtab-" + question_num + " a"; this.$el.find(selector).tab('show'); return; } // okey, we're going to send this new election - but first disable // the send question button to avoid sending the same thing multiple // times $(".create_election_btn").addClass("disabled"); this.sendingData = true; var json = this.model.toJSON(); json.action = 'create_election'; var agora_id = $("#agora_id").val(); var self = this; var jqxhr = $.ajax("/api/v1/agora/" + agora_id + "/action/", { data: JSON.stringifyCompat(json), contentType : 'application/json', type: 'POST', }) .done(function(e) { window.location.href = e.url; }) .fail(function(e) { self.sendingData = false; $(".create_election_btn").removeClass("disabled"); var response = $.parseJSON(e.responseText); if (response.errors) { alert(response.errors.__all__); } else { alert(gettext("Error creating the election")); } }); return false; }, updateButtonsShown: function() { if (this.model.get("questions").length == 0) { this.$el.find(".create_election_btn").hide(); this.$el.find("#save_election_btn").hide(); this.$el.find("#show_add_question_tab_btn").show(); } else { this.$el.find(".create_election_btn").show(); this.$el.find("#save_election_btn").show(); this.$el.find("#show_add_question_tab_btn").hide(); } }, showAddQuestionTab: function() { this.$el.find('.nav-tabs a:last').tab('show'); } }); Agora.ElectionEditForm = Agora.ElectionCreateForm.extend({ getInitModel: function() { // here we filter the values to those that can be modified var from_date = moment(ajax_data.voting_starts_at_date); var to_date = moment(ajax_data.voting_ends_at_date); if (from_date) { from_date = from_date.format("MM/DD/YYYY HH:mm"); } if (to_date) { to_date = to_date.format("MM/DD/YYYY HH:mm"); } var initData = { id: ajax_data.id, pretty_name: ajax_data.pretty_name, description: ajax_data.description, comments_policy: ajax_data.comments_policy, is_vote_secret: ajax_data.is_vote_secret, questions: ajax_data.questions, from_date: from_date, to_date: to_date, }; return new Agora.ElectionModel(initData); }, modelToJsonForTemplate: function() { var json = this.model.toJSON(); json.edit_election = (!ajax_data) ? false : true; return json; }, sendingData: false, saveElection: function(e) { e.preventDefault(); // if we are already sending do nothing if (this.sendingData) { return; } if (!this.$el.find("#create_election_form").nod().formIsErrorFree()) { return; } this.updateModel(); // look for a question whose data is invalid var failingQuestion = this.model.get('questions').find(function (question) { question.questionView.updateModel(); return !question.questionView.$el.find("form").nod().formIsErrorFree(); }); // if found, switch to that question if (failingQuestion) { var question_num =failingQuestion.get('question_num'); var selector = "#question-navtab-" + question_num + " a"; this.$el.find(selector).tab('show'); return; } // okey, we're going to send this new election - but first disable // the send question button to avoid sending the same thing multiple // times this.$el.find("#save_election_btn").addClass("disabled"); this.sendingData = true; var json = this.model.toJSON(); if (json.from_date) { json.from_date = new Date(json.from_date).toJSON(); } if (json.to_date) { json.to_date = new Date(json.to_date).toJSON(); } var election_id = this.model.get('id'); var self = this; var jqxhr = $.ajax("/api/v1/election/" + election_id + "/", { data: JSON.stringifyCompat(json), contentType : 'application/json', type: 'PUT', }) .done(function(e) { window.location.href = e.url; }) .fail(function() { alert("Error saving the election"); }) .always(function() { self.sendingData = false; self.$el.find("#save_election_btn").removeClass("disabled"); }); return false; }, }); }).call(this);
agpl-3.0
jittat/ku-eng-direct-admission
scripts/import_results_for_private_display.py
2421
import codecs import sys if len(sys.argv) < 3: print "Usage: import_results_for_private_display [round_number] [results.csv] [--force]" quit() round_number = int(sys.argv[1]) file_name = sys.argv[2] if len(sys.argv)>3: is_force = sys.argv[3]=="--force" else: is_force = False from django.conf import settings from django_bootstrap import bootstrap bootstrap(__file__) from result.models import AdmissionResult from application.models import Applicant, SubmissionInfo, PersonalInfo, Major def read_results(): f = codecs.open(file_name, encoding="utf-8", mode="r") lines = f.readlines()[1:] order = 1 applicant_data = [] for l in lines: items = l.strip().split(',') app = {'order': order, 'national_id': items[0], 'major': items[2] } applicant_data.append(app) order += 1 return applicant_data def delete_old_admission_results(round_number): AdmissionResult.objects.filter(round_number=round_number).delete() def standardize_major_number(major): return ('0' * (3 - len(major))) + major def import_results(round_number, applicant_data): print 'Importing results...' delete_old_admission_results(round_number) majors = Major.get_all_majors() major_dict = dict([(m.number, m) for m in majors]) app_order = 1 for a in applicant_data: applicant = Applicant.objects.get(national_id=a['national_id']) aresult = AdmissionResult() aresult.applicant = applicant aresult.round_number = round_number if a['major']=='wait': aresult.is_admitted = False aresult.is_waitlist = True aresult.admitted_major = None else: major_number = standardize_major_number(a['major']) major = major_dict[major_number] aresult.is_admitted = True aresult.is_waitlist = False aresult.admitted_major = major aresult.save() print a['national_id'] def main(): # make sure not to screw up previous round results if AdmissionResult.objects.filter(round_number=round_number).count()!=0: if not is_force: print "Old results exist. If you want to overwrite, use --force" quit() applicant_data = read_results() import_results(round_number, applicant_data) if __name__ == '__main__': main()
agpl-3.0
pdehaye/theming-edx-platform
common/lib/xmodule/xmodule/x_module.py
35767
import logging import copy import yaml import os from lxml import etree from collections import namedtuple from pkg_resources import resource_listdir, resource_string, resource_isdir from xmodule.modulestore import Location from xmodule.modulestore.exceptions import ItemNotFoundError, InsufficientSpecificationError, InvalidLocationError from xblock.core import XBlock, Scope, String, Integer, Float, List, ModelType from xblock.fragment import Fragment from xblock.runtime import Runtime from xmodule.modulestore.locator import BlockUsageLocator log = logging.getLogger(__name__) def dummy_track(_event_type, _event): pass class LocationField(ModelType): """ XBlock field for storing Location values """ def from_json(self, value): """ Parse the json value as a Location """ try: return Location(value) except InvalidLocationError: if isinstance(value, BlockUsageLocator): return value else: return BlockUsageLocator(value) def to_json(self, value): """ Store the Location as a url string in json """ return value.url() class HTMLSnippet(object): """ A base class defining an interface for an object that is able to present an html snippet, along with associated javascript and css """ js = {} js_module_name = None css = {} @classmethod def get_javascript(cls): """ Return a dictionary containing some of the following keys: coffee: A list of coffeescript fragments that should be compiled and placed on the page js: A list of javascript fragments that should be included on the page All of these will be loaded onto the page in the CMS """ # cdodge: We've moved the xmodule.coffee script from an outside directory into the xmodule area of common # this means we need to make sure that all xmodules include this dependency which had been previously implicitly # fulfilled in a different area of code coffee = cls.js.setdefault('coffee', []) fragment = resource_string(__name__, 'js/src/xmodule.coffee') if fragment not in coffee: coffee.insert(0, fragment) return cls.js @classmethod def get_css(cls): """ Return a dictionary containing some of the following keys: css: A list of css fragments that should be applied to the html contents of the snippet sass: A list of sass fragments that should be applied to the html contents of the snippet scss: A list of scss fragments that should be applied to the html contents of the snippet """ return cls.css def get_html(self): """ Return the html used to display this snippet """ raise NotImplementedError( "get_html() must be provided by specific modules - not present in {0}" .format(self.__class__)) class XModuleFields(object): display_name = String( display_name="Display Name", help="This name appears in the horizontal navigation at the top of the page.", scope=Scope.settings, # it'd be nice to have a useful default but it screws up other things; so, # use display_name_with_default for those default=None ) # Please note that in order to be compatible with XBlocks more generally, # the LMS and CMS shouldn't be using this field. It's only for internal # consumption by the XModules themselves location = LocationField( display_name="Location", help="This is the location id for the XModule.", scope=Scope.content, default=Location(None), ) # Please note that in order to be compatible with XBlocks more generally, # the LMS and CMS shouldn't be using this field. It's only for internal # consumption by the XModules themselves category = String( display_name="xmodule category", help="This is the category id for the XModule. It's for internal use only", scope=Scope.content, ) class XModule(XModuleFields, HTMLSnippet, XBlock): ''' Implements a generic learning module. Subclasses must at a minimum provide a definition for get_html in order to be displayed to users. See the HTML module for a simple example. ''' # The default implementation of get_icon_class returns the icon_class # attribute of the class # # This attribute can be overridden by subclasses, and # the function can also be overridden if the icon class depends on the data # in the module icon_class = 'other' def __init__(self, runtime, descriptor, model_data): ''' Construct a new xmodule runtime: An XBlock runtime allowing access to external resources descriptor: the XModuleDescriptor that this module is an instance of. model_data: A dictionary-like object that maps field names to values for those fields. ''' super(XModule, self).__init__(runtime, model_data) self._model_data = model_data self.system = runtime self.descriptor = descriptor # LMS tests don't require descriptor but really it's required if descriptor: self.url_name = descriptor.url_name # don't need to set category as it will automatically get from descriptor elif isinstance(self.location, Location): self.url_name = self.location.name if getattr(self, 'category', None) is None: self.category = self.location.category elif isinstance(self.location, BlockUsageLocator): self.url_name = self.location.usage_id if getattr(self, 'category', None) is None: raise InsufficientSpecificationError() else: raise InsufficientSpecificationError() self._loaded_children = None @property def id(self): return self.location.url() @property def display_name_with_default(self): ''' Return a display name for the module: use display_name if defined in metadata, otherwise convert the url name. ''' name = self.display_name if name is None: name = self.url_name.replace('_', ' ') return name def get_children(self): ''' Return module instances for all the children of this module. ''' if self._loaded_children is None: child_descriptors = self.get_child_descriptors() # This deliberately uses system.get_module, rather than runtime.get_block, # because we're looking at XModule children, rather than XModuleDescriptor children. # That means it can use the deprecated XModule apis, rather than future XBlock apis # TODO: Once we're in a system where this returns a mix of XModuleDescriptors # and XBlocks, we're likely to have to change this more children = [self.system.get_module(descriptor) for descriptor in child_descriptors] # get_module returns None if the current user doesn't have access # to the location. self._loaded_children = [c for c in children if c is not None] return self._loaded_children def __unicode__(self): return '<x_module(id={0})>'.format(self.id) def get_child_descriptors(self): ''' Returns the descriptors of the child modules Overriding this changes the behavior of get_children and anything that uses get_children, such as get_display_items. This method will not instantiate the modules of the children unless absolutely necessary, so it is cheaper to call than get_children These children will be the same children returned by the descriptor unless descriptor.has_dynamic_children() is true. ''' return self.descriptor.get_children() def get_child_by(self, selector): """ Return a child XModuleDescriptor with the specified url_name, if it exists, and None otherwise. """ for child in self.get_children(): if selector(child): return child return None def get_display_items(self): ''' Returns a list of descendent module instances that will display immediately inside this module. ''' items = [] for child in self.get_children(): items.extend(child.displayable_items()) return items def displayable_items(self): ''' Returns list of displayable modules contained by this module. If this module is visible, should return [self]. ''' return [self] def get_icon_class(self): ''' Return a css class identifying this module in the context of an icon ''' return self.icon_class # Functions used in the LMS def get_score(self): """ Score the student received on the problem, or None if there is no score. Returns: dictionary {'score': integer, from 0 to get_max_score(), 'total': get_max_score()} NOTE (vshnayder): not sure if this was the intended return value, but that's what it's doing now. I suspect that we really want it to just return a number. Would need to change (at least) capa and modx_dispatch to match if we did that. """ return None def max_score(self): ''' Maximum score. Two notes: * This is generic; in abstract, a problem could be 3/5 points on one randomization, and 5/7 on another * In practice, this is a Very Bad Idea, and (a) will break some code in place (although that code should get fixed), and (b) break some analytics we plan to put in place. ''' return None def get_progress(self): ''' Return a progress.Progress object that represents how far the student has gone in this module. Must be implemented to get correct progress tracking behavior in nesting modules like sequence and vertical. If this module has no notion of progress, return None. ''' return None def handle_ajax(self, _dispatch, _data): ''' dispatch is last part of the URL. data is a dictionary-like object with the content of the request''' return "" # ~~~~~~~~~~~~~~~ XBlock API Wrappers ~~~~~~~~~~~~~~~~ def student_view(self, context): """ Return a fragment with the html from this XModule Doesn't yet add any of the javascript to the fragment, nor the css. Also doesn't expect any javascript binding, yet. Makes no use of the context parameter """ return Fragment(self.get_html()) def policy_key(location): """ Get the key for a location in a policy file. (Since the policy file is specific to a course, it doesn't need the full location url). """ return '{cat}/{name}'.format(cat=location.category, name=location.name) Template = namedtuple("Template", "metadata data children") class ResourceTemplates(object): """ Gets the templates associated w/ a containing cls. The cls must have a 'template_dir_name' attribute. It finds the templates as directly in this directory under 'templates'. """ @classmethod def templates(cls): """ Returns a list of dictionary field: value objects that describe possible templates that can be used to seed a module of this type. Expects a class attribute template_dir_name that defines the directory inside the 'templates' resource directory to pull templates from """ templates = [] dirname = cls.get_template_dir() if dirname is not None: for template_file in resource_listdir(__name__, dirname): if not template_file.endswith('.yaml'): log.warning("Skipping unknown template file %s", template_file) continue template_content = resource_string(__name__, os.path.join(dirname, template_file)) template = yaml.safe_load(template_content) template['template_id'] = template_file templates.append(template) return templates @classmethod def get_template_dir(cls): if getattr(cls, 'template_dir_name', None): dirname = os.path.join('templates', getattr(cls, 'template_dir_name')) if not resource_isdir(__name__, dirname): log.warning("No resource directory {dir} found when loading {cls_name} templates".format( dir=dirname, cls_name=cls.__name__, )) return None else: return dirname else: return None @classmethod def get_template(cls, template_id): """ Get a single template by the given id (which is the file name identifying it w/in the class's template_dir_name) """ dirname = cls.get_template_dir() if dirname is not None: try: template_content = resource_string(__name__, os.path.join(dirname, template_id)) except IOError: return None template = yaml.safe_load(template_content) template['template_id'] = template_id return template else: return None class XModuleDescriptor(XModuleFields, HTMLSnippet, ResourceTemplates, XBlock): """ An XModuleDescriptor is a specification for an element of a course. This could be a problem, an organizational element (a group of content), or a segment of video, for example. XModuleDescriptors are independent and agnostic to the current student state on a problem. They handle the editing interface used by instructors to create a problem, and can generate XModules (which do know about student state). """ entry_point = "xmodule.v1" module_class = XModule # Attributes for inspection of the descriptor # This indicates whether the xmodule is a problem-type. # It should respond to max_score() and grade(). It can be graded or ungraded # (like a practice problem). has_score = False # A list of descriptor attributes that must be equal for the descriptors to # be equal equality_attributes = ('_model_data', 'location') # Class level variable # True if this descriptor always requires recalculation of grades, for # example if the score can change via an extrnal service, not just when the # student interacts with the module on the page. A specific example is # FoldIt, which posts grade-changing updates through a separate API. always_recalculate_grades = False # VS[compat]. Backwards compatibility code that can go away after # importing 2012 courses. # A set of metadata key conversions that we want to make metadata_translations = { 'slug': 'url_name', 'name': 'display_name', } # ============================= STRUCTURAL MANIPULATION =================== def __init__(self, *args, **kwargs): """ Construct a new XModuleDescriptor. The only required arguments are the system, used for interaction with external resources, and the definition, which specifies all the data needed to edit and display the problem (but none of the associated metadata that handles recordkeeping around the problem). This allows for maximal flexibility to add to the interface while preserving backwards compatibility. runtime: A DescriptorSystem for interacting with external resources model_data: A dictionary-like object that maps field names to values for those fields. XModuleDescriptor.__init__ takes the same arguments as xblock.core:XBlock.__init__ """ super(XModuleDescriptor, self).__init__(*args, **kwargs) self.system = self.runtime if isinstance(self.location, Location): self.url_name = self.location.name if getattr(self, 'category', None) is None: self.category = self.location.category elif isinstance(self.location, BlockUsageLocator): self.url_name = self.location.usage_id if getattr(self, 'category', None) is None: raise InsufficientSpecificationError() else: raise InsufficientSpecificationError() # update_version is the version which last updated this xblock v prev being the penultimate updater # leaving off original_version since it complicates creation w/o any obv value yet and is computable # by following previous until None # definition_locator is only used by mongostores which separate definitions from blocks self.edited_by = self.edited_on = self.previous_version = self.update_version = self.definition_locator = None self._child_instances = None @property def id(self): return self.location.url() @property def display_name_with_default(self): ''' Return a display name for the module: use display_name if defined in metadata, otherwise convert the url name. ''' name = self.display_name if name is None: name = self.url_name.replace('_', ' ') return name def get_required_module_descriptors(self): """Returns a list of XModuleDescritpor instances upon which this module depends, but are not children of this module""" return [] def get_children(self): """Returns a list of XModuleDescriptor instances for the children of this module""" if not self.has_children: return [] if self._child_instances is None: self._child_instances = [] for child_loc in self.children: if isinstance(child_loc, XModuleDescriptor): child = child_loc else: try: child = self.runtime.get_block(child_loc) except ItemNotFoundError: log.exception('Unable to load item {loc}, skipping'.format(loc=child_loc)) continue self._child_instances.append(child) return self._child_instances def get_child_by(self, selector): """ Return a child XModuleDescriptor with the specified url_name, if it exists, and None otherwise. """ for child in self.get_children(): if selector(child): return child return None def xmodule(self, system): """ Returns an XModule. system: Module system """ # save any field changes module = self.module_class( system, self, system.xblock_model_data(self), ) module.save() return module def has_dynamic_children(self): """ Returns True if this descriptor has dynamic children for a given student when the module is created. Returns False if the children of this descriptor are the same children that the module will return for any student. """ return False @classmethod def _translate(cls, key): 'VS[compat]' return cls.metadata_translations.get(key, key) # ================================= XML PARSING ============================ @staticmethod def load_from_xml(xml_data, system, org=None, course=None, default_class=None): """ This method instantiates the correct subclass of XModuleDescriptor based on the contents of xml_data. xml_data must be a string containing valid xml system is an XMLParsingSystem org and course are optional strings that will be used in the generated module's url identifiers """ class_ = XModuleDescriptor.load_class( etree.fromstring(xml_data).tag, default_class ) # leave next line, commented out - useful for low-level debugging # log.debug('[XModuleDescriptor.load_from_xml] tag=%s, class_=%s' % ( # etree.fromstring(xml_data).tag,class_)) return class_.from_xml(xml_data, system, org, course) @classmethod def from_xml(cls, xml_data, system, org=None, course=None): """ Creates an instance of this descriptor from the supplied xml_data. This may be overridden by subclasses xml_data: A string of xml that will be translated into data and children for this module system is an XMLParsingSystem org and course are optional strings that will be used in the generated module's url identifiers """ raise NotImplementedError( 'Modules must implement from_xml to be parsable from xml') def export_to_xml(self, resource_fs): """ Returns an xml string representing this module, and all modules underneath it. May also write required resources out to resource_fs Assumes that modules have single parentage (that no module appears twice in the same course), and that it is thus safe to nest modules as xml children as appropriate. The returned XML should be able to be parsed back into an identical XModuleDescriptor using the from_xml method with the same system, org, and course """ raise NotImplementedError( 'Modules must implement export_to_xml to enable xml export') # =============================== Testing ================================== def get_sample_state(self): """ Return a list of tuples of instance_state, shared_state. Each tuple defines a sample case for this module """ return [('{}', '{}')] @property def xblock_kvs(self): """ Use w/ caution. Really intended for use by the persistence layer. """ # if caller wants kvs, caller's assuming it's up to date; so, decache it self.save() return self._model_data._kvs # =============================== BUILTIN METHODS ========================== def __eq__(self, other): return (self.__class__ == other.__class__ and all(getattr(self, attr, None) == getattr(other, attr, None) for attr in self.equality_attributes)) def __repr__(self): return ( "{class_}({system!r}, location={location!r}," " model_data={model_data!r})".format( class_=self.__class__.__name__, system=self.system, location=self.location, model_data=self._model_data, ) ) def iterfields(self): """ A generator for iterate over the fields of this xblock (including the ones in namespaces). Example usage: [field.name for field in module.iterfields()] """ for field in self.fields: yield field for namespace in self.namespaces: for field in getattr(self, namespace).fields: yield field @property def non_editable_metadata_fields(self): """ Return the list of fields that should not be editable in Studio. When overriding, be sure to append to the superclasses' list. """ # We are not allowing editing of xblock tag and name fields at this time (for any component). return [XBlock.tags, XBlock.name] def get_explicitly_set_fields_by_scope(self, scope=Scope.content): """ Get a dictionary of the fields for the given scope which are set explicitly on this xblock. (Including any set to None.) """ if scope == Scope.settings and hasattr(self, '_inherited_metadata'): inherited_metadata = getattr(self, '_inherited_metadata') result = {} for field in self.iterfields(): if (field.scope == scope and field.name in self._model_data and field.name not in inherited_metadata): result[field.name] = self._model_data[field.name] return result else: result = {} for field in self.iterfields(): if (field.scope == scope and field.name in self._model_data): result[field.name] = self._model_data[field.name] return result @property def editable_metadata_fields(self): """ Returns the metadata fields to be edited in Studio. These are fields with scope `Scope.settings`. Can be limited by extending `non_editable_metadata_fields`. """ inherited_metadata = getattr(self, '_inherited_metadata', {}) inheritable_metadata = getattr(self, '_inheritable_metadata', {}) metadata_fields = {} for field in self.fields: if field.scope != Scope.settings or field in self.non_editable_metadata_fields: continue inheritable = False value = getattr(self, field.name) default_value = field.default explicitly_set = field.name in self._model_data if field.name in inheritable_metadata: inheritable = True default_value = field.from_json(inheritable_metadata.get(field.name)) if field.name in inherited_metadata: explicitly_set = False # We support the following editors: # 1. A select editor for fields with a list of possible values (includes Booleans). # 2. Number editors for integers and floats. # 3. A generic string editor for anything else (editing JSON representation of the value). editor_type = "Generic" values = copy.deepcopy(field.values) if isinstance(values, tuple): values = list(values) if isinstance(values, list): if len(values) > 0: editor_type = "Select" for index, choice in enumerate(values): json_choice = copy.deepcopy(choice) if isinstance(json_choice, dict) and 'value' in json_choice: json_choice['value'] = field.to_json(json_choice['value']) else: json_choice = field.to_json(json_choice) values[index] = json_choice elif isinstance(field, Integer): editor_type = "Integer" elif isinstance(field, Float): editor_type = "Float" elif isinstance(field, List): editor_type = "List" metadata_fields[field.name] = { 'field_name': field.name, 'type': editor_type, 'display_name': field.display_name, 'value': field.to_json(value), 'options': [] if values is None else values, 'default_value': field.to_json(default_value), 'inheritable': inheritable, 'explicitly_set': explicitly_set, 'help': field.help, } return metadata_fields # ~~~~~~~~~~~~~~~ XBlock API Wrappers ~~~~~~~~~~~~~~~~ def studio_view(self, context): """ Return a fragment with the html from this XModuleDescriptor's editing view Doesn't yet add any of the javascript to the fragment, nor the css. Also doesn't expect any javascript binding, yet. Makes no use of the context parameter """ return Fragment(self.get_html()) class DescriptorSystem(Runtime): def __init__(self, load_item, resources_fs, error_tracker, **kwargs): """ load_item: Takes a Location and returns an XModuleDescriptor resources_fs: A Filesystem object that contains all of the resources needed for the course error_tracker: A hook for tracking errors in loading the descriptor. Used for example to get a list of all non-fatal problems on course load, and display them to the user. A function of (error_msg). errortracker.py provides a handy make_error_tracker() function. Patterns for using the error handler: try: x = access_some_resource() check_some_format(x) except SomeProblem as err: msg = 'Grommet {0} is broken: {1}'.format(x, str(err)) log.warning(msg) # don't rely on tracker to log # NOTE: we generally don't want content errors logged as errors self.system.error_tracker(msg) # work around return 'Oops, couldn't load grommet' OR, if not in an exception context: if not check_something(thingy): msg = "thingy {0} is broken".format(thingy) log.critical(msg) self.system.error_tracker(msg) NOTE: To avoid duplication, do not call the tracker on errors that you're about to re-raise---let the caller track them. """ self.load_item = load_item self.resources_fs = resources_fs self.error_tracker = error_tracker def get_block(self, block_id): """See documentation for `xblock.runtime:Runtime.get_block`""" return self.load_item(block_id) class XMLParsingSystem(DescriptorSystem): def __init__(self, load_item, resources_fs, error_tracker, process_xml, policy, **kwargs): """ load_item, resources_fs, error_tracker: see DescriptorSystem policy: a policy dictionary for overriding xml metadata process_xml: Takes an xml string, and returns a XModuleDescriptor created from that xml """ DescriptorSystem.__init__(self, load_item, resources_fs, error_tracker, **kwargs) self.process_xml = process_xml self.policy = policy class ModuleSystem(Runtime): ''' This is an abstraction such that x_modules can function independent of the courseware (e.g. import into other types of courseware, LMS, or if we want to have a sandbox server for user-contributed content) ModuleSystem objects are passed to x_modules to provide access to system functionality. Note that these functions can be closures over e.g. a django request and user, or other environment-specific info. ''' def __init__( self, ajax_url, track_function, get_module, render_template, replace_urls, xblock_model_data, user=None, filestore=None, debug=False, xqueue=None, publish=None, node_path="", anonymous_student_id='', course_id=None, open_ended_grading_interface=None, s3_interface=None, cache=None, can_execute_unsafe_code=None, replace_course_urls=None, replace_jump_to_id_urls=None): ''' Create a closure around the system environment. ajax_url - the url where ajax calls to the encapsulating module go. track_function - function of (event_type, event), intended for logging or otherwise tracking the event. TODO: Not used, and has inconsistent args in different files. Update or remove. get_module - function that takes a descriptor and returns a corresponding module instance object. If the current user does not have access to that location, returns None. render_template - a function that takes (template_file, context), and returns rendered html. user - The user to base the random number generator seed off of for this request filestore - A filestore ojbect. Defaults to an instance of OSFS based at settings.DATA_DIR. xqueue - Dict containing XqueueInterface object, as well as parameters for the specific StudentModule: xqueue = {'interface': XQueueInterface object, 'callback_url': Callback into the LMS, 'queue_name': Target queuename in Xqueue} replace_urls - TEMPORARY - A function like static_replace.replace_urls that capa_module can use to fix up the static urls in ajax results. anonymous_student_id - Used for tracking modules with student id course_id - the course_id containing this module publish(event) - A function that allows XModules to publish events (such as grade changes) xblock_model_data - A function that constructs a model_data for an xblock from its corresponding descriptor cache - A cache object with two methods: .get(key) returns an object from the cache or None. .set(key, value, timeout_secs=None) stores a value in the cache with a timeout. can_execute_unsafe_code - A function returning a boolean, whether or not to allow the execution of unsafe, unsandboxed code. ''' self.ajax_url = ajax_url self.xqueue = xqueue self.track_function = track_function self.filestore = filestore self.get_module = get_module self.render_template = render_template self.DEBUG = self.debug = debug self.seed = user.id if user is not None else 0 self.replace_urls = replace_urls self.node_path = node_path self.anonymous_student_id = anonymous_student_id self.course_id = course_id self.user_is_staff = user is not None and user.is_staff self.xblock_model_data = xblock_model_data if publish is None: publish = lambda e: None self.publish = publish self.open_ended_grading_interface = open_ended_grading_interface self.s3_interface = s3_interface self.cache = cache or DoNothingCache() self.can_execute_unsafe_code = can_execute_unsafe_code or (lambda: False) self.replace_course_urls = replace_course_urls self.replace_jump_to_id_urls = replace_jump_to_id_urls def get(self, attr): ''' provide uniform access to attributes (like etree).''' return self.__dict__.get(attr) def set(self, attr, val): '''provide uniform access to attributes (like etree)''' self.__dict__[attr] = val def __repr__(self): return repr(self.__dict__) def __str__(self): return str(self.__dict__) class DoNothingCache(object): """A duck-compatible object to use in ModuleSystem when there's no cache.""" def get(self, _key): return None def set(self, key, value, timeout=None): pass
agpl-3.0
rapidminer/rapidminer-5
src/com/rapidminer/gui/look/fc/BookmarkList.java
5244
/* * 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.look.fc; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.SwingTools; /** * The list containing the bookmarks. * * @author Ingo Mierswa */ public class BookmarkList extends JList implements ListSelectionListener, MouseListener { private static final long serialVersionUID = -7109320787696008679L; private static class BookmarkCellRenderer implements ListCellRenderer { private JLabel label = new JLabel(); public BookmarkCellRenderer() { this.label.setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); this.label.setOpaque(true); this.label.setIcon(SwingTools.createIcon("16/star_yellow.png")); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Bookmark bookmark = (Bookmark)value; String name = bookmark.getName(); final String path = bookmark.getPath(); if (isSelected) { label.setBackground(UIManager.getColor("List.selectionBackground")); label.setForeground(UIManager.getColor("List.selectionForeground")); } else { label.setBackground(UIManager.getColor("List.background")); label.setForeground(UIManager.getColor("List.foreground")); } if (!new File(path).exists()) { label.setForeground(Color.GRAY); } label.setText(name); label.setToolTipText("<html><b>" + name + "</b><br>" + path + "</html>"); return label; } } private static final ListCellRenderer RENDERER = new BookmarkCellRenderer(); private FileList fileList; public BookmarkList(BookmarkListModel model, FileList fileList) { super(model); this.fileList = fileList; addListSelectionListener(this); addMouseListener(this); } @Override public ListCellRenderer getCellRenderer() { return RENDERER; } public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { Bookmark selectedBookmark = (Bookmark)getSelectedValue(); if (selectedBookmark != null) { String path = selectedBookmark.getPath(); File bookmarkFile = new File(path); if (bookmarkFile.exists() && bookmarkFile.canRead()) { fileList.filechooserUI.setCurrentDirectoryOfFileChooser(bookmarkFile); } else { JOptionPane.showConfirmDialog(fileList.fc, "Cannot access selected bookmark directory.", "Cannot access directory", JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE); } } } } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { int index = locationToIndex(e.getPoint()); setSelectedIndex(index); evaluatePopup(e); } public void mouseReleased(MouseEvent e) { evaluatePopup(e); } /** Checks if the given mouse event is a popup trigger and creates a new popup menu if necessary. */ private void evaluatePopup(MouseEvent e) { if (e.isPopupTrigger()) { JPopupMenu menu = createBookmarkPopupMenu(); if (menu != null) { menu.show(this, e.getX(), e.getY()); } } } private JPopupMenu createBookmarkPopupMenu() { final Bookmark bookmark = (Bookmark)getSelectedValue(); if (bookmark != null) { JPopupMenu bookmarksPopup = new JPopupMenu(); bookmarksPopup.add(new JMenuItem(new ResourceAction("file_chooser.rename_bookmark") { private static final long serialVersionUID = -3728467995967823779L; public void actionPerformed(ActionEvent e) { fileList.renameBookmark(bookmark); } })); bookmarksPopup.add(new JMenuItem(new ResourceAction("file_chooser.delete_bookmark") { private static final long serialVersionUID = 5432105038105200178L; public void actionPerformed(ActionEvent e) { fileList.deleteBookmark(bookmark); } })); return bookmarksPopup; } else { return null; } } }
agpl-3.0
leosac/leosac
test/Visitor.cpp
3152
/* Copyright (C) 2014-2016 Leosac This file is part of Leosac. Leosac 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. Leosac 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/>. */ #include "tools/Visitor.hpp" #include "tools/IVisitable.hpp" #include "gtest/gtest.h" using namespace Leosac; using namespace Leosac::Tools; namespace Leosac { namespace Test { struct DummyVisitable : public virtual IVisitable { DummyVisitable() = default; MAKE_VISITABLE(); }; struct DummyVisitor : public Visitor<DummyVisitable> { DummyVisitor() { } void visit(DummyVisitable &) override { visited_non_const_ = true; } void visit(const DummyVisitable &) override { visited_const_ = true; } bool visited_non_const_{false}; bool visited_const_{false}; }; TEST(TestVisitor, simple_non_const) { DummyVisitable visitable; DummyVisitor visitor; visitable.accept(visitor); ASSERT_TRUE(visitor.visited_non_const_); ASSERT_FALSE(visitor.visited_const_); } TEST(TestVisitor, simple_const) { const DummyVisitable visitable; DummyVisitor visitor; visitable.accept(visitor); ASSERT_TRUE(visitor.visited_const_); ASSERT_FALSE(visitor.visited_non_const_); } struct DummyConstOnlyVisitor : public Visitor<DummyVisitable> { DummyConstOnlyVisitor() : visited_const_(false) { } void visit(const DummyVisitable &) override { visited_const_ = true; } bool visited_const_; }; TEST(TestVisitor, const_visit_accept_non_const_visitable) { DummyVisitable visitable; DummyConstOnlyVisitor visitor; visitable.accept(visitor); ASSERT_TRUE(visitor.visited_const_); } TEST(TestVisitor, const_visit_accept_const_visitable) { const DummyVisitable visitable; DummyConstOnlyVisitor visitor; visitable.accept(visitor); ASSERT_TRUE(visitor.visited_const_); } /** * Visitor2 that is ready to visit object * of type DummyVisitable, but not of type * DummyChildVisitable. Yet, we try to * pass it a DummyChildVisitable */ struct DummyVisitor2 : public Visitor<DummyVisitable> { DummyVisitor2() = default; void visit(const DummyVisitable &) override { visited_ = true; } bool visited_{false}; }; struct DummyChildVisitable : public virtual DummyVisitable { DummyChildVisitable() = default; MAKE_VISITABLE_FALLBACK(DummyVisitable); }; TEST(TestVisitor, test_class_hierarchy) { DummyChildVisitable visitable; DummyVisitor2 visitor; visitable.accept(visitor); ASSERT_TRUE(visitor.visited_); } } }
agpl-3.0
BloatIt/bloatit
main/src/main/java/com/bloatit/framework/webprocessor/components/form/HtmlSimpleInput.java
2570
/* * Copyright (C) 2010 BloatIt. This file is part of BloatIt. BloatIt 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. * BloatIt 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 BloatIt. If not, see <http://www.gnu.org/licenses/>. */ package com.bloatit.framework.webprocessor.components.form; import com.bloatit.framework.webprocessor.components.meta.HtmlLeaf; /** * Meta class used to create various input fields */ public class HtmlSimpleInput extends HtmlLeaf { public enum InputType { TEXT_INPUT, PASSWORD_INPUT, FILE_INPUT, CHECKBOX_INPUT, RADIO_INPUT, BUTTON_INPUT, SUBMIT_INPUT, RESET_INPUT, HIDDEN_INPUT } private static final String TEXT = "text"; private static final String PASSWORD = "password"; private static final String FILE = "file"; private static final String CHECKBOX = "checkbox"; private static final String RADIO = "radio"; private static final String BUTTON = "button"; private static final String SUBMIT = "submit"; private static final String RESET = "reset"; private static final String HIDDEN = "hidden"; public HtmlSimpleInput(final String type) { super("input"); addAttribute("type", type); } protected final HtmlSimpleInput setName(final String name) { addAttribute("name", name).addAttribute("id", name); return this; } public static String getInput(final InputType type) { switch (type) { case TEXT_INPUT: return TEXT; case BUTTON_INPUT: return BUTTON; case CHECKBOX_INPUT: return CHECKBOX; case FILE_INPUT: return FILE; case HIDDEN_INPUT: return HIDDEN; case PASSWORD_INPUT: return PASSWORD; case RADIO_INPUT: return RADIO; case RESET_INPUT: return RESET; case SUBMIT_INPUT: return SUBMIT; default: assert false; return TEXT; } } }
agpl-3.0
KrzysiekJ/bestja
addons/message_template/models.py
4383
# -*- coding: utf-8 -*- from urlparse import urljoin from openerp import models, fields, api, tools from openerp.addons.email_template.email_template import mako_template_env class MessageTemplate(models.Model): _name = 'message_template' subject = fields.Char() body = fields.Text() model = fields.Char() @api.one def send(self, recipients, sender=None, record=None, record_name=None): recipient_partners = [] for recipient in recipients: recipient_partners.append( (4, recipient.sudo().partner_id.id) ) subtype = None if not sender: sender = self.env.ref('message_template.user_messages') subtype = self.env.ref('message_template.subtype_system_message') base_url = self.env['ir.config_parameter'].get_param('web.base.url') def link_to(record): """ Create an absolute link to the given record. """ path = '/web#id={}&model={}'.format(record.id, record._name) return urljoin(base_url, path) # Enable resolution of ${variables} inside body template_context = { 'record': record, 'context': self.env.context, 'base_url': base_url, 'link_to': link_to, 'site_name': self.env.user.company_id.name, } body_template = mako_template_env.from_string(tools.ustr(self.body)) body_rendered = body_template.render(template_context) subject_template = mako_template_env.from_string(tools.ustr(self.subject)) subject_rendered = subject_template.render(template_context) self.env['mail.message'].sudo().create({ 'type': 'comment', 'author_id': sender.sudo().partner_id.id, 'partner_ids': recipient_partners, 'model': self.model, 'res_id': record and record.id, 'record_name': record_name or (record and record.display_name), 'subject': subject_rendered, 'body': body_rendered, 'template': self.id, 'subtype_id': subtype and subtype.id }) @api.multi def send_group(self, group, sender=None, record=None, record_name=None): """ Send a message to all users in a group `group`. """ group_obj = self.env.ref(group) self.send( recipients=group_obj.sudo().users, sender=sender, record=record, record_name=record_name, ) class MessageTemplateMixin(models.AbstractModel): """ This mixin enables model's records to be used with Odoo messages and adds `send` and `send_group` methods to the model. """ _name = 'message_template.mixin' @api.one def send(self, template, recipients, sender=None, record_name=None): return self.env.ref(template).send( recipients=recipients, sender=sender, record=self, record_name=record_name, ) @api.one def send_group(self, template, group, sender=None, record_name=None): return self.env.ref(template).send_group( group=group, sender=sender, record=self, record_name=record_name, ) @api.multi def message_get_suggested_recipients(self): """ Used by the messages module (in JS code). No, we don't want to add additional recipients, Odoo. Thanks, but no thanks. """ return [] @api.model def message_redirect_action(self): """ Used by the messages module (in JS code). Returns an action for displaying the related record. """ return self.env['mail.thread'].message_redirect_action() def message_post(self, *args, **kwargs): """ Used by the messages module to reply in a thread. """ return self.pool['mail.thread'].message_post(*args, **kwargs) @api.model def _get_access_link(self, mail, partner): """ Used to generate a link to the associated object in e-mail notification. """ return self.env['mail.thread']._get_access_link(mail, partner) class MailMessage(models.Model): _inherit = 'mail.message' template = fields.Many2one('message_template')
agpl-3.0
edx/ecommerce
ecommerce/enterprise/exceptions.py
167
""" Exceptions used by the Enterprise app. """ class EnterpriseDoesNotExist(Exception): """ Exception for errors related to Enterprise service data. """
agpl-3.0
LinxHQ/LinxCloud
linxbooks/protected/modules/lbExpenses/views/default/_search.php
1539
<?php /* @var $this LbExpensesController */ /* @var $model LbExpenses */ /* @var $form CActiveForm */ ?> <div class="wide form"> <?php $form=$this->beginWidget('CActiveForm', array( 'action'=>Yii::app()->createUrl($this->route), 'method'=>'get', )); ?> <div class="row"> <?php echo $form->label($model,'lb_record_primary_key'); ?> <?php echo $form->textField($model,'lb_record_primary_key'); ?> </div> <div class="row"> <?php echo $form->label($model,'lb_category_id'); ?> <?php echo $form->textField($model,'lb_category_id'); ?> </div> <div class="row"> <?php echo $form->label($model,'lb_expenses_amount'); ?> <?php echo $form->textField($model,'lb_expenses_amount',array('size'=>10,'maxlength'=>10)); ?> </div> <div class="row"> <?php echo $form->label($model,'lb_expenses_date'); ?> <?php echo $form->textField($model,'lb_expenses_date'); ?> </div> <div class="row"> <?php echo $form->label($model,'lb_expenses_recurring_id'); ?> <?php echo $form->textField($model,'lb_expenses_recurring_id'); ?> </div> <div class="row"> <?php echo $form->label($model,'lb_expenses_brank_account_id'); ?> <?php echo $form->textField($model,'lb_expenses_brank_account_id'); ?> </div> <div class="row"> <?php echo $form->label($model,'lb_expenses_note'); ?> <?php echo $form->textField($model,'lb_expenses_note',array('size'=>60,'maxlength'=>500)); ?> </div> <div class="row buttons"> <?php echo CHtml::submitButton('Search'); ?> </div> <?php $this->endWidget(); ?> </div><!-- search-form -->
agpl-3.0
hrayr-artunyan/shuup
shuup/admin/forms/__init__.py
315
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from ._base import ShuupAdminForm __all__ = [ "ShuupAdminForm", ]
agpl-3.0
victori/gitorious-jruby
test/unit/repository_test.rb
41731
# encoding: utf-8 #-- # Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) # # 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/>. #++ require File.dirname(__FILE__) + '/../test_helper' require "ostruct" class RepositoryTest < ActiveSupport::TestCase def new_repos(opts={}) Repository.new({ :name => "foo", :project => projects(:johans), :user => users(:johan), :owner => users(:johan) }.merge(opts)) end def setup @repository = new_repos FileUtils.mkdir_p(@repository.full_repository_path, :mode => 0755) end def teardown clear_message_queue end should_validate_presence_of :user_id, :name, :owner_id should_validate_uniqueness_of :hashed_path should_validate_uniqueness_of :name, :scoped_to => :project_id, :case_sensitive => false should_have_many :hooks, :dependent => :destroy should " only accept names with alphanum characters in it" do @repository.name = "foo bar" assert !@repository.valid?, 'valid? should be false' @repository.name = "foo!bar" assert !@repository.valid?, 'valid? should be false' @repository.name = "foobar" assert @repository.valid? @repository.name = "foo42" assert @repository.valid? end should "has a unique name within a project" do @repository.save repos = new_repos(:name => "FOO") assert !repos.valid?, 'valid? should be false' assert_not_nil repos.errors.on(:name) assert new_repos(:project => projects(:moes)).valid? end should "not have a reserved name" do repo = new_repos(:name => Gitorious::Reservations.repository_names.first.dup) repo.valid? assert_not_nil repo.errors.on(:name) RepositoriesController.action_methods.each do |action| repo.name = action.dup repo.valid? assert_not_nil repo.errors.on(:name), "fail on #{action}" end end context "git urls" do setup do @host_with_user = "#{GitoriousConfig['gitorious_user']}@#{GitoriousConfig['gitorious_host']}" @host = "#{GitoriousConfig['gitorious_host']}" end should "has a gitdir name" do assert_equal "#{@repository.project.slug}/foo.git", @repository.gitdir end should "has a push url" do assert_equal "#{@host_with_user}:#{@repository.project.slug}/foo.git", @repository.push_url end should "has a clone url" do assert_equal "git://#{@host}/#{@repository.project.slug}/foo.git", @repository.clone_url end should "has a http url" do assert_equal "#{GitoriousConfig['scheme']}://git.#{@host}/#{@repository.project.slug}/foo.git", @repository.http_clone_url end should "use the real http cloning URL" do old_value = Site::HTTP_CLONING_SUBDOMAIN silence_warnings do Site::HTTP_CLONING_SUBDOMAIN = "whatever" end assert_equal "#{GitoriousConfig['scheme']}://whatever.#{@host}/#{@repository.project.slug}/foo.git", @repository.http_clone_url silence_warnings {Site::HTTP_CLONING_SUBDOMAIN = old_value} end should "has a clone url with the project name, if it is a mainline" do @repository.owner = groups(:team_thunderbird) @repository.kind = Repository::KIND_PROJECT_REPO assert_equal "git://#{@host}/#{@repository.project.slug}/foo.git", @repository.clone_url end should "have a clone url with the team/user, if it is not a mainline" do @repository.kind = Repository::KIND_TEAM_REPO url = "git://#{@host}/#{@repository.owner.to_param_with_prefix}/#{@repository.project.slug}/foo.git" assert_equal url, @repository.clone_url @repository.kind = Repository::KIND_USER_REPO @repository.owner = users(:johan) url = "git://#{@host}/#{users(:johan).to_param_with_prefix}/#{@repository.project.slug}/foo.git" assert_equal url, @repository.clone_url end should "has a push url with the project name, if it is a mainline" do @repository.owner = groups(:team_thunderbird) @repository.kind = Repository::KIND_PROJECT_REPO assert_equal "#{@host_with_user}:#{@repository.project.slug}/foo.git", @repository.push_url end should "have a push url with the team/user, if it is not a mainline" do @repository.owner = groups(:team_thunderbird) @repository.kind = Repository::KIND_TEAM_REPO url = "#{@host_with_user}:#{groups(:team_thunderbird).to_param_with_prefix}/#{@repository.project.slug}/foo.git" assert_equal url, @repository.push_url @repository.kind = Repository::KIND_USER_REPO @repository.owner = users(:johan) url = "#{@host_with_user}:#{users(:johan).to_param_with_prefix}/#{@repository.project.slug}/foo.git" assert_equal url, @repository.push_url end should "has a http clone url with the project name, if it is a mainline" do @repository.owner = groups(:team_thunderbird) @repository.kind = Repository::KIND_PROJECT_REPO assert_equal "#{GitoriousConfig['scheme']}://git.#{@host}/#{@repository.project.slug}/foo.git", @repository.http_clone_url end should "have a http clone url with the team/user, if it is not a mainline" do @repository.owner = groups(:team_thunderbird) @repository.kind = Repository::KIND_TEAM_REPO url = "#{GitoriousConfig['scheme']}://git.#{@host}/#{groups(:team_thunderbird).to_param_with_prefix}/#{@repository.project.slug}/foo.git" assert_equal url, @repository.http_clone_url @repository.owner = users(:johan) @repository.kind = Repository::KIND_USER_REPO url = "#{GitoriousConfig['scheme']}://git.#{@host}/#{users(:johan).to_param_with_prefix}/#{@repository.project.slug}/foo.git" assert_equal url, @repository.http_clone_url end should "has a full repository_path" do expected_dir = File.expand_path(File.join(GitoriousConfig["repository_base_path"], "#{@repository.full_hashed_path}.git")) assert_equal expected_dir, @repository.full_repository_path end should "always display SSH URLs when so instructed" do old_value = GitoriousConfig["always_display_ssh_url"] GitoriousConfig["always_display_ssh_url"] = true assert @repository.display_ssh_url?(users(:moe)) GitoriousConfig["always_display_ssh_url"] = old_value end end should "inits the git repository" do path = @repository.full_repository_path Repository.git_backend.expects(:create).with(path).returns(true) Repository.create_git_repository(@repository.real_gitdir) assert File.exist?(path), 'File.exist?(path) should be true' Dir.chdir(path) do hooks = File.join(path, "hooks") assert File.exist?(hooks), 'File.exist?(hooks) should be true' assert File.symlink?(hooks), 'File.symlink?(hooks) should be true' assert File.symlink?(File.expand_path(File.readlink(hooks))), 'File.symlink?(File.expand_path(File.readlink(hooks))) should be true' end end should "clones a git repository" do source = repositories(:johans) target = @repository target_path = @repository.full_repository_path git_backend = mock("Git backend") Repository.expects(:git_backend).returns(git_backend) git_backend.expects(:clone).with(target.full_repository_path, source.full_repository_path).returns(true) Repository.expects(:create_hooks).returns(true) assert Repository.clone_git_repository(target.real_gitdir, source.real_gitdir) end should "not create hooks if the :skip_hooks option is set to true" do source = repositories(:johans) target = @repository target_path = @repository.full_repository_path git_backend = mock("Git backend") Repository.expects(:git_backend).returns(git_backend) git_backend.expects(:clone).with(target.full_repository_path, source.full_repository_path).returns(true) Repository.expects(:create_hooks).never Repository.clone_git_repository(target.real_gitdir, source.real_gitdir, :skip_hooks => true) end should " create the hooks" do hooks = "/path/to/hooks" path = "/path/to/repository" base_path = "#{RAILS_ROOT}/data/hooks" File.expects(:join).in_sequence.with(GitoriousConfig["repository_base_path"], ".hooks").returns(hooks) Dir.expects(:chdir).in_sequence.with(path).yields(nil) File.expects(:symlink?).in_sequence.with(hooks).returns(false) File.expects(:exist?).in_sequence.with(hooks).returns(false) FileUtils.expects(:ln_s).in_sequence.with(base_path, hooks) local_hooks = "/path/to/local/hooks" File.expects(:join).in_sequence.with(path, "hooks").returns(local_hooks) File.expects(:exist?).in_sequence.with(local_hooks).returns(true) File.expects(:join).with(path, "description").in_sequence File.expects(:open).in_sequence.returns(true) assert Repository.create_hooks(path) end should "deletes a repository" do Repository.git_backend.expects(:delete!).with(@repository.full_repository_path).returns(true) Repository.delete_git_repository(@repository.real_gitdir) end should "knows if has commits" do @repository.stubs(:new_record?).returns(false) @repository.stubs(:ready?).returns(true) git_mock = mock("Grit::Git") @repository.stubs(:git).returns(git_mock) head = mock("head") head.stubs(:name).returns("master") @repository.git.expects(:heads).returns([head]) assert @repository.has_commits?, '@repository.has_commits? should be true' end should "knows if has commits, unless its a new record" do @repository.stubs(:new_record?).returns(false) assert !@repository.has_commits?, '@repository.has_commits? should be false' end should "knows if has commits, unless its not ready" do @repository.stubs(:ready?).returns(false) assert !@repository.has_commits?, '@repository.has_commits? should be false' end should " build a new repository by cloning another one" do repos = Repository.new_by_cloning(@repository) assert_equal @repository, repos.parent assert_equal @repository.project, repos.project assert repos.new_record?, 'new_record? should be true' end should "inherit merge request inclusion from its parent" do @repository.update_attribute(:merge_requests_enabled, true) clone = Repository.new_by_cloning(@repository) assert clone.merge_requests_enabled? @repository.update_attribute(:merge_requests_enabled, false) clone = Repository.new_by_cloning(@repository) assert !clone.merge_requests_enabled? end should "suggests a decent name for a cloned repository bsed on username" do repos = Repository.new_by_cloning(@repository, username="johan") assert_equal "johans-foo", repos.name repos = Repository.new_by_cloning(@repository, username=nil) assert_equal nil, repos.name end should "has it is name as its to_param value" do @repository.save assert_equal @repository.name, @repository.to_param end should "finds a repository by name or raises" do assert_equal repositories(:johans), Repository.find_by_name!(repositories(:johans).name) assert_raises(ActiveRecord::RecordNotFound) do Repository.find_by_name!("asdasdasd") end end context "find_by_path" do should "finds a repository by its path" do repo = repositories(:johans) path = File.join(GitoriousConfig['repository_base_path'], projects(:johans).slug, "#{repo.name}.git") assert_equal repo, Repository.find_by_path(path) end should_eventually "finds a repository by its path, regardless of repository kind" do repo = projects(:johans).wiki_repository path = File.join(GitoriousConfig['repository_base_path'].chomp("/"), projects(:johans).slug, "#{repo.name}.git") assert_equal repo, Repository.find_by_path(path) end should "finds a group repository by its path" do repo = repositories(:johans) repo.owner = groups(:team_thunderbird) repo.kind = Repository::KIND_TEAM_REPO repo.save! path = File.join(GitoriousConfig['repository_base_path'], repo.gitdir) assert_equal repo, Repository.find_by_path(path) end should "finds a user repository by its path" do repo = repositories(:johans) repo.owner = users(:johan) repo.kind = Repository::KIND_USER_REPO repo.save! path = File.join(GitoriousConfig['repository_base_path'], repo.gitdir) assert_equal repo, Repository.find_by_path(path) end should "scope the find by project id" do repo = repositories(:johans) repo.owner = groups(:team_thunderbird) repo.kind = Repository::KIND_TEAM_REPO repo.save! same_name_repo = new_repos(:name => repo.name) same_name_repo same_name_repo.project = projects(:moes) same_name_repo.owner = groups(:team_thunderbird) same_name_repo.kind = Repository::KIND_TEAM_REPO same_name_repo.save! path = File.join(GitoriousConfig['repository_base_path'], same_name_repo.gitdir) assert_equal same_name_repo, Repository.find_by_path(path) end end context "#to_xml" do should "xmlilizes git paths as well" do assert @repository.to_xml.include?("<clone-url>") assert @repository.to_xml.include?("<push-url>") end should "include a description of the kind" do assert_match(/<kind>mainline<\/kind>/, @repository.to_xml) @repository.kind = Repository::KIND_TEAM_REPO assert_match(/<kind>team<\/kind>/, @repository.to_xml) end should "include the project name" do assert_match(/<project>#{@repository.project.slug}<\/project>/, @repository.to_xml) end should "include the owner" do assert_match(/<owner kind="User">johan<\/owner>/, @repository.to_xml) end end context "#writable_by?" do should "knows if a user can write to self" do @repository.owner = users(:johan) @repository.save! @repository.reload assert @repository.writable_by?(users(:johan)) assert !@repository.writable_by?(users(:mike)) @repository.change_owner_to!(groups(:team_thunderbird)) @repository.save! assert !@repository.writable_by?(users(:johan)) @repository.owner.add_member(users(:moe), Role.member) @repository.committerships.reload assert @repository.writable_by?(users(:moe)) end context "a wiki repository" do setup do @repository.kind = Repository::KIND_WIKI end should "be writable by everyone" do @repository.wiki_permissions = Repository::WIKI_WRITABLE_EVERYONE [:johan, :mike, :moe].each do |login| assert @repository.writable_by?(users(login)), "not writable_by #{login}" end end should "only be writable by project members" do @repository.wiki_permissions = Repository::WIKI_WRITABLE_PROJECT_MEMBERS assert @repository.project.member?(users(:johan)) assert @repository.writable_by?(users(:johan)) assert !@repository.project.member?(users(:moe)) assert !@repository.writable_by?(users(:moe)) end end end should "publishe a message on create and update" do @repository.save! assert_published("/queue/GitoriousRepositoryCreation", { "command" => "create_git_repository", "target_id" => @repository.id, "arguments" => [@repository.real_gitdir] }) end should "publishe a message on clone" do @repository.parent = repositories(:johans) @repository.save! assert_published("/queue/GitoriousRepositoryCreation", { "command" => "clone_git_repository", "target_id" => @repository.id, "arguments" => [@repository.real_gitdir, @repository.parent.real_gitdir] }) end should "create a notification on destroy" do @repository.save! @repository.destroy assert_published("/queue/GitoriousRepositoryDeletion", { "command" => "delete_git_repository", "arguments" => [@repository.real_gitdir] }) end should "has one recent commit" do @repository.save! repos_mock = mock("Git mock") commit_mock = stub_everything("Git::Commit mock") repos_mock.expects(:commits).with("master", 1).returns([commit_mock]) @repository.stubs(:git).returns(repos_mock) @repository.stubs(:has_commits?).returns(true) heads_stub = mock("head") heads_stub.stubs(:name).returns("master") @repository.stubs(:head_candidate).returns(heads_stub) assert_equal commit_mock, @repository.last_commit end should "has one recent commit within a given ref" do @repository.save! repos_mock = mock("Git mock") commit_mock = stub_everything("Git::Commit mock") repos_mock.expects(:commits).with("foo", 1).returns([commit_mock]) @repository.stubs(:git).returns(repos_mock) @repository.stubs(:has_commits?).returns(true) @repository.expects(:head_candidate).never assert_equal commit_mock, @repository.last_commit("foo") end context "deletion" do setup do @repository.kind = Repository::KIND_PROJECT_REPO @repository.project.repositories << new_repos(:name => "another") @repository.save! @repository.committerships.create!({ :committer => users(:moe), :permissions => (Committership::CAN_REVIEW | Committership::CAN_COMMIT) }) end should "be deletable by admins" do assert @repository.admin?(users(:johan)) assert !@repository.admin?(users(:moe)) assert @repository.can_be_deleted_by?(users(:johan)) assert !@repository.can_be_deleted_by?(users(:moe)) end should "always be deletable if admin and non-project repo" do @repository.kind = Repository::KIND_TEAM_REPO assert @repository.can_be_deleted_by?(users(:johan)) assert !@repository.can_be_deleted_by?(users(:moe)) end should "also be deletable by users with admin privs" do @repository.kind = Repository::KIND_TEAM_REPO cs = @repository.committerships.create_with_permissions!({ :committer => users(:mike) }, Committership::CAN_ADMIN) assert @repository.can_be_deleted_by?(users(:johan)) assert @repository.can_be_deleted_by?(users(:mike)) end end should "have a git method that accesses the repository" do # FIXME: meh for stubbing internals, need to refactor that part in Grit File.expects(:exist?).at_least(1).with("#{@repository.full_repository_path}/.git").returns(false) File.expects(:exist?).at_least(1).with(@repository.full_repository_path).returns(true) assert_instance_of Grit::Repo, @repository.git assert_equal @repository.full_repository_path, @repository.git.path end should "have a head_candidate" do head_stub = mock("head") head_stub.stubs(:name).returns("master") git = mock("git backend") @repository.stubs(:git).returns(git) git.expects(:head).returns(head_stub) @repository.expects(:has_commits?).returns(true) assert_equal head_stub, @repository.head_candidate end should "have a head_candidate, unless it does not have commits" do @repository.expects(:has_commits?).returns(false) assert_equal nil, @repository.head_candidate end should "has paginated_commits" do git = mock("git") commits = [mock("commit"), mock("commit")] @repository.expects(:git).times(2).returns(git) git.expects(:commit_count).returns(120) git.expects(:commits).with("foo", 30, 30).returns(commits) commits = @repository.paginated_commits("foo", 2, 30) assert_instance_of WillPaginate::Collection, commits end should "has a count_commits_from_last_week_by_user of 0 if no commits" do @repository.expects(:has_commits?).returns(false) assert_equal 0, @repository.count_commits_from_last_week_by_user(users(:johan)) end should "returns a set of users from a list of commits" do commits = [] users(:johan, :moe).map do |u| committer = OpenStruct.new(:email => u.email) commits << OpenStruct.new(:committer => committer, :author => committer) end users = Repository.users_by_commits(commits) assert_equal users(:johan, :moe).map(&:email).sort, users.keys.sort assert_equal users(:johan, :moe).map(&:login).sort, users.values.map(&:login).sort end should "know if it is a normal project repository" do assert @repository.project_repo?, '@repository.project_repo? should be true' end should "know if it is a wiki repo" do @repository.kind = Repository::KIND_WIKI assert @repository.wiki?, '@repository.wiki? should be true' end should "has a parent, which is the owner" do @repository.kind = Repository::KIND_TEAM_REPO @repository.owner = groups(:team_thunderbird) assert_equal groups(:team_thunderbird), @repository.breadcrumb_parent @repository.kind = Repository::KIND_USER_REPO @repository.owner = users(:johan) assert_equal users(:johan), @repository.breadcrumb_parent end should "has a parent, which is the project for mainlines" do @repository.kind = Repository::KIND_PROJECT_REPO @repository.owner = groups(:team_thunderbird) assert_equal projects(:johans), @repository.breadcrumb_parent @repository.owner = users(:johan) assert_equal projects(:johans), @repository.breadcrumb_parent end should " return its name as title" do assert_equal @repository.title, @repository.name end should "return the project title as owner_title if it is a mainline" do @repository.kind = Repository::KIND_PROJECT_REPO assert_equal @repository.project.title, @repository.owner_title end should "return the owner title as owner_title if it is not a mainline" do @repository.kind = Repository::KIND_TEAM_REPO assert_equal @repository.owner.title, @repository.owner_title end should "returns a list of committers depending on owner type" do repo = repositories(:johans2) repo.committerships.each(&:delete) repo.reload assert !repo.committers.include?(users(:moe)) repo.committerships.create_with_permissions!({ :committer => users(:johan) }, Committership::CAN_COMMIT) assert_equal [users(:johan).login], repo.committers.map(&:login) repo.committerships.create_with_permissions!({ :committer => groups(:team_thunderbird) }, Committership::CAN_COMMIT) exp_users = groups(:team_thunderbird).members.unshift(users(:johan)) assert_equal exp_users.map(&:login), repo.committers.map(&:login) groups(:team_thunderbird).add_member(users(:moe), Role.admin) repo.reload assert repo.committers.include?(users(:moe)) end should "know you can request merges from it" do repo = repositories(:johans2) assert !repo.mainline? assert repo.committer?(users(:mike)) assert repo.can_request_merge?(users(:mike)) repo.kind = Repository::KIND_PROJECT_REPO assert repo.mainline? assert !repo.can_request_merge?(users(:mike)), "mainlines should not request merges" end should "sets a hash on create" do assert @repository.new_record?, '@repository.new_record? should be true' @repository.save! assert_not_nil @repository.hashed_path assert_equal 3, @repository.hashed_path.split("/").length assert_match(/[a-z0-9\/]{42}/, @repository.hashed_path) end should "create the initial committership on create for owner" do group_repo = new_repos(:owner => groups(:team_thunderbird)) assert_difference("Committership.count") do group_repo.save! assert_equal 1, group_repo.committerships.count assert_equal groups(:team_thunderbird), group_repo.committerships.first.committer end user_repo = new_repos(:owner => users(:johan), :name => "foo2") assert_difference("Committership.count") do user_repo.save! assert_equal 1, user_repo.committerships.count cs = user_repo.committerships.first assert_equal users(:johan), cs.committer [:reviewer?, :committer?, :admin?].each do |m| assert cs.send(m), "should have #{m} permissions" end end end should "know the full hashed path" do assert_equal @repository.hashed_path, @repository.full_hashed_path end should "allow changing ownership from a user to a group" do repo = repositories(:johans) repo.change_owner_to!(groups(:team_thunderbird)) assert_equal groups(:team_thunderbird), repo.owner repo.change_owner_to!(users(:johan)) assert_equal groups(:team_thunderbird), repo.owner end should "not change kind when it is a project repo and changing owner" do repo = repositories(:johans) repo.change_owner_to!(groups(:team_thunderbird)) assert_equal groups(:team_thunderbird), repo.owner assert_equal Repository::KIND_PROJECT_REPO, repo.kind end should "change kind when changing owner" do repo = repositories(:johans) repo.update_attribute(:kind, Repository::KIND_USER_REPO) assert repo.user_repo? repo.change_owner_to!(groups(:team_thunderbird)) assert_equal groups(:team_thunderbird), repo.owner assert repo.team_repo? end should "changing ownership adds the new owner to the committerships" do repo = repositories(:johans) old_committer = repo.owner repo.change_owner_to!(groups(:team_thunderbird)) assert !repo.committers.include?(old_committer) assert repo.committers.include?(groups(:team_thunderbird).members.first) [:reviewer?, :committer?, :admin?].each do |m| assert repo.committerships.last.send(m), "cannot #{m}" end end should "downcases the name before validation" do repo = new_repos(:name => "FOOBAR") repo.save! assert_equal "foobar", repo.reload.name end should "have a project_or_owner" do repo = repositories(:johans) assert repo.project_repo? assert_equal repo.project, repo.project_or_owner repo.kind = Repository::KIND_TEAM_REPO repo.owner = groups(:team_thunderbird) assert_equal repo.owner, repo.project_or_owner repo.kind = Repository::KIND_TEAM_REPO repo.owner = groups(:team_thunderbird) assert_equal repo.owner, repo.project_or_owner end context "participant groups" do setup do @repo = repositories(:moes) end should "includes the groups' members in #committers" do assert @repo.committers.include?(groups(:team_thunderbird).members.first) end should "only include unique users in #committers" do groups(:team_thunderbird).add_member(users(:moe), Role.member) assert_equal 1, @repo.committers.select{|u| u == users(:moe)}.size end should "not include committerships without a commit permission bit" do assert_equal 1, @repo.committerships.count cs = @repo.committerships.first cs.build_permissions(:review) cs.save! assert_equal [], @repo.committers.map(&:login) end should "return a list of reviewers" do assert !@repo.reviewers.map(&:login).include?(users(:moe).login) @repo.committerships.create_with_permissions!({ :committer => users(:moe) }, Committership::CAN_REVIEW) assert @repo.reviewers.map(&:login).include?(users(:moe).login) end context "permission helpers" do setup do @cs = @repo.committerships.first @cs.permissions = 0 @cs.save! end should "know if a user is a committer" do assert !@repo.committer?(@cs.committer) @cs.build_permissions(:commit); @cs.save assert !@repo.committer?(:false) assert !@repo.committer?(@cs.committer) end should "know if a user is a reviewer" do assert !@repo.reviewer?(@cs.committer) @cs.build_permissions(:review); @cs.save assert !@repo.reviewer?(:false) assert !@repo.reviewer?(@cs.committer) end should "know if a user is a admin" do assert !@repo.admin?(@cs.committer) @cs.build_permissions(:commit, :admin); @cs.save assert !@repo.admin?(:false) assert !@repo.admin?(@cs.committer) end end end context 'owners as User or Group' do setup do @repo = repositories(:moes) end should "return a list of the users who are admin for the repository if owned_by_group?" do @repo.change_owner_to!(groups(:a_team)) assert_equal([users(:johan)], @repo.owners) end should 'not throw an error if transferring ownership to a group if the group is already a committer' do @repo.change_owner_to!(groups(:team_thunderbird)) assert_equal([users(:mike)], @repo.owners) end should 'return the owner if owned by user' do @repo.change_owner_to!(users(:moe)) assert_equal([users(:moe)], @repo.owners) end end should "create an event on create if it is a project repo" do repo = new_repos repo.kind = Repository::KIND_PROJECT_REPO assert_difference("repo.project.events.count") do repo.save! end assert_equal repo, Event.last.target assert_equal Action::ADD_PROJECT_REPOSITORY, Event.last.action end context "find_by_name_in_project" do should "find with a project" do Repository.expects(:find_by_name_and_project_id!).with(repositories(:johans).name, projects(:johans).id).once Repository.find_by_name_in_project!(repositories(:johans).name, projects(:johans)) end should "find without a project" do Repository.expects(:find_by_name!).with(repositories(:johans).name).once Repository.find_by_name_in_project!(repositories(:johans).name) end end context 'Signoff of merge requests' do setup do @project = projects(:johans) @mainline_repository = repositories(:johans) @other_repository = repositories(:johans2) end should 'know that the mainline repository requires signoff of merge requests' do assert @mainline_repository.mainline? assert @mainline_repository.requires_signoff_on_merge_requests? end should 'not require signoff of merge requests in other repositories' do assert !@other_repository.mainline? assert !@other_repository.requires_signoff_on_merge_requests? end end context "Merge request status tags" do setup {@repo = repositories(:johans)} should "have a list of used status tags" do @repo.merge_requests.last.update_attribute(:status_tag, "worksforme") assert_equal %w[open worksforme], @repo.merge_request_status_tags end end context "Thottling" do setup{ Repository.destroy_all } should "throttle on create" do assert_nothing_raised do 5.times{|i| new_repos(:name => "wifebeater#{i}").save! } end assert_no_difference("Repository.count") do assert_raises(RecordThrottling::LimitReachedError) do new_repos(:name => "wtf-are-you-doing-bro").save! end end end end context 'Logging updates' do setup {@repository = repositories(:johans)} should 'generate events for each value that is changed' do assert_incremented_by(@repository.events, :size, 1) do @repository.log_changes_with_user(users(:johan)) do @repository.replace_value(:name, "new_name") end assert @repository.save end assert_equal 'new_name', @repository.reload.name end should 'not generate events when blank values are provided' do assert_incremented_by(@repository.events, :size, 0) do @repository.log_changes_with_user(users(:johan)) do @repository.replace_value(:name, "") end end end should "allow blank updates if we say it is ok" do @repository.update_attribute(:description, "asdf") @repository.log_changes_with_user(users(:johan)) do @repository.replace_value(:description, "", true) end @repository.save! assert @repository.reload.description.blank?, "desc: #{@repository.description.inspect}" end should 'not generate events when invalid values are provided' do assert_incremented_by(@repository.events, :size, 0) do @repository.log_changes_with_user(users(:johan)) do @repository.replace_value(:name, "Some illegal value") end end end should 'not generate events when a value is unchanged' do assert_incremented_by(@repository.events, :size, 0) do @repository.log_changes_with_user(users(:johan)) do @repository.replace_value(:name, @repository.name) end end end end context "changing the HEAD" do setup do @grit = Grit::Repo.new(grit_test_repo("dot_git"), :is_bare => true) @repository.stubs(:git).returns(@grit) end should "change the head" do assert the_head = @grit.get_head("test/master") @grit.expects(:update_head).with(the_head).returns(true) @repository.head = the_head.name end should "not change the head if given a nonexistant ref" do @grit.expects(:update_head).never @repository.head = "non-existant" @repository.head = nil @repository.head = "" end should "change the head, even if the current head is nil" do assert the_head = @grit.get_head("test/master") @grit.expects(:head).returns(nil) @grit.expects(:update_head).with(the_head).returns(true) @repository.head = the_head.name end end context 'Merge request repositories' do setup do @project = Factory.create(:user_project) @main_repo = Factory.create(:repository, :project => @project, :owner => @project.owner, :user => @project.user) end should 'initially not have a merge request repository' do assert !@main_repo.has_tracking_repository? end should 'generate a tracking repository' do @merge_repo = @main_repo.create_tracking_repository assert @main_repo.project_repo? assert @merge_repo.tracking_repo? assert_equal @main_repo, @merge_repo.parent assert_equal @main_repo.owner, @merge_repo.owner assert_equal @main_repo.user, @merge_repo.user assert @main_repo.has_tracking_repository? assert_equal @merge_repo, @main_repo.tracking_repository end should 'not post a repository creation message for merge request repositories' do @merge_repo = @main_repo.build_tracking_repository @merge_repo.expects(:publish).never assert @merge_repo.save end end context "Merge requests enabling" do setup do @repository = Repository.new end should "by default allow merge requests" do assert @repository.merge_requests_enabled? end end context "garbage collection" do setup do @repository = repositories(:johans) @now = Time.now Time.stubs(:now).returns(@now) @repository.stubs(:git).returns(stub()) @repository.git.expects(:gc_auto).returns(true) end should "have a gc! method that updates last_gc_at" do assert_nil @repository.last_gc_at assert @repository.gc! assert_not_nil @repository.last_gc_at assert_equal @now, @repository.last_gc_at end should "set push_count_since_gc to 0 when doing gc" do @repository.push_count_since_gc = 10 @repository.gc! assert_equal 0, @repository.push_count_since_gc end end context "Fresh repositories" do setup do Repository.destroy_all @me = Factory.create(:user, :login => "johnnie") @project = Factory.create(:project, :user => @me, :owner => @me) @repo = Factory.create(:repository, :project => @project, :owner => @project, :user => @me) @users = %w(bill steve jack nellie).map { | login | Factory.create(:user, :login => login) } @user_repos = @users.map do |u| new_repo = Repository.new_by_cloning(@repo) new_repo.name = "#{u.login}s-clone" new_repo.user = u new_repo.owner = u new_repo.kind = Repository::KIND_USER_REPO new_repo.last_pushed_at = 1.hour.ago assert new_repo.save new_repo end end should "include repositories recently pushed to" do assert @project.repositories.reload.by_users.fresh(2).include?(@user_repos.first) end should "not include repositories last pushed to in the middle ages" do older_repo = @user_repos.pop older_repo.last_pushed_at = 500.years.ago older_repo.save assert !@project.repositories.by_users.fresh(2).include?(older_repo) end end context "Searching clones" do setup do @repo = repositories(:johans) @clone = repositories(:johans2) end should "find clones matching an owning group's name" do assert @repo.clones.include?(@clone) assert @repo.search_clones("sproject").include?(@clone) end context "by user name" do setup do @repo = repositories(:moes) @clone = repositories(:johans_moe_clone) users(:johan).update_attribute(:login, "rohan") @clone.update_attribute(:name, "rohans-clone-of-moes") end should "match users with a matching name" do assert_includes(@repo.search_clones("rohan"), @clone) end should "not match user with diverging name" do assert_not_includes(@repo.search_clones("johan"), @clone) end end context "by group name" do setup do @repo = repositories(:johans) @clone = repositories(:johans2) end should "match groups with a matching name" do assert_includes(@repo.search_clones("thunderbird"), @clone) end should "not match groups with diverging name" do assert_not_includes(@repo.search_clones("A-team"), @clone) end end context "by repo name and description" do setup do @repo = repositories(:johans) @clone = repositories(:johans2) end should "match repos with a matching name" do assert_includes(@repo.search_clones("projectrepos"), @clone) end should "not match repos with a different parent" do assert_not_includes(@repo.search_clones("projectrepos"), repositories(:moes)) end end end context "Sequences" do setup do @repository = repositories(:johans) end should "calculate the highest existing sequence number" do assert_equal(@repository.merge_requests.max_by(&:sequence_number).sequence_number, @repository.calculate_highest_merge_request_sequence_number) end should "calculate the number of merge requests" do assert_equal(3, @repository.merge_request_count) end should "be the number of merge requests for a given repo" do assert_equal 3, @repository.merge_requests.size assert_equal 4, @repository.next_merge_request_sequence_number end # 3 merge requests, update one to have seq 4 should "handle taken sequence numbers gracefully" do last_merge_request = @repository.merge_requests.last last_merge_request.update_attribute(:sequence_number, 4) @repository.expects(:calculate_highest_merge_request_sequence_number).returns(99) assert_equal(100, @repository.next_merge_request_sequence_number) end end context "default favoriting" do should "add the owner as a watcher when creating a clone" do user = users(:mike) repo = Repository.new_by_cloning(repositories(:johans), "mike") repo.user = repo.owner = user assert_difference("user.favorites.reload.count") do repo.save! end assert repo.reload.watched_by?(user) end should "not add as watcher if it is an internal repository" do repo = new_repos(:user => users(:moe)) repo.kind = Repository::KIND_TRACKING_REPO assert_no_difference("users(:moe).favorites.count") do repo.save! end end end context "Calculation of disk usage" do setup do @repository = repositories(:johans) @bytes = 90129 end should "save the bytes used" do @repository.expects(:calculate_disk_usage).returns(@bytes) @repository.update_disk_usage assert_equal @bytes, @repository.disk_usage end end context "Pushing" do setup do @repository = repositories(:johans) end should "update last_pushed_at" do @repository.last_pushed_at = 1.hour.ago.utc @repository.stubs(:update_disk_usage) @repository.register_push assert @repository.last_pushed_at > 1.hour.ago.utc end should "increment the number of pushes" do @repository.push_count_since_gc = 2 @repository.stubs(:update_disk_usage) @repository.register_push assert_equal 3, @repository.push_count_since_gc end should "call update_disk_usage when registering a push" do @repository.expects(:update_disk_usage) @repository.register_push end end end
agpl-3.0
cloudbase/v-magine
v_magine/virt/hyperv/netutils.py
13525
# Copyright 2013 Cloudbase Solutions SRL # Copyright 2013 Pedro Navarro Perez # 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. import logging import time import wmi from v_magine.i18n import _ from v_magine.virt.hyperv import vmutils LOG = logging.getLogger(__name__) WMI_JOB_STATE_STARTED = 4096 WMI_JOB_STATE_RUNNING = 4 WMI_JOB_STATE_COMPLETED = 7 class NetworkUtils(object): _ETHERNET_SWITCH_PORT = 'Msvm_SwitchPort' _wmi_namespace = '//./root/virtualization' _wmi_cimv2_namespace = '//./root/cimv2' def __init__(self): self._wmi_conn = None self._wmi_conn_cimv2 = None @property def _conn(self): # if self._wmi_conn is None: self._wmi_conn = wmi.WMI(moniker=self._wmi_namespace) return self._wmi_conn @property def _conn_cimv2(self): if self._wmi_conn_cimv2 is None: self._wmi_conn_cimv2 = wmi.WMI(moniker=self._wmi_cimv2_namespace) return self._wmi_conn_cimv2 def set_host_nic_ip_address(self, nic_name, dhcp=False, ip_list=None, netmask_list=None, gateway_list=None, gateway_metrics_list=None): net_adapter_list = self._conn_cimv2.Win32_NetworkAdapter( NetConnectionID=nic_name) if not net_adapter_list: raise vmutils.HyperVException(_('Nic not found: %s') % nic_name) net_adapter = net_adapter_list[0] net_adapter_config = net_adapter.associators( wmi_result_class='Win32_NetworkAdapterConfiguration')[0] if dhcp: (ret_val,) = net_adapter_config.EnableDHCP() if ret_val not in [0, 1]: raise vmutils.HyperVException( _('Enabling DHCP failed with error: %s') % ret_val) else: (ret_val,) = net_adapter_config.EnableStatic( IPAddress=ip_list, SubnetMask=netmask_list) if ret_val not in [0, 1]: raise vmutils.HyperVException( _('Setting static IP addresses %(ip_list)s with netmasks ' '%(netmask_list)s on interface %(nic_name)s failed with ' 'error: %(ret_val)s') % {'ip_list': ip_list, 'nic_name': nic_name, 'netmask_list': netmask_list, 'ret_val': ret_val}) if gateway_list: (ret_val,) = net_adapter_config.EnableGateways( DefaultIPGateway=gateway_list, GatewayCostMetric=netmask_list) if ret_val not in [0, 1]: raise vmutils.HyperVException( _('Setting a gateway failed with error: %s') % ret_val) def get_switch_ports(self, vswitch_name): vswitch = self._get_vswitch(vswitch_name) vswitch_ports = vswitch.associators( wmi_result_class=self._ETHERNET_SWITCH_PORT) return set(p.Name for p in vswitch_ports) def vnic_port_exists(self, port_id): try: self._get_vnic_settings(port_id) except Exception: return False return True def get_vnic_ids(self): return set( p.ElementName for p in self._conn.Msvm_SyntheticEthernetPortSettingData() + self._conn.Msvm_EmulatedEthernetPortSettingData() if p.ElementName is not None) def _get_vnic_settings(self, vnic_name): vnic_settings = self._conn.Msvm_SyntheticEthernetPortSettingData( ElementName=vnic_name) vnic_settings += self._conn.Msvm_EmulatedEthernetPortSettingData( ElementName=vnic_name) if not vnic_settings: raise vmutils.HyperVException(_('Vnic not found: %s') % vnic_name) if len(vnic_settings) > 1: raise vmutils.HyperVException(_('Multiple vnics found with name: ' '%s') % vnic_name) return vnic_settings[0] def connect_vnic_to_vswitch(self, vswitch_name, switch_port_name): vnic_settings = self._get_vnic_settings(switch_port_name) if not vnic_settings.Connection or not vnic_settings.Connection[0]: port = self.get_port_by_id(switch_port_name, vswitch_name) if port: port_path = port.Path_() else: port_path = self._create_switch_port( vswitch_name, switch_port_name) vnic_settings.Connection = [port_path] self._modify_virt_resource(vnic_settings) def _get_vm_from_res_setting_data(self, res_setting_data): sd = res_setting_data.associators( wmi_result_class='Msvm_VirtualSystemSettingData') vm = sd[0].associators( wmi_result_class='Msvm_ComputerSystem') return vm[0] def _modify_virt_resource(self, res_setting_data): vm = self._get_vm_from_res_setting_data(res_setting_data) vs_man_svc = self._conn.Msvm_VirtualSystemManagementService()[0] (job_path, ret_val) = vs_man_svc.ModifyVirtualSystemResources( vm.Path_(), [res_setting_data.GetText_(1)]) self._check_job_status(ret_val, job_path) def _check_job_status(self, ret_val, jobpath): """Poll WMI job state for completion.""" if not ret_val: return elif ret_val not in [WMI_JOB_STATE_STARTED, WMI_JOB_STATE_RUNNING]: raise vmutils.HyperVException(_('Job failed with error %d') % ret_val) job_wmi_path = jobpath.replace('\\', '/') job = wmi.WMI(moniker=job_wmi_path) while job.JobState == WMI_JOB_STATE_RUNNING: time.sleep(0.1) job = wmi.WMI(moniker=job_wmi_path) if job.JobState != WMI_JOB_STATE_COMPLETED: job_state = job.JobState if job.path().Class == "Msvm_ConcreteJob": err_sum_desc = job.ErrorSummaryDescription err_desc = job.ErrorDescription err_code = job.ErrorCode data = {'job_state': job_state, 'err_sum_desc': err_sum_desc, 'err_desc': err_desc, 'err_code': err_code} raise vmutils.HyperVException( _("WMI job failed with status %(job_state)d. " "Error details: %(err_sum_desc)s - %(err_desc)s - " "Error code: %(err_code)d") % data) else: (error, ret_val) = job.GetError() if not ret_val and error: data = {'job_state': job_state, 'error': error} raise vmutils.HyperVException( _("WMI job failed with status %(job_state)d. " "Error details: %(error)s") % data) else: raise vmutils.HyperVException( _("WMI job failed with status %d. " "No error description available") % job_state) desc = job.Description elap = job.ElapsedTime LOG.debug(_("WMI job succeeded: %(desc)s, Elapsed=%(elap)s"), {'desc': desc, 'elap': elap}) def _create_switch_port(self, vswitch_name, switch_port_name): """Creates a switch port.""" switch_svc = self._conn.Msvm_VirtualSwitchManagementService()[0] vswitch_path = self._get_vswitch(vswitch_name).path_() (new_port, ret_val) = switch_svc.CreateSwitchPort( Name=switch_port_name, FriendlyName=switch_port_name, ScopeOfResidence="", VirtualSwitch=vswitch_path) if ret_val != 0: raise vmutils.HyperVException( _('Failed creating port for %s') % vswitch_name) return new_port def remove_all_security_rules(self, switch_port_name): pass def disconnect_switch_port( self, vswitch_name, switch_port_name, delete_port): """Disconnects the switch port.""" switch_svc = self._conn.Msvm_VirtualSwitchManagementService()[0] switch_port_path = self._get_switch_port_path_by_name( switch_port_name) if not switch_port_path: # Port not found. It happens when the VM was already deleted. return (ret_val, ) = switch_svc.DisconnectSwitchPort( SwitchPort=switch_port_path) if ret_val != 0: data = {'switch_port_name': switch_port_name, 'vswitch_name': vswitch_name, 'ret_val': ret_val} raise vmutils.HyperVException( _('Failed to disconnect port %(switch_port_name)s ' 'from switch %(vswitch_name)s ' 'with error %(ret_val)s') % data) if delete_port: (ret_val, ) = switch_svc.DeleteSwitchPort( SwitchPort=switch_port_path) if ret_val != 0: data = {'switch_port_name': switch_port_name, 'vswitch_name': vswitch_name, 'ret_val': ret_val} raise vmutils.HyperVException( _('Failed to delete port %(switch_port_name)s ' 'from switch %(vswitch_name)s ' 'with error %(ret_val)s') % data) def get_vswitches(self): raise NotImplementedError() def _get_vswitch(self, vswitch_name): vswitch = self._conn.Msvm_VirtualSwitch(ElementName=vswitch_name) if not vswitch: raise vmutils.HyperVException(_('VSwitch not found: %s') % vswitch_name) return vswitch[0] def vswitch_exists(self, vswitch_name): try: self._get_vswitch(vswitch_name) return True except vmutils.HyperVException: return False def create_vswitch(self, vswitch_name, external_port_name=None, create_internal_port=False): raise NotImplementedError() def remove_vswitch(self, vswitch_name): raise NotImplementedError() def get_external_ports(self): raise NotImplementedError() def _get_vswitch_external_port(self, vswitch): vswitch_ports = vswitch.associators( wmi_result_class=self._ETHERNET_SWITCH_PORT) for vswitch_port in vswitch_ports: lan_endpoints = vswitch_port.associators( wmi_result_class='Msvm_SwitchLanEndpoint') if lan_endpoints: ext_port = lan_endpoints[0].associators( wmi_result_class='Msvm_ExternalEthernetPort') if ext_port: return vswitch_port def set_vnic_port_security(self, switch_port_name, allow_mac_spoofing=False, enable_dhcp_guard=False, enable_router_guard=False, allow_ieee_priority_tag=False, allow_teaming=False, monitor_mode=0): raise NotImplementedError() def set_vswitch_port_vlan_id(self, vlan_id, switch_port_name, trunk_vlan_ids=None, native_vlan_id=0): vlan_endpoint_settings = self._conn.Msvm_VLANEndpointSettingData( ElementName=switch_port_name)[0] if trunk_vlan_ids: raise NotImplementedError() if vlan_endpoint_settings.AccessVLAN != vlan_id: vlan_endpoint_settings.AccessVLAN = vlan_id vlan_endpoint_settings.put() def _get_switch_port_path_by_name(self, switch_port_name): vswitch = self._conn.Msvm_SwitchPort(ElementName=switch_port_name) if vswitch: return vswitch[0].path_() def get_vswitch_id(self, vswitch_name): vswitch = self._get_vswitch(vswitch_name) return vswitch.Name def get_port_by_id(self, port_id, vswitch_name): vswitch = self._get_vswitch(vswitch_name) switch_ports = vswitch.associators( wmi_result_class=self._ETHERNET_SWITCH_PORT) for switch_port in switch_ports: if (switch_port.ElementName == port_id): return switch_port def enable_port_metrics_collection(self, switch_port_name): raise NotImplementedError(_("Metrics collection is not supported on " "this version of Hyper-V")) def enable_control_metrics(self, switch_port_name): raise NotImplementedError(_("Metrics collection is not supported on " "this version of Hyper-V")) def can_enable_control_metrics(self, switch_port_name): return False
agpl-3.0
usmschuck/canvas
vendor/bundle/ruby/1.9.1/gems/aws-sdk-1.8.3.1/lib/aws/s3/bucket_collection.rb
5157
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. module AWS class S3 # Represents a collection of buckets. # # You can use this to create a bucket: # # s3.buckets.create(:name => "mybucket") # # You can get a handle for a specific bucket with indifferent # access: # # bucket = s3.buckets[:mybucket] # bucket = s3.buckets['mybucket'] # # You can also use it to find out which buckets are in your account: # # s3.buckets.collect(&:name) # #=> ['bucket1', 'bucket2', ...] # class BucketCollection include Core::Model include Enumerable # Creates and returns a new Bucket. For example: # # @note If your bucket name contains one or more periods and it # is hosted in a non-US region, you should make requests # against the bucket using the S3 endpoint specific to the # region in which your bucket resides. For example: # # s3 = AWS::S3.new(:s3_endpoint => "s3-eu-west-1.amazonaws.com") # bucket = s3.buckets.create("my.eu.bucket") # # For a full list of endpoints and regions, see # {http://docs.amazonwebservices.com/general/latest/gr/index.html?rande.html # Regions and Endpoints} in the Amazon Web Services General # Reference. # # @example # # bucket = s3.buckets.create('my-bucket') # bucket.name #=> "my-bucket" # bucket.exists? #=> true # # @param [String] bucket_name # # @param [Hash] options # # @option options [String] :location_constraint (nil) The # location where the bucket should be created. Defaults to # the classic US region; however, if you configure a regional # endpoint for Amazon S3 this option will default to the # appropriate location constraint for the endpoint. For # example: # # s3 = AWS::S3.new(:s3_endpoint => "s3-us-west-1.amazonaws.com") # bucket = s3.buckets.create("my-us-west-bucket") # bucket.location_constraint # => "us-west-1" # # @option options [Symbol,String] :acl (:private) Sets the ACL of the # bucket you are creating. Valid Values include: # * +:private+ # * +:public_read+ # * +:public_read_write+ # * +:authenticated_read+ # * +:log_delivery_write+ # # @option options [String] :grant_read # @option options [String] :grant_write # @option options [String] :grant_read_acp # @option options [String] :grant_write_acp # @option options [String] :grant_full_control # # @return [Bucket] # def create bucket_name, options = {} # convert the symbolized-canned acl into the string version if acl = options[:acl] options[:acl] = acl.to_s.tr('_', '-') end # auto set the location constraint for the user if it is not # passed in and the endpoint is not the us-standard region. don't # override the location constraint though, even it is wrong, unless config.s3_endpoint == 's3.amazonaws.com' or options[:location_constraint] then constraint = case config.s3_endpoint when 's3-eu-west-1.amazonaws.com' then 'EU' when /^s3-(.*)\.amazonaws\.com$/ then $1 end options[:location_constraint] = constraint if constraint end client.create_bucket(options.merge(:bucket_name => bucket_name)) bucket_named(bucket_name) end # Returns the Bucket with the given name. # # Makes no requests. The returned bucket object can # be used to make requets for the bucket and its objects. # # @example # # bucket = s3.buckets[:mybucket], # bucket = s3.buckets['mybucket'], # # @param [String] bucket_name # @return [Bucket] def [] bucket_name bucket_named(bucket_name) end # Iterates the buckets in this collection. # # @example # # s3.buckets.each do |bucket| # puts bucket.name # end # # @return [nil] def each &block response = client.list_buckets response.buckets.each do |b| yield(bucket_named(b.name, response.owner)) end nil end # @private private def bucket_named name, owner = nil S3::Bucket.new(name.to_s, :owner => owner, :config => config) end end end end
agpl-3.0
rapidminer/rapidminer-5
src/com/rapidminer/gui/tools/dialogs/DatabaseAdvancedConnectionDialog.java
11993
/* * 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.tools.dialogs; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.sql.DriverPropertyInfo; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import javax.swing.AbstractButton; import javax.swing.DefaultCellEditor; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import com.rapidminer.gui.tools.ExtendedJScrollPane; import com.rapidminer.tools.I18N; /** * In this dialog, the user can edit the advanvced properties of the given JDBC driver. * Note: These are not the jdbc properties! * * @author Marco Boeck */ public class DatabaseAdvancedConnectionDialog extends ButtonDialog { private static final long serialVersionUID = -3287030968059122084L; /** * This {@link TableModel} can work with a {@link DriverPropertyInfo} array. * */ private class DriverPropertyInfoTableModel extends AbstractTableModel { private static final long serialVersionUID = -6521100131706498109L; /** the driver propinfos */ private DriverPropertyInfo[] propInfo; /** a list indicating for each propInfo index if the default value should be overriden or not */ private List<Boolean> override; /** * Creates a new {@link DriverPropertyInfoTableModel}. * @param propInfo all propertyInfos of a JDBC driver (not the jdbc properties) * @param currentProperties the current edited custom properties as of before this dialog */ private DriverPropertyInfoTableModel(DriverPropertyInfo[] propInfo, Properties currentProperties) { this.propInfo = propInfo; this.override = new ArrayList<Boolean>(propInfo.length); for (int i=0; i<this.propInfo.length; i++) { // only set override for the rows to true where the key exists in the currentProperties if (currentProperties.get(propInfo[i].name) != null) { override.add(true); } else { override.add(false); } } } @Override public int getRowCount() { return propInfo.length; } @Override public int getColumnCount() { return 3; } @Override public boolean isCellEditable(int row, int col) { // only values are editable if (col == 1 || col == 2) { return true; } return false; } @Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex == 0) { return String.class; } else if (columnIndex == 1) { return Object.class; } else { return Boolean.class; } } @Override public String getColumnName(int col) { if (col == 0) { return "Key"; } else if (col == 2) { return "Override"; } else { return "Value"; } } /** * Returns the current value of a combo item. * @param row * @return */ public String getComboValue(int row) { return propInfo[row].value; } /** * Returns the tooltip for the given row. * @param row * @return */ public String getTooltip(int row) { return propInfo[row].description; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return propInfo[rowIndex].name; } else if (columnIndex == 2) { return override.get(rowIndex); } else { if (propInfo[rowIndex].choices == null) { return propInfo[rowIndex].value; } else { return propInfo[rowIndex].choices; } } } @Override public void setValueAt(Object value, int row, int col) { // nothing but the value column is editable if (col != 1 && col != 2) { return; } if (col == 1) { // check if choices are available that the value is one of the choices if (propInfo[row].choices != null) { boolean found = false; for (String choice : propInfo[row].choices) { if (choice.equals(value)) { found = true; break; } } if (!found) { return; } } propInfo[row].value = String.valueOf(value); override.set(row, Boolean.TRUE); fireTableCellUpdated(row, 2); } else if (col == 2) { override.set(row, Boolean.parseBoolean(String.valueOf(value))); } } /** * Returns the user edited properties. * @return */ public Properties getProperties() { Properties props = new Properties(); for (int i=0; i<getRowCount(); i++) { // empty values mean field not set, don't add to properties // and only add if manual override has been checked if (propInfo[i].value != null && !"".equals(propInfo[i].value) && override.get(i)) { props.put(propInfo[i].name, propInfo[i].value); } } return props; } } /** * This {@link TableCellRenderer} can render the arrays from a {@link DriverPropertyInfo} array. * */ private class DriverPropertyInfoTableDefaultCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = -3376218040898856384L; /** the combo box for array values */ JComboBox box; /** * Creates a new {@link DriverPropertyInfoTableDefaultCellRenderer}. */ private DriverPropertyInfoTableDefaultCellRenderer() { box = new JComboBox(); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value instanceof String[]) { box.setModel(new DefaultComboBoxModel((String[])value)); box.setSelectedItem(((DriverPropertyInfoTableModel)table.getModel()).getComboValue(table.convertRowIndexToModel(row))); return box; } else { Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); // add tooltips for key column if (component instanceof DefaultTableCellRenderer && table.convertColumnIndexToModel(column) == 0) { String tooltip = ((DriverPropertyInfoTableModel)table.getModel()).getTooltip(table.convertRowIndexToModel(row)); tooltip = "<html><div width = 300px>" + tooltip + "</div></html>"; ((DefaultTableCellRenderer)component).setToolTipText(tooltip); } return component; } } } /** the JTable displaying the properties */ private JTable table; private int returnValue = ConfirmDialog.CANCEL_OPTION; /** * Creates a new advanced connection properties dialog. * @param i18nKey * @param propertyInfos the propertyInfo[] array as returned by the driver * @param currentProperties the currently set properties * @param i18nArgs */ public DatabaseAdvancedConnectionDialog(String i18nKey, DriverPropertyInfo[] propertyInfos, Properties currentProperties, Object ... i18nArgs) { super(i18nKey, true, i18nArgs); setupGUI(propertyInfos, currentProperties); } private void setupGUI(final DriverPropertyInfo[] propInfo, final Properties currentProperties) { table = new JTable(new DriverPropertyInfoTableModel(propInfo, currentProperties)) { private static final long serialVersionUID = 1L; /** a map containing the JComboBoxes for each row where one is needed */ private Map<Integer, JComboBox> mapOfBoxes = new HashMap<Integer, JComboBox>(propInfo.length);; @Override public TableCellEditor getCellEditor(int row, int col) { if (getModel().getValueAt(convertRowIndexToModel(row), convertColumnIndexToModel(col)) instanceof String[]) { // this needs a JComboBox as editor JComboBox box = mapOfBoxes.get(convertRowIndexToModel(row)); if (box == null) { mapOfBoxes.put(convertRowIndexToModel(row), new JComboBox((String[])getModel().getValueAt(convertRowIndexToModel(row), convertColumnIndexToModel(col)))); box = mapOfBoxes.get(convertRowIndexToModel(row)); } box.setSelectedItem(((DriverPropertyInfoTableModel)table.getModel()).getComboValue(table.convertRowIndexToModel(row))); return new DefaultCellEditor(box); } else if (getModel().getValueAt(convertRowIndexToModel(row), convertColumnIndexToModel(col)) instanceof Boolean) { // override checkbox return getDefaultEditor(Boolean.class); } else { // normal string text editor return getDefaultEditor(String.class); } } @Override protected JTableHeader createDefaultTableHeader() { return new JTableHeader(columnModel) { private static final long serialVersionUID = 1L; public String getToolTipText(MouseEvent e) { // add table header tooltips Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); switch (realIndex) { case 0: return I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.db_connection_advanced.table.key.tooltip"); case 1: return I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.db_connection_advanced.table.value.tooltip"); case 2: return I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.db_connection_advanced.table.override.tooltip"); default: return null; } } }; } }; table.setAutoCreateRowSorter(true); table.setRowHeight(table.getRowHeight() + 4); table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN); table.getColumnModel().getColumn(0).setPreferredWidth(200); table.getColumnModel().getColumn(1).setPreferredWidth(200); table.getColumnModel().getColumn(2).setPreferredWidth(10); table.setDefaultRenderer(Object.class, new DriverPropertyInfoTableDefaultCellRenderer()); table.getTableHeader().setReorderingAllowed(false); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); ExtendedJScrollPane scrollPane = new ExtendedJScrollPane(table); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1; gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; panel.add(scrollPane, gbc); Collection<AbstractButton> list = new LinkedList<AbstractButton>(); JButton okButton = makeOkButton(); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { returnValue = ConfirmDialog.OK_OPTION; } }); list.add(okButton); list.add(makeCancelButton()); layoutDefault(panel, NORMAL, list); } /** * Returns the user edited connection properties or {@code null} if the user pressed cancel. * @return */ public Properties getConnectionProperties() { if (returnValue == ConfirmDialog.OK_OPTION) { return ((DriverPropertyInfoTableModel)table.getModel()).getProperties(); } else { return null; } } }
agpl-3.0
uclouvain/osis
education_group/tests/views/mini_training/test_content_read.py
5481
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so on. # # Copyright (C) 2015-2020 Université catholique de Louvain (http://www.uclouvain.be) # # 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. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################## from typing import List from django.http import HttpResponseForbidden, HttpResponse, HttpResponseNotFound from django.test import TestCase from django.urls import reverse from base.models.enums.education_group_types import MiniTrainingType from base.tests.factories.academic_year import AcademicYearFactory from base.tests.factories.person import PersonWithPermissionsFactory from base.tests.factories.user import UserFactory from base.utils.urls import reverse_with_get from education_group.ddd.domain.group import Group from education_group.views.mini_training.common_read import Tab from program_management.tests.factories.education_group_version import EducationGroupVersionFactory from program_management.tests.factories.element import ElementGroupYearFactory class TestMiniTrainingReadContent(TestCase): @classmethod def setUpTestData(cls): cls.academic_year = AcademicYearFactory(current=True) cls.person = PersonWithPermissionsFactory('view_educationgroup') cls.mini_training_version = EducationGroupVersionFactory( offer__acronym="APPBIOL", offer__academic_year=cls.academic_year, offer__education_group_type__name=MiniTrainingType.DEEPENING.name, root_group__partial_acronym="LBIOL100P", root_group__acronym="APPBIOL", root_group__academic_year=cls.academic_year, root_group__education_group_type__name=MiniTrainingType.DEEPENING.name, ) ElementGroupYearFactory(group_year=cls.mini_training_version.root_group) cls.url = reverse('mini_training_content', kwargs={'year': cls.academic_year.year, 'code': 'LBIOL100P'}) def setUp(self) -> None: self.client.force_login(self.person.user) def test_case_user_not_logged(self): self.client.logout() response = self.client.get(self.url) self.assertRedirects(response, '/login/?next={}'.format(self.url)) def test_case_user_have_not_permission(self): self.client.force_login(UserFactory()) response = self.client.get(self.url) self.assertEqual(response.status_code, HttpResponseForbidden.status_code) self.assertTemplateUsed(response, "access_denied.html") def test_case_mini_training_not_exists(self): dummy_url = reverse('mini_training_content', kwargs={'year': 2018, 'code': 'DUMMY100B'}) response = self.client.get(dummy_url) self.assertEqual(response.status_code, HttpResponseNotFound.status_code) def test_assert_template_used(self): response = self.client.get(self.url) self.assertEqual(response.status_code, HttpResponse.status_code) self.assertTemplateUsed(response, "education_group_app/mini_training/content_read.html") def test_assert_context_data(self): response = self.client.get(self.url) self.assertEqual(response.context['person'], self.person) self.assertEqual(response.context['group_year'], self.mini_training_version.root_group) self.assertEqual(response.context['update_permission_name'], "base.change_link_data") expected_tree_json_url = reverse_with_get( 'tree_json', kwargs={'root_id': self.mini_training_version.root_group.element.pk}, get={"path": str(self.mini_training_version.root_group.element.pk)} ) self.assertEqual(response.context['tree_json_url'], expected_tree_json_url) self.assertIsInstance(response.context['group'], Group) self.assertIsInstance(response.context['children'], List) def test_assert_active_tabs_is_content_and_others_are_not_active(self): response = self.client.get(self.url) self.assertTrue(response.context['tab_urls'][Tab.CONTENT]['active']) self.assertFalse(response.context['tab_urls'][Tab.IDENTIFICATION]['active']) self.assertFalse(response.context['tab_urls'][Tab.UTILIZATION]['active']) self.assertFalse(response.context['tab_urls'][Tab.GENERAL_INFO]['active']) self.assertFalse(response.context['tab_urls'][Tab.SKILLS_ACHIEVEMENTS]['active']) self.assertFalse(response.context['tab_urls'][Tab.ACCESS_REQUIREMENTS]['active'])
agpl-3.0
rkorzeniewski/bacula
gui/baculum/framework/Caching/TMemCache.php
12388
<?php /** * TMemCache class file * * @author Qiang Xue <qiang.xue@gmail.com> * @author Carl G. Mathisen <carlgmathisen@gmail.com> * @link http://www.pradosoft.com/ * @copyright Copyright &copy; 2005-2013 PradoSoft * @license http://www.pradosoft.com/license/ * @version $Id: TMemCache.php 3245 2013-01-07 20:23:32Z ctrlaltca $ * @package System.Caching */ /** * TMemCache class * * TMemCache implements a cache application module based on {@link http://www.danga.com/memcached/ memcached}. * * TMemCache can be configured with the Host and Port properties, which * specify the host and port of the memcache server to be used. * By default, they take the value 'localhost' and 11211, respectively. * These properties must be set before {@link init} is invoked. * * The following basic cache operations are implemented: * - {@link get} : retrieve the value with a key (if any) from cache * - {@link set} : store the value with a key into cache * - {@link add} : store the value only if cache does not have this key * - {@link delete} : delete the value with the specified key from cache * - {@link flush} : delete all values from cache * * Each value is associated with an expiration time. The {@link get} operation * ensures that any expired value will not be returned. The expiration time can * be specified by the number of seconds (maximum 60*60*24*30) * or a UNIX timestamp. A expiration time 0 represents never expire. * * By definition, cache does not ensure the existence of a value * even if it never expires. Cache is not meant to be an persistent storage. * * Also note, there is no security measure to protected data in memcache. * All data in memcache can be accessed by any process running in the system. * * To use this module, the memcache PHP extension must be loaded. * * Some usage examples of TMemCache are as follows, * <code> * $cache=new TMemCache; // TMemCache may also be loaded as a Prado application module * $cache->init(null); * $cache->add('object',$object); * $object2=$cache->get('object'); * </code> * * You can configure TMemCache two different ways. If you only need one memcache server * you may use the method as follows. * <code> * <module id="cache" class="System.Caching.TMemCache" Host="localhost" Port="11211" /> * </code> * * If you want a more complex configuration, you may use the method as follows. * <code> * <module id="cache" classs="System.Caching.TMemCache"> * <server Host="localhost" Port="11211" Weight="1" Timeout="300" RetryInterval="15" /> * <server Host="anotherhost" Port="11211" Weight="1" Timeout="300" RetryInterval="15" /> * </module> * </code> * * If loaded, TMemCache will register itself with {@link TApplication} as the * cache module. It can be accessed via {@link TApplication::getCache()}. * * TMemCache may be configured in application configuration file as follows * <code> * <module id="cache" class="System.Caching.TMemCache" Host="localhost" Port="11211" /> * </code> * where {@link getHost Host} and {@link getPort Port} are configurable properties * of TMemCache. * * Automatic compression of values may be used (using zlib extension) by setting {@link getThreshold Threshold} and {@link getMinSavings MinSavings} properties. * NB : MemCache server(s) must be restarted to apply settings. Require (PECL memcache >= 2.0.0). * * @author Qiang Xue <qiang.xue@gmail.com> * @version $Id: TMemCache.php 3245 2013-01-07 20:23:32Z ctrlaltca $ * @package System.Caching * @since 3.0 */ class TMemCache extends TCache { /** * @var boolean if the module is initialized */ private $_initialized=false; /** * @var Memcache the Memcache instance */ private $_cache=null; /** * @var string a unique prefix used to identify this cache instance from the others */ private $_prefix=null; /** * @var string host name of the memcache server */ private $_host='localhost'; /** * @var integer the port number of the memcache server */ private $_port=11211; /** * @var boolean controls the use of a persistent connection. Default to true. */ private $_persistence = true; /** * @var integer number of buckets to create for this server which in turn control its * probability of it being selected. The probability is relative to the total weight * of all servers. */ private $_weight = 1; private $_timeout = 360; private $_retryInterval = 15; /** * @var integer Controls the minimum value length before attempting to compress automatically. */ private $_threshold=0; /** * @var float Specifies the minimum amount of savings to actually store the value compressed. The supplied value must be between 0 and 1. Default value is 0.2 giving a minimum 20% compression savings. */ private $_minSavings=0.0; private $_status = true; private $_failureCallback = null; /** * @var array list of servers available */ private $_servers=array(); /** * Destructor. * Disconnect the memcache server. */ public function __destruct() { if($this->_cache!==null) $this->_cache->close(); } /** * Initializes this module. * This method is required by the IModule interface. It makes sure that * UniquePrefix has been set, creates a Memcache instance and connects * to the memcache server. * @param TApplication Prado application, can be null * @param TXmlElement configuration for this module, can be null * @throws TConfigurationException if memcache extension is not installed or memcache sever connection fails */ public function init($config) { if(!extension_loaded('memcache')) throw new TConfigurationException('memcache_extension_required'); $this->_cache=new Memcache; $this->loadConfig($config); if(count($this->_servers)) { foreach($this->_servers as $server) { Prado::trace('Adding server '.$server['Host'].' from serverlist', 'System.Caching.TMemCache'); if($this->_cache->addServer($server['Host'],$server['Port'],$server['Persistent'], $server['Weight'],$server['Timeout'],$server['RetryInterval'])===false) throw new TConfigurationException('memcache_connection_failed',$server['Host'],$server['Port']); } } else { Prado::trace('Adding server '.$this->_host, 'System.Caching.TMemCache'); if($this->_cache->addServer($this->_host,$this->_port)===false) throw new TConfigurationException('memcache_connection_failed',$this->_host,$this->_port); } if($this->_threshold!==0) $this->_cache->setCompressThreshold($this->_threshold,$this->_minSavings); $this->_initialized=true; parent::init($config); } /** * Loads configuration from an XML element * @param TXmlElement configuration node * @throws TConfigurationException if log route class or type is not specified */ private function loadConfig($xml) { if($xml instanceof TXmlElement) { foreach($xml->getElementsByTagName('server') as $serverConfig) { $properties=$serverConfig->getAttributes(); if(($host=$properties->remove('Host'))===null) throw new TConfigurationException('memcache_serverhost_required'); if(($port=$properties->remove('Port'))===null) throw new TConfigurationException('memcache_serverport_required'); if(!is_numeric($port)) throw new TConfigurationException('memcache_serverport_invalid'); $server = array('Host'=>$host,'Port'=>$port,'Weight'=>1,'Timeout'=>1800,'RetryInterval'=>15,'Persistent'=>true); $checks = array( 'Weight'=>'memcache_serverweight_invalid', 'Timeout'=>'memcache_servertimeout_invalid', 'RetryInterval'=>'memcach_serverretryinterval_invalid' ); foreach($checks as $property=>$exception) { $value=$properties->remove($property); if($value!==null && is_numeric($value)) $server[$property]=$value; else if($value!==null) throw new TConfigurationException($exception); } $server['Persistent']= TPropertyValue::ensureBoolean($properties->remove('Persistent')); $this->_servers[]=$server; } } } /** * @return string host name of the memcache server */ public function getHost() { return $this->_host; } /** * @param string host name of the memcache server * @throws TInvalidOperationException if the module is already initialized */ public function setHost($value) { if($this->_initialized) throw new TInvalidOperationException('memcache_host_unchangeable'); else $this->_host=$value; } /** * @return integer port number of the memcache server */ public function getPort() { return $this->_port; } /** * @param integer port number of the memcache server * @throws TInvalidOperationException if the module is already initialized */ public function setPort($value) { if($this->_initialized) throw new TInvalidOperationException('memcache_port_unchangeable'); else $this->_port=TPropertyValue::ensureInteger($value); } /** * @return integer minimum value length before attempting to compress */ public function getThreshold() { return $this->_threshold; } /** * @param integer minimum value length before attempting to compress * @throws TInvalidOperationException if the module is already initialized */ public function setThreshold($value) { if($this->_initialized) throw new TInvalidOperationException('memcache_threshold_unchangeable'); else $this->_threshold=TPropertyValue::ensureInteger($value); } /** * @return float minimum amount of savings to actually store the value compressed */ public function getMinSavings() { return $this->_minSavings; } /** * @param float minimum amount of savings to actually store the value compressed * @throws TInvalidOperationException if the module is already initialized */ public function setMinSavings($value) { if($this->_initialized) throw new TInvalidOperationException('memcache_min_savings_unchangeable'); else $this->_minSavings=TPropertyValue::ensureFloat($value); } /** * Retrieves a value from cache with a specified key. * This is the implementation of the method declared in the parent class. * @param string a unique key identifying the cached value * @return string the value stored in cache, false if the value is not in the cache or expired. */ protected function getValue($key) { return $this->_cache->get($key); } /** * Stores a value identified by a key in cache. * This is the implementation of the method declared in the parent class. * * @param string the key identifying the value to be cached * @param string the value to be cached * @param integer the number of seconds in which the cached value will expire. 0 means never expire. * @return boolean true if the value is successfully stored into cache, false otherwise */ protected function setValue($key,$value,$expire) { return $this->_cache->set($key,$value,0,$expire); } /** * Stores a value identified by a key into cache if the cache does not contain this key. * This is the implementation of the method declared in the parent class. * * @param string the key identifying the value to be cached * @param string the value to be cached * @param integer the number of seconds in which the cached value will expire. 0 means never expire. * @return boolean true if the value is successfully stored into cache, false otherwise */ protected function addValue($key,$value,$expire) { return $this->_cache->add($key,$value,0,$expire); } /** * Deletes a value with the specified key from cache * This is the implementation of the method declared in the parent class. * @param string the key of the value to be deleted * @return boolean if no error happens during deletion */ protected function deleteValue($key) { return $this->_cache->delete($key); } /** * Deletes all values from cache. * Be careful of performing this operation if the cache is shared by multiple applications. */ public function flush() { return $this->_cache->flush(); } }
agpl-3.0
yourcelf/btb
scanblog/subscriptions/models.py
7142
import datetime from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from scanning.models import Document from annotations.models import Tag from comments.models import Comment from profiles.models import Organization, Affiliation from campaigns.models import Campaign from notification import models as notification # Create your models here. class Subscription(models.Model): subscriber = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="subscriptions") document = models.ForeignKey(Document, related_name="subscriptions", blank=True, null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="author_subscriptions", blank=True, null=True) tag = models.ForeignKey(Tag, related_name="tag_subscriptions", blank=True, null=True) organization = models.ForeignKey(Organization, related_name="organization_subscriptions", blank=True, null=True) campaign = models.ForeignKey(Campaign, related_name="organization_subscriptions", blank=True, null=True) affiliation = models.ForeignKey(Affiliation, related_name="affiliation_subscriptions", blank=True, null=True) def __unicode__(self): return "%s -> %s" % (self.subscriber, (self.document or self.author or self.tag or self.campaign or self.affiliation)) class Meta: ordering = ['tag', 'author', 'document', 'campaign', 'affiliation'] class DocumentNotificationLog(models.Model): """ Log notifications of documents, so that we only send once per document, even if the user is multiply subscribed (e.g. to featured posts as well as posts by an author). """ recipient = models.ForeignKey(settings.AUTH_USER_MODEL) document = models.ForeignKey(Document) def __unicode__(self): return "%s -> %s" % (self.document, self.recipient) class CommentNotificationLog(models.Model): """ Log notifications of comments, so that we only send once per comment, even if the comment is edited. """ recipient = models.ForeignKey(settings.AUTH_USER_MODEL) comment = models.ForeignKey(Comment) def __unicode__(self): return "%s -> %s" % (self.comment, self.recipient) class NotificationBlacklist(models.Model): """ Any email in this list will never be sent a notification. For abuse prevention. """ email = models.EmailField() def __unicode__(self): return self.email class UserNotificationLog(models.Model): """ Log of each notification sent to a user, used for throttling of notifications. """ recipient = models.ForeignKey(settings.AUTH_USER_MODEL) date = models.DateTimeField(auto_now_add=True) def __unicode__(self): return "%s -> %s" % (self.recipient, self.date) class Meta: ordering = ['-date'] class MailingListInterest(models.Model): email = models.EmailField(max_length=254) volunteering = models.BooleanField( default=False, help_text="Are you interested in volunteering?") allies = models.BooleanField( default=False, help_text="Are you interested in joining with Between the Bars in campaigns?") announcements = models.BooleanField( default=False, help_text="Are you interested in announcements about new projects and features?") details = models.TextField(blank=True, help_text="Tell us more about your interests, if you like.") def __unicode__(self): return self.email def send_notices(recipients, *args): """ Send notices, but throttled by the UserNotificationLog. """ cutoff = datetime.datetime.now() - datetime.timedelta(seconds=30*60) new_recipients = [] for recipient in recipients: if UserNotificationLog.objects.filter( date__gte=cutoff, recipient=recipient).exists(): continue else: UserNotificationLog.objects.create(recipient=recipient) new_recipients.append(recipient) notification.send(new_recipients, *args) # # Signals # if not settings.DISABLE_NOTIFICATIONS: @receiver(post_save, sender=Document) def send_document_notifications(sender, instance=None, **kwargs): if instance is None: return document = instance if document.author is None: return if not document.is_public(): return subs = Subscription.objects.filter(author=document.author) for org in document.author.organization_set.all(): subs |= Subscription.objects.filter(organization=org) for tag in document.tags.all(): subs |= Subscription.objects.filter(tag=tag) recipients = [] if document.in_reply_to_id: campaign = None try: campaign = document.in_reply_to.campaign except Campaign.DoesNotExist: pass if campaign: subs |= Subscription.objects.filter(campaign=campaign) if document.affiliation: subs |= Subscription.objects.filter(affiliation=document.affiliation) for sub in subs: if NotificationBlacklist.objects.filter( email=sub.subscriber.email).exists(): continue if document.adult and not sub.subscriber.profile.show_adult_content: continue log, created = DocumentNotificationLog.objects.get_or_create( recipient=sub.subscriber, document=document ) if created: recipients.append(sub.subscriber) if recipients: send_notices(recipients, "new_post", {'document': document}) @receiver(post_save, sender=Comment) def send_comment_notifications(sender, instance=None, **kwargs): # Only fire on creation. if instance is None or 'created' not in kwargs: return comment = instance if comment.document is None: return # Create default subscription for commenter. sub, created = Subscription.objects.get_or_create( subscriber=comment.user, document=comment.document ) # Send notices to all subscribed parties. subs = Subscription.objects.filter(document=comment.document) recipients = [] for sub in subs: if NotificationBlacklist.objects.filter( email=sub.subscriber.email).exists(): continue # No notification if the subscriber is the comment author. :) if sub.subscriber == comment.user: continue log, created = CommentNotificationLog.objects.get_or_create( recipient=sub.subscriber, comment=comment ) if created: recipients.append(sub.subscriber) if recipients: send_notices(recipients, "new_reply", {'comment': comment})
agpl-3.0
sciCloud/OLiMS
lims/exportimport/instruments/thermoscientific/arena/__init__.py
3792
""" Thermo Scientific 'Arena' """ from datetime import datetime from lims import logger from lims.exportimport.instruments.resultsimport import \ AnalysisResultsImporter, InstrumentCSVResultsFileParser class ThermoArenaRPRCSVParser(InstrumentCSVResultsFileParser): def __init__(self, csv): InstrumentCSVResultsFileParser.__init__(self, csv) self._end_header = False self._columns = [] self._period = [False,''] # Variable to control results from period beginning and end. def _parseline(self, line): # Process the line differently if it pertains at header or results block if not self._end_header: return self.parse_headerline(line) else: return self.parse_resultline(line) def parse_headerline(self, line): if line.startswith('Arena'): self._header['ARId'] = line.strip(',') return 0 elif line.startswith('Results from time'): self._period = [True, line.strip(',')] return 0 elif line.startswith('Sample Id'): if self._period[0]: # If there is a period, we should save it self._period[0] = False self._header[self._period[1]] = self._period[2:] self._end_header = True self._columns = line.split(',') elif self._period[0]: # Is a date date = self.csvDate2BikaDate(line.strip(',')) self._period.append(date) return 0 else: self.err('Unexpected header format', numline=self._numline) return -1 def parse_resultline(self, line): sline = line.split(',') if not sline: return 0 rawdict = {} for idx, result in enumerate(sline): if len(self._columns) <= idx: self.err("Orphan value in column ${index}", mapping={"index":str(idx + 1)}, numline=self._numline) break rawdict[self._columns[idx]] = result acode = rawdict.get('Test short name', '') if not acode: self.err("No Analysis Code defined", numline=self._numline) return 0 rid = rawdict.get('Sample Id', '') del(rawdict['Sample Id']) if not rid: self.err("No Sample ID defined", numline=self._numline) return 0 errors = rawdict.get('Errors', '') errors = "Errors: %s" % errors if errors else '' notes = rawdict.get('Notes', '') notes = "Notes: %s" % notes if notes else '' rawdict['DefaultResult'] = 'Result' rawdict['Remarks'] = ' '.join([errors, notes]) raw = {} raw[acode] = rawdict self._addRawResult(rid, raw, False) return 0 def csvDate2BikaDate(self,DateTime): #11/03/2014 14:46:46 --> %d/%m/%Y %H:%M %p try: dtobj = datetime.strptime(DateTime, "%a %b %d %H:%M:%S %Y") return dtobj.strftime("%Y%m%d %H:%M:%S") except ValueError: warn = "No date format known." logger.warning(warn) return DateTime class ThermoArenaImporter(AnalysisResultsImporter): def __init__(self, parser, context, idsearchcriteria, override, allowed_ar_states=None, allowed_analysis_states=None, instrument_uid=None): AnalysisResultsImporter.__init__(self, parser, context, idsearchcriteria, override, allowed_ar_states, allowed_analysis_states, instrument_uid)
agpl-3.0
retk/slamby-api
src/Slamby.API/Middlewares/ElmSecurityMiddleware.cs
2667
using System; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Slamby.Common.Config; using Microsoft.AspNetCore.Server.Kestrel.Internal.Http; namespace Slamby.API.Middlewares { public class ElmSecurityMiddleware { readonly RequestDelegate next; readonly SiteConfig siteConfig; const string SessionKey = "elm-authenticated-user"; public ElmSecurityMiddleware(RequestDelegate next, SiteConfig siteConfig) { this.siteConfig = siteConfig; this.next = next; } public async Task Invoke(HttpContext context) { var isElmUrl = context.Request.Path.StartsWithSegments("/elm"); var isSessionAuthenticated = !string.IsNullOrWhiteSpace(context.Session.GetString(SessionKey)); if (!isElmUrl || isSessionAuthenticated) { await next.Invoke(context); return; } var basicAuth = new BasicAuthenticationParser(context); if (string.Equals(basicAuth.Username, "slamby", StringComparison.Ordinal) && string.Equals(basicAuth.Password, siteConfig.Elm.Key, StringComparison.Ordinal)) { context.Session.SetString(SessionKey, basicAuth.Username); await next.Invoke(context); return; } context.Response.StatusCode = 401; context.Response.Headers.Add("WWW-Authenticate", new[] { "Basic" }); } } internal class BasicAuthenticationParser { public string Username { get; } public string Password { get; } public BasicAuthenticationParser(HttpContext context) { var parts = GetCredentials(context).Split(':'); if (parts.Length == 2) { Username = parts[0]; Password = parts[1]; } } private string GetCredentials(HttpContext context) { try { var authorizationHeader = ((FrameRequestHeaders)context.Request.Headers).HeaderAuthorization; if (authorizationHeader.Any(headerValue => headerValue.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))) { var value = Convert.FromBase64String(authorizationHeader[0].Split(' ')[1]); return Encoding.UTF8.GetString(value); } return string.Empty; } catch { return string.Empty; } } } }
agpl-3.0
ecamp/ecamp3
backend/module/eCampApi/src/eCampApi/V1/RpcConfig.php
4043
<?php namespace eCampApi\V1; use eCamp\Lib\Entity\EntityLink; use eCamp\Lib\Entity\EntityLinkCollection; use Laminas\Di\Container\ServiceManager\AutowireFactory; use Laminas\Stdlib\ArrayUtils; class RpcConfig { private string $routeName; private string $controller; private string $route; private array $parameterDefaults = []; private array $allowedHttpMethods; private array $collectionQueryWhiteList = []; private function __construct($routeName) { $this->routeName = $routeName; } public static function forRoute($routeName): RpcConfig { return new RpcConfig($routeName); } public static function merge(...$configs): array { $result = []; foreach ($configs as $config) { $result = ArrayUtils::merge($result, $config); } return $result; } public function setController(string $controller): RpcConfig { $this->controller = $controller; return $this; } public function setRoute(string $route): RpcConfig { $this->route = $route; return $this; } public function addParameterDefault(string $parameter, string $default): RpcConfig { $this->parameterDefaults[$parameter] = $default; return $this; } public function setAllowedHttpMethods(string ...$allowedHttpMethods): RpcConfig { $this->allowedHttpMethods = $allowedHttpMethods; return $this; } public function setCollectionQueryWhiteList(string ...$collectionQueryWhiteList): RpcConfig { $this->collectionQueryWhiteList = $collectionQueryWhiteList; return $this; } public function build() { $config = [ 'router' => [ 'routes' => [ $this->routeName => [ 'type' => 'Segment', 'options' => [ 'route' => $this->route, 'defaults' => array_merge(['controller' => $this->controller], $this->parameterDefaults), ], ], ], ], 'controllers' => [ 'factories' => [ $this->controller => AutowireFactory::class, ], ], 'api-tools-content-negotiation' => [ 'controllers' => [ $this->controller => 'HalJson', ], 'accept_whitelist' => [ $this->controller => [ '0' => 'application/vnd.e-camp-api.v1+json', '1' => 'application/json', '2' => 'application/*+json', ], ], 'content_type_whitelist' => [ $this->controller => [ '0' => 'application/vnd.e-camp-api.v1+json', '1' => 'application/json', ], ], ], 'api-tools-hal' => [ 'metadata_map' => [ EntityLink::class => [ 'route_identifier_name' => 'id', 'entity_identifier_name' => 'id', 'route_name' => '', ], EntityLinkCollection::class => [ 'entity_identifier_name' => 'id', 'route_name' => '', 'is_collection' => true, ], ], ], 'api-tools-rpc' => [ $this->controller => [ 'http_methods' => $this->allowedHttpMethods, 'route_name' => $this->routeName, ], ], ]; if (sizeof($this->collectionQueryWhiteList) > 0) { $config['api-tools-rpc'][$this->controller]['collection_query_whitelist'] = $this->collectionQueryWhiteList; } return $config; } }
agpl-3.0
luxigo/freepano
js/thirdparty/howler.js/howler.effects.js
21792
/*! * Effects Plugin - Adds advanced Web Audio API functionality. * * howler.js v2.0.0-beta * howlerjs.com * * (c) 2013-2014, James Simpson of GoldFire Studios * goldfirestudios.com * * MIT License */ (function() { 'use strict'; // Setup default effects properties. HowlerGlobal.prototype._pos = [0, 0, 0]; HowlerGlobal.prototype._orientation = [0, 0, -1, 0, 1, 0]; HowlerGlobal.prototype._velocity = [0, 0, 0]; HowlerGlobal.prototype._listenerAttr = { dopplerFactor: 1, speedOfSound: 343.3 }; /** Global Methods **/ /***************************************************************************/ /** * Get/set the position of the listener in 3D cartesian space. Sounds using * 3D position will be relative to the listener's position. * @param {Number} x The x-position of the listener. * @param {Number} y The y-position of the listener. * @param {Number} z The z-position of the listener. * @return {Howler/Array} Self or current listener position. */ HowlerGlobal.prototype.pos = function(x, y, z) { var self = this; // Stop right here if not using Web Audio. if (!self.ctx || !self.ctx.listener) { return self; } // Set the defaults for optional 'y' & 'z'. y = (typeof y !== 'number') ? self._pos[1] : y; z = (typeof z !== 'number') ? self._pos[2] : z; if (typeof x === 'number') { self._pos = [x, y, z]; self.ctx.listener.setPosition(self._pos[0], self._pos[1], self._Pos[2]); } else { return self._pos; } return self; }; /** * Get/set the direction the listener is pointing in the 3D cartesian space. * A front and up vector must be provided. The front is the direction the * face of the listener is pointing, and up is the direction the top of the * listener is pointing. Thus, these values are expected to be at right angles * from each other. * @param {Number} x The x-orientation of the listener. * @param {Number} y The y-orientation of the listener. * @param {Number} z The z-orientation of the listener. * @param {Number} xUp The x-orientation of the top of the listener. * @param {Number} yUp The y-orientation of the top of the listener. * @param {Number} zUp The z-orientation of the top of the listener. * @return {Howler/Array} Returns self or the current orientation vectors. */ HowlerGlobal.prototype.orientation = function(x, y, z, xUp, yUp, zUp) { var self = this; // Stop right here if not using Web Audio. if (!self.ctx || !self.ctx.listener) { return self; } // Set the defaults for optional 'y' & 'z'. var or = self._orientation; y = (typeof y !== 'number') ? or[1] : y; z = (typeof z !== 'number') ? or[2] : z; xUp = (typeof xUp !== 'number') ? or[3] : xUp; yUp = (typeof yUp !== 'number') ? or[4] : yUp; zUp = (typeof zUp !== 'number') ? or[5] : zUp; if (typeof x === 'number') { self._orientation = [x, y, z, xUp, yUp, zUp]; self.ctx.listener.setOrientation(x, y, z, xUp, yUp, zUp); } else { return or; } return self; }; /** * Get/set the velocity vector of the listener. This controls both direction and speed * in 3D space, and is combined relative to a sound's velocity to determine how much * doppler shift (pitch change) to apply. * @param {Number} x The x-velocity of the listener. * @param {Number} y The y-velocity of the listener. * @param {Number} z The z-velocity of the listener. * @return {Howler/Array} Self or current listener velocity. */ HowlerGlobal.prototype.velocity = function(x, y, z) { var self = this; // Stop right here if not using Web Audio. if (!self.ctx || !self.ctx.listener) { return self; } // Set the defaults for optional 'y' & 'z'. y = (typeof y !== 'number') ? self._velocity[1] : y; z = (typeof z !== 'number') ? self._velocity[2] : z; if (typeof x === 'number') { self._velocity = [x, y, z]; self.ctx.listener.setVelocity(self._velocity[0], self._velocity[1], self._velocity[2]); } else { return self._velocity; } return self; }; /** * Get/set the audio listener attributes. * Attributes: * dopplerFactor - (`1` by default) Determines the amount of pitch shift from doppler effect. * speedOfSound - (`343.3` by default) Speed of sound used to calculate doppler shift. * @param {Object} o The attributes to set. * @return {Howl/Object} Returns self or current listener attributes. */ HowlerGlobal.prototype.listenerAttr = function(o) { var self = this; // Stop right here if not using Web Audio. if (!self.ctx || !self.ctx.listener) { return self; } var la = self._listenerAttr; if (o) { // Update the listener attribute values. self._listenerAttr = { dopplerFactor: typeof o.dopplerFactor !== 'undefined' ? o.dopplerFactor : la.dopplerFactor, speedOfSound: typeof o.speedOfSound !== 'undefined' ? o.speedOfSound : la.speedOfSound }; // Apply the new values. self.ctx.listener.dopplerFactor = la.dopplerFactor; self.ctx.listener.speedOfSound = la.speedOfSound; } else { return la; } return self; }; /** Group Methods **/ /***************************************************************************/ /** * Add new properties to the core init. * @param {Function} _super Core init method. * @return {Howl} */ Howl.prototype.init = (function(_super) { return function(o) { var self = this; // Setup user-defined default properties. self._orientation = o.orientation || [1, 0, 0]; self._pos = o.pos || null; self._velocity = o.velocity || [0, 0, 0]; self._pannerAttr = { coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : 360, coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : 360, coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : 0, distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : 'inverse', maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : 10000, panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : 'HRTF', refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : 1, rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : 1 }; // Complete initilization with howler.js core's init function. return _super.call(this, o); }; })(Howl.prototype.init); /** * Get/set the 3D spatial position of the audio source for this sound or * all in the group. The most common usage is to set the 'x' position for * left/right panning. Setting any value higher than 1.0 will begin to * decrease the volume of the sound as it moves further away. * @param {Number} x The x-position of the audio from -1000.0 to 1000.0. * @param {Number} y The y-position of the audio from -1000.0 to 1000.0. * @param {Number} z The z-position of the audio from -1000.0 to 1000.0. * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated. * @return {Howl/Array} Returns self or the current 3D spatial position: [x, y, z]. */ Howl.prototype.pos = function(x, y, z, id) { var self = this; // Stop right here if not using Web Audio. if (!self._webAudio) { return self; } // Wait for the sound to play before changing position. if (!self._loaded) { self.once('play', function() { self.pos(x, y, z, id); }); return self; } // Set the defaults for optional 'y' & 'z'. y = (typeof y !== 'number') ? 0 : y; z = (typeof z !== 'number') ? -0.5 : z; // Setup the group's spatial position if no ID is passed. if (typeof id === 'undefined') { // Return the group's spatial position if no parameters are passed. if (typeof x === 'number') { self._pos = [x, y, z]; } else { return self._pos; } } // Change the spatial position of one or all sounds in group. var ids = self._getSoundIds(id); for (var i=0; i<ids.length; i++) { // Get the sound. var sound = self._soundById(ids[i]); if (sound) { if (typeof x === 'number') { sound._pos = [x, y, z]; if (sound._node) { // Check if there is a panner setup and create a new one if not. if (!sound._panner) { setupPanner(sound); } sound._panner.setPosition(x, y, z); } } else { return sound._pos; } } } return self; }; /** * Get/set the direction the audio source is pointing in the 3D cartesian coordinate * space. Depending on how direction the sound is, based on the `cone` attributes, * a sound pointing away from the listener can be quiet or silent. * @param {Number} x The x-orientation of the source. * @param {Number} y The y-orientation of the source. * @param {Number} z The z-orientation of the source. * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated. * @return {Howl/Array} Returns self or the current 3D spatial orientation: [x, y, z]. */ Howl.prototype.orientation = function(x, y, z, id) { var self = this; // Stop right here if not using Web Audio. if (!self._webAudio) { return self; } // Wait for the sound to play before changing orientation. if (!self._loaded) { self.once('play', function() { self.orientation(x, y, z, id); }); return self; } // Set the defaults for optional 'y' & 'z'. y = (typeof y !== 'number') ? self._orientation[1] : y; z = (typeof z !== 'number') ? self._orientation[1] : z; // Setup the group's spatial orientation if no ID is passed. if (typeof id === 'undefined') { // Return the group's spatial orientation if no parameters are passed. if (typeof x === 'number') { self._orientation = [x, y, z]; } else { return self._orientation; } } // Change the spatial orientation of one or all sounds in group. var ids = self._getSoundIds(id); for (var i=0; i<ids.length; i++) { // Get the sound. var sound = self._soundById(ids[i]); if (sound) { if (typeof x === 'number') { sound._orientation = [x, y, z]; if (sound._node) { // Check if there is a panner setup and create a new one if not. if (!sound._panner) { setupPanner(sound); } sound._panner.setOrientation(x, y, z); } } else { return sound._orientation; } } } return self; }; /** * Get/set the velocity vector of the audio source or group. This controls both * direction and speed in 3D space and is relative to the listener's velocity. * The units are meters/second and are independent of position and orientation. * @param {Number} x The x-velocity of the source. * @param {Number} y The y-velocity of the source. * @param {Number} z The z-velocity of the source. * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated. * @return {Howl/Array} Returns self or the current 3D spatial velocity: [x, y, z]. */ Howl.prototype.velocity = function(x, y, z, id) { var self = this; // Stop right here if not using Web Audio. if (!self._webAudio) { return self; } // Wait for the sound to play before changing velocity. if (!self._loaded) { self.once('play', function() { self.velocity(x, y, z, id); }); return self; } // Set the defaults for optional 'y' & 'z'. y = (typeof y !== 'number') ? self._velocity[1] : y; z = (typeof z !== 'number') ? self._velocity[1] : z; // Setup the group's spatial velocity if no ID is passed. if (typeof id === 'undefined') { // Return the group's spatial velocity if no parameters are passed. if (typeof x === 'number') { self._velocity = [x, y, z]; } else { return self._velocity; } } // Change the spatial velocity of one or all sounds in group. var ids = self._getSoundIds(id); for (var i=0; i<ids.length; i++) { // Get the sound. var sound = self._soundById(ids[i]); if (sound) { if (typeof x === 'number') { sound._velocity = [x, y, z]; if (sound._node) { // Check if there is a panner setup and create a new one if not. if (!sound._panner) { setupPanner(sound); } sound._panner.setVelocity(x, y, z); } } else { return sound._velocity; } } } return self; }; /** * Get/set the panner node's attributes for a sound or group of sounds. * This method can optionall take 0, 1 or 2 arguments. * pannerAttr() -> Returns the group's values. * pannerAttr(id) -> Returns the sound id's values. * pannerAttr(o) -> Set's the values of all sounds in this Howl group. * pannerAttr(o, id) -> Set's the values of passed sound id. * * Attributes: * coneInnerAngle - (360 by default) There will be no volume reduction inside this angle. * coneOuterAngle - (360 by default) The volume will be reduced to a constant value of * `coneOuterGain` outside this angle. * coneOuterGain - (0 by default) The amount of volume reduction outside of `coneOuterAngle`. * distanceModel - ('inverse' by default) Determines algorithm to use to reduce volume as audio moves * away from listener. Can be `linear`, `inverse` or `exponential. * maxDistance - (10000 by default) Volume won't reduce between source/listener beyond this distance. * panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio. * Can be `HRTF` or `equalpower`. * refDistance - (1 by default) A reference distance for reducing volume as the source * moves away from the listener. * rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. * * @return {Howl/Object} Returns self or current panner attributes. */ Howl.prototype.pannerAttr = function() { var self = this; var args = arguments; var o, id, sound; // Stop right here if not using Web Audio. if (!self._webAudio) { return self; } // Determine the values based on arguments. if (args.length === 0) { // Return the group's panner attribute values. return self._pannerAttr; } else if (args.length === 1) { if (typeof args[0] === 'object') { o = args[0]; // Set the grou's panner attribute values. if (typeof id === 'undefined') { self._pannerAttr = { coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : self._coneInnerAngle, coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : self._coneOuterAngle, coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : self._coneOuterGain, distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : self._distanceModel, maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : self._maxDistance, panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : self._panningModel, refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : self._refDistance, rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : self._rolloffFactor }; } } else { // Return this sound's panner attribute values. sound = self._soundById(parseInt(args[0], 10)); return sound ? sound._pannerAttr : self._pannerAttr; } } else if (args.length === 2) { o = args[0]; id = parseInt(args[1], 10); } // Update the values of the specified sounds. var ids = self._getSoundIds(id); for (var i=0; i<ids.length; i++) { sound = self._soundById(ids[i]); if (sound) { // Merge the new values into the sound. var pa = sound._pannerAttr; pa = { coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : pa.coneInnerAngle, coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : pa.coneOuterAngle, coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : pa.coneOuterGain, distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : pa.distanceModel, maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : pa.maxDistance, panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : pa.panningModel, refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : pa.refDistance, rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : pa.rolloffFactor }; // Update the panner values or create a new panner if none exists. var panner = sound._panner; if (panner) { panner.coneInnerAngle = pa.coneInnerAngle; panner.coneOuterAngle = pa.coneOuterAngle; panner.coneOuterGain = pa.coneOuterGain; panner.distanceModel = pa.distanceModel; panner.maxDistance = pa.maxDistance; panner.panningModel = pa.panningModel; panner.refDistance = pa.refDistance; panner.rolloffFactor = pa.rolloffFactor; } else { // Make sure we have a position to setup the node with. if (!sound._pos) { sound._pos = self._pos || [0, 0, -0.5]; } // Create a new panner node. setupPanner(sound); } } } return self; }; /** Single Sound Methods **/ /***************************************************************************/ /** * Add new properties to the core Sound init. * @param {Function} _super Core Sound init method. * @return {Sound} */ Sound.prototype.init = (function(_super) { return function() { var self = this; var parent = self._parent; // Setup user-defined default properties. self._orientation = parent._orientation; self._pos = parent._pos; self._velocity = parent._velocity; self._pannerAttr = parent._pannerAttr; // Complete initilization with howler.js core Sound's init function. _super.call(this); // If a position was specified, set it up. if (self._pos) { parent.pos(self._pos[0], self._pos[1], self._pos[2], self._id); } }; })(Sound.prototype.init); /** * Override the Sound.reset method to clean up properties from the effects plugin. * @param {Function} _super Sound reset method. * @return {Sound} */ Sound.prototype.reset = (function(_super) { return function() { var self = this; var parent = self._parent; // Reset all effects module properties on this sound. self._orientation = parent._orientation; self._pos = parent._pos; self._velocity = parent._velocity; self._pannerAttr = parent._pannerAttr; // Complete resetting of the sound. return _super.call(this); }; })(Sound.prototype.reset); /** Helper Methods **/ /***************************************************************************/ /** * Create a new panner node and save it on the sound. * @param {Sound} sound Specific sound to setup panning on. */ var setupPanner = function(sound) { // Create the new panner node. sound._panner = Howler.ctx.createPanner(); sound._panner.coneInnerAngle = (sound._pannerAttr.coneInnerAngle!==undefined) ? sound._pannerAttr.coneInnerAngle : sound._panner.coneInnerAngle; sound._panner.coneOuterAngle = (sound._pannerAttr.coneOuterAngle!==undefined) ? sound._pannerAttr.coneOuterAngle : sound._panner.coneOuterAngle; sound._panner.coneOuterGain = (sound._pannerAttr.coneOuterGain!==undefined) ? sound._pannerAttr.coneOuterGain : sound._panner.coneOuterGain; sound._panner.distanceModel = (sound._pannerAttr.distanceModel!==undefined) ? sound._pannerAttr.distanceModel : sound._panner.distanceModel; sound._panner.maxDistance = (sound._pannerAttr.maxDistance!==undefined) ? sound._pannerAttr.maxDistance : sound._panner.maxDistance; sound._panner.panningModel = (sound._pannerAttr.panningModel!==undefined) ? sound._pannerAttr.panningModel : sound._panner.panningModel; sound._panner.refDistance = (sound._pannerAttr.refDistance!==undefined) ? sound._pannerAttr.refDistance : sound._panner.refDistance; sound._panner.rolloffFactor = (sound._pannerAttr.rolloffFactor!==undefined) ? sound._pannerAttr.rolloffFactor : sound._panner.rolloffFactor; sound._panner.setPosition(sound._pos[0], sound._pos[1], sound._pos[2]); sound._panner.setOrientation(sound._orientation[0], sound._orientation[1], sound._orientation[2]); sound._panner.setVelocity(sound._velocity[0], sound._velocity[1], sound._velocity[2]); sound._panner.connect(sound._node); // Update the connections. if (!sound._paused) { sound._parent.pause(sound._id).play(sound._id); } }; })();
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/therapies/vo/StrengtheningProgramVoCollection.java
8614
//############################################################################# //# # //# 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.therapies.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to therapies.treatment.StrengtheningProgram business object (ID: 1019100052). */ public class StrengtheningProgramVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<StrengtheningProgramVo> { private static final long serialVersionUID = 1L; private ArrayList<StrengtheningProgramVo> col = new ArrayList<StrengtheningProgramVo>(); public String getBoClassName() { return "ims.therapies.treatment.domain.objects.StrengtheningProgram"; } public boolean add(StrengtheningProgramVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, StrengtheningProgramVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(StrengtheningProgramVo instance) { return col.indexOf(instance); } public StrengtheningProgramVo get(int index) { return this.col.get(index); } public boolean set(int index, StrengtheningProgramVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(StrengtheningProgramVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(StrengtheningProgramVo instance) { return indexOf(instance) >= 0; } public Object clone() { StrengtheningProgramVoCollection clone = new StrengtheningProgramVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((StrengtheningProgramVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; 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]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public StrengtheningProgramVoCollection sort() { return sort(SortOrder.ASCENDING); } public StrengtheningProgramVoCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public StrengtheningProgramVoCollection sort(SortOrder order) { return sort(new StrengtheningProgramVoComparator(order)); } public StrengtheningProgramVoCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new StrengtheningProgramVoComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public StrengtheningProgramVoCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public ims.therapies.treatment.vo.StrengtheningProgramRefVoCollection toRefVoCollection() { ims.therapies.treatment.vo.StrengtheningProgramRefVoCollection result = new ims.therapies.treatment.vo.StrengtheningProgramRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { result.add(this.col.get(x)); } return result; } public StrengtheningProgramVo[] toArray() { StrengtheningProgramVo[] arr = new StrengtheningProgramVo[col.size()]; col.toArray(arr); return arr; } public Iterator<StrengtheningProgramVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class StrengtheningProgramVoComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public StrengtheningProgramVoComparator() { this(SortOrder.ASCENDING); } public StrengtheningProgramVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public StrengtheningProgramVoComparator(SortOrder order, boolean caseInsensitive) { if (order == SortOrder.DESCENDING) { direction = -1; } this.caseInsensitive = caseInsensitive; } public int compare(Object obj1, Object obj2) { StrengtheningProgramVo voObj1 = (StrengtheningProgramVo)obj1; StrengtheningProgramVo voObj2 = (StrengtheningProgramVo)obj2; return direction*(voObj1.compareTo(voObj2, this.caseInsensitive)); } public boolean equals(Object obj) { return false; } } public ims.therapies.vo.beans.StrengtheningProgramVoBean[] getBeanCollection() { return getBeanCollectionArray(); } public ims.therapies.vo.beans.StrengtheningProgramVoBean[] getBeanCollectionArray() { ims.therapies.vo.beans.StrengtheningProgramVoBean[] result = new ims.therapies.vo.beans.StrengtheningProgramVoBean[col.size()]; for(int i = 0; i < col.size(); i++) { StrengtheningProgramVo vo = ((StrengtheningProgramVo)col.get(i)); result[i] = (ims.therapies.vo.beans.StrengtheningProgramVoBean)vo.getBean(); } return result; } public static StrengtheningProgramVoCollection buildFromBeanCollection(java.util.Collection beans) { StrengtheningProgramVoCollection coll = new StrengtheningProgramVoCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while (iter.hasNext()) { coll.add(((ims.therapies.vo.beans.StrengtheningProgramVoBean)iter.next()).buildVo()); } return coll; } public static StrengtheningProgramVoCollection buildFromBeanCollection(ims.therapies.vo.beans.StrengtheningProgramVoBean[] beans) { StrengtheningProgramVoCollection coll = new StrengtheningProgramVoCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(beans[x].buildVo()); } return coll; } }
agpl-3.0
BuildingSMART/IfcDoc
IfcKit/schemas/IfcSharedBldgServiceElements/IfcFlowMovingDevice.cs
1366
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org. // IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Xml.Serialization; using BuildingSmart.IFC.IfcGeometricConstraintResource; using BuildingSmart.IFC.IfcKernel; using BuildingSmart.IFC.IfcMeasureResource; using BuildingSmart.IFC.IfcProductExtension; using BuildingSmart.IFC.IfcRepresentationResource; using BuildingSmart.IFC.IfcSharedBldgElements; using BuildingSmart.IFC.IfcStructuralAnalysisDomain; using BuildingSmart.IFC.IfcUtilityResource; namespace BuildingSmart.IFC.IfcSharedBldgServiceElements { public partial class IfcFlowMovingDevice : IfcDistributionFlowElement { public IfcFlowMovingDevice(IfcGloballyUniqueId __GlobalId, IfcOwnerHistory __OwnerHistory, IfcLabel? __Name, IfcText? __Description, IfcLabel? __ObjectType, IfcObjectPlacement __ObjectPlacement, IfcProductRepresentation __Representation, IfcIdentifier? __Tag) : base(__GlobalId, __OwnerHistory, __Name, __Description, __ObjectType, __ObjectPlacement, __Representation, __Tag) { } } }
agpl-3.0
wmbutler/courtlistener
alert/citations/management/commands/cl_add_citations_to_docs.py
6828
from datetime import datetime import time import sys from django.conf import settings from alert.lib.db_tools import queryset_generator from alert.lib import sunburnt from alert.search.models import Document from celery.task.sets import TaskSet from citations.tasks import update_document from django.core.management import call_command from django.core.management import BaseCommand, CommandError from django.utils.timezone import make_aware, utc from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '--doc_id', type=int, help='id of a document to update' ), make_option( '--start_id', type=int, default=0, help='start id for a range of documents to update' ), make_option( '--end_id', type=int, help='end id for a range of documents to update' ), make_option( # Note that there's a temptation to add a field here for # date_modified, to get any recently modified files. The danger of # doing this is that you modify files as you process them, # creating an endless loop. You'll start the program reporting X # files to modify, but after those items finish, you'll discover # that the program continues onto the newly edited files, # including those files that have new citations to them. '--filed_after', type=str, help="Start date in ISO-8601 format for a range of documents to " "update" ), make_option( '--all', default=False, action='store_true', help='Parse citations for all items', ), make_option( '--index', default='all_at_end', type=str, help=("When/if to save changes to the Solr index. Options are " "all_at_end, concurrently or False. Saving 'concurrently' " "is least efficient, since each document is updated once " "for each citation to it, however this setting will show " "changes in the index in realtime. Saving 'all_at_end' can " "be considerably more efficient, but will not show changes " "until the process has finished and the index has been " "completely regenerated from the database. Setting this to " "False disables changes to Solr, if that is what's desired. " "Finally, only 'concurrently' will avoid reindexing the " "entire collection."), ) ) help = 'Parse citations out of documents.' def update_documents(self, documents, count): sys.stdout.write('Graph size is {0:d} nodes.\n'.format(count)) sys.stdout.flush() processed_count = 0 subtasks = [] timings = [] average_per_s = 0 if self.index == 'concurrently': index_during_subtask = True else: index_during_subtask = False for doc in documents: processed_count += 1 if processed_count % 10000 == 0: # Send the commit every 10000 times. self.si.commit() subtasks.append(update_document.subtask((doc, index_during_subtask))) if processed_count % 1000 == 1: t1 = time.time() if processed_count % 1000 == 0: t2 = time.time() timings.append(t2 - t1) average_per_s = 1000 / (sum(timings) / float(len(timings))) sys.stdout.write("\rProcessing items in Celery queue: {:.0%} ({}/{}, {:.1f}/s)".format( processed_count * 1.0 / count, processed_count, count, average_per_s )) sys.stdout.flush() last_document = (count == processed_count) if (processed_count % 500 == 0) or last_document: # Every 500 documents, we send the subtasks off for processing # Poll to see when they're done. job = TaskSet(tasks=subtasks) result = job.apply_async() while not result.ready(): time.sleep(0.5) # The jobs finished - clean things up for the next round subtasks = [] if self.index == 'all_at_end': call_command( 'cl_update_index', update_mode=True, everything=True, solr_url='http://127.0.0.1:8983/solr/collection1' ) elif self.index == 'false': sys.stdout.write("Solr index not updated after running citation " "finder. You may want to do so manually.") def handle(self, *args, **options): both_list_and_endpoints = (options.get('doc_id') is not None and (options.get('start_id') is not None or options.get('end_id') is not None or options.get('filed_after') is not None)) no_option = (not any([options.get('doc_id') is None, options.get('start_id') is None, options.get('end_id') is None, options.get('filed_after') is None, options.get('all') is False])) if both_list_and_endpoints or no_option: raise CommandError('Please specify either a list of documents, a ' 'range of ids, a range of dates, or ' 'everything.') if options.get('filed_after'): start_date = make_aware(datetime.strptime(options['filed_after'], '%Y-%m-%d'), utc) self.index = options['index'].lower() self.si = sunburnt.SolrInterface(settings.SOLR_OPINION_URL, mode='rw') # Use query chaining to build the query query = Document.objects.all() if options.get('doc_id'): query = query.filter(pk=options.get('doc_id')) if options.get('end_id'): query = query.filter(pk__lte=options.get('end_id')) if options.get('start_id'): query = query.filter(pk__gte=options.get('start_id')) if options.get('filed_after'): query = query.filter(date_filed__gte=start_date) if options.get('all'): query = Document.objects.all() count = query.count() docs = queryset_generator(query, chunksize=10000) self.update_documents(docs, count)
agpl-3.0
Peergos/Peergos
src/peergos/server/net/ResponseHeaderHandler.java
702
package peergos.server.net; import com.sun.net.httpserver.*; import java.io.*; import java.util.*; public class ResponseHeaderHandler implements HttpHandler { private final Map<String, String> responseHeaders; private final HttpHandler handler; public ResponseHeaderHandler(Map<String, String> responseHeaders, HttpHandler handler) { this.responseHeaders = responseHeaders; this.handler = handler; } @Override public void handle(HttpExchange httpExchange) throws IOException { for (String key: responseHeaders.keySet()) httpExchange.getResponseHeaders().set(key, responseHeaders.get(key)); handler.handle(httpExchange); } }
agpl-3.0
kyriog/youfood-web
test/functional/frontend/menuActionsTest.php
391
<?php include(dirname(__FILE__).'/../../bootstrap/functional.php'); $browser = new sfTestFunctional(new sfBrowser()); $browser-> get('/menu/index')-> with('request')->begin()-> isParameter('module', 'menu')-> isParameter('action', 'index')-> end()-> with('response')->begin()-> isStatusCode(200)-> checkElement('body', '!/This is a temporary page/')-> end() ;
agpl-3.0
AlexFloppy/laravel-api-boilerplate
app/Services/ActivationService.php
2741
<?php namespace App\Services; use App\Models\Activation; use App\Models\User; use Carbon\Carbon; use Hash; use Mail; /** * Class ActivationRepository * @package App\Repositories */ class ActivationService { /** * Activation email template * * @var string */ protected $activationEmailTemplate = 'emails.activation'; /** * @param User $user * * @return string */ public function createActivation(User $user) { $user->activation()->delete(); $hash = Hash::make(str_random(Activation::ACTIVATION_HASH_LENGTH)); $expired = Carbon::now()->addDay(); Activation::insert([ 'user_id' => $user->id, 'token' => $hash, 'expired' => $expired, ]); return $hash; } /** * @param User $user * * @return Activation */ public function getActivation(User $user) { return $user->activation; } /** * @param string $token * * @return Activation */ public function getActivationByToken(string $token) { return Activation::where('token', $token)->first(); } /** * @param string $token * * @return bool */ public function verifyEmail(string $token) { $activation = Activation::where('token', $token)->first(); if ($activation) { $user = $activation->user; $user->activated = true; $user->save(); $activation->delete(); return $user; } return false; } /** * */ public function deleteOldActivations() { $date = Carbon::now()->subDays(Activation::EXPIRE_DAYS); $activations = Activation::where('expired', '<', $date->toDateTimeString())->get(); if (!$activations->isEmpty()) { User::destroy($activations->pluck('user_id')); } } /** * @param User $user * @param string $hash */ public function sendActivationEmail(User $user, string $hash) { return Mail::send( $this->activationEmailTemplate, ['hash' => $hash], function ($message) use ($user) { $message->to($user->email, $user->usename)->subject('Laravel api boilerplate'); } ); } /** * @param $email * @return bool */ public function resendActivationEmail($email) { $user = User::where('email', '=', $email)->first(); if ($user->activated) { return false; } $hash = $this->createActivation($user); $this->sendActivationEmail($user, $hash); return true; } }
agpl-3.0
armadillotec/SuiteSelectra
selectraerp/modulos/principal/templates_c/%%F5^F54^F5494468%%cargar_post.tpl.php
559
<?php /* Smarty version 2.6.21, created on 2013-07-31 18:43:25 compiled from cargar_post.tpl */ ?> <br> <br> <br> <br> <br> <center> Seleccione el Archivo POST a importar <form action='?opt_menu=<?php echo $_GET['opt_menu']; ?> &opt_seccion=<?php echo $_GET['opt_seccion']; ?> ' enctype="multipart/form-data" method='POST' > <input name='archivo' type='file'> </input> <br> <br><br> <input type='submit' name='boton' value='Enviar Archivo'> </input> </form> <br> <br> <?php echo $this->_tpl_vars['info']; ?> </center> </br>
agpl-3.0
djbender/canvas-lms
spec/apis/v1/services_api_spec.rb
4129
# # Copyright (C) 2011 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # require File.expand_path(File.dirname(__FILE__) + '/../api_spec_helper') describe "Services API", type: :request do before :once do user_with_pseudonym(:active_all => true) end before :each do @kal = double('CanvasKaltura::ClientV3') allow(CanvasKaltura::ClientV3).to receive(:config).and_return({ 'domain' => 'kaltura.fake.local', 'resource_domain' => 'cdn.kaltura.fake.local', 'rtmp_domain' => 'rtmp-kaltura.fake.local', 'partner_id' => '420', }) end it "should check for auth" do get("/api/v1/services/kaltura") assert_status(401) end it "should return the config information for kaltura" do json = api_call(:get, "/api/v1/services/kaltura", :controller => "services_api", :action => "show_kaltura_config", :format => "json") expect(json).to eq({ 'enabled' => true, 'domain' => 'kaltura.fake.local', 'resource_domain' => 'cdn.kaltura.fake.local', 'rtmp_domain' => 'rtmp-kaltura.fake.local', 'partner_id' => '420', }) end it "should degrade gracefully if kaltura is disabled or not configured" do allow(CanvasKaltura::ClientV3).to receive(:config).and_return(nil) json = api_call(:get, "/api/v1/services/kaltura", :controller => "services_api", :action => "show_kaltura_config", :format => "json") expect(json).to eq({ 'enabled' => false, }) end it "should return a new kaltura session" do stub_kaltura kal = double('CanvasKaltura::ClientV3') expect(kal).to receive(:startSession).and_return "new_session_id_here" allow(CanvasKaltura::ClientV3).to receive(:new).and_return(kal) json = api_call(:post, "/api/v1/services/kaltura_session", :controller => "services_api", :action => "start_kaltura_session", :format => "json") expect(json.delete_if { |k| %w(serverTime).include?(k) }).to eq({ 'ks' => "new_session_id_here", 'subp_id' => '10000', 'partner_id' => '100', 'uid' => "#{@user.id}_#{Account.default.id}", }) end it "should return a new kaltura session with upload config if param provided" do stub_kaltura kal = double('CanvasKaltura::ClientV3') expect(kal).to receive(:startSession).and_return "new_session_id_here" allow(CanvasKaltura::ClientV3).to receive(:new).and_return(kal) json = api_call(:post, "/api/v1/services/kaltura_session", :controller => "services_api", :action => "start_kaltura_session", :format => "json", :include_upload_config => 1) expect(json.delete_if { |k| %w(serverTime).include?(k) }).to eq({ 'ks' => "new_session_id_here", 'subp_id' => '10000', 'partner_id' => '100', 'uid' => "#{@user.id}_#{Account.default.id}", 'kaltura_setting' => { 'domain'=>'kaltura.example.com', 'kcw_ui_conf'=>'1', 'partner_id'=>'100', 'player_ui_conf'=>'1', 'resource_domain'=>'kaltura.example.com', 'subpartner_id'=>'10000', 'upload_ui_conf'=>'1', 'entryUrl' => 'http:///index.php/partnerservices2/addEntry', 'uiconfUrl' => 'http:///index.php/partnerservices2/getuiconf', 'uploadUrl' => 'http:///index.php/partnerservices2/upload', 'partner_data' => { 'root_account_id'=>@user.account.root_account.id, 'sis_source_id'=>nil, 'sis_user_id'=>nil }, }, }) end end
agpl-3.0
coder-han/Orpheus
src/net/server/handlers/channel/RangedAttackHandler.java
8983
/* OrpheusMS: MapleStory Private Server based on OdinMS Copyright (C) 2012 Aaron Weiss <aaron@deviant-core.net> Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.server.handlers.channel; import client.IItem; import client.ISkill; import client.MapleBuffStat; import client.MapleCharacter; import client.MapleCharacter.CancelCooldownAction; import client.MapleClient; import client.MapleInventory; import client.MapleInventoryType; import client.MapleWeaponType; import client.SkillFactory; import constants.ItemConstants; import constants.ServerConstants; import constants.skills.Aran; import constants.skills.Buccaneer; import constants.skills.NightLord; import constants.skills.NightWalker; import constants.skills.Shadower; import constants.skills.ThunderBreaker; import constants.skills.WindArcher; import tools.Randomizer; import net.MaplePacket; import server.MapleInventoryManipulator; import server.MapleItemInformationProvider; import server.MapleStatEffect; import server.TimerManager; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; public final class RangedAttackHandler extends AbstractDealDamageHandler { @Override public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { MapleCharacter player = c.getPlayer(); AttackInfo attack = parseDamage(slea, player, true); if (attack.skill == Buccaneer.ENERGY_ORB || attack.skill == ThunderBreaker.SPARK || attack.skill == Shadower.TAUNT || attack.skill == NightLord.TAUNT) { player.getMap().broadcastMessage(player, MaplePacketCreator.rangedAttack(player, attack.skill, attack.skilllevel, attack.stance, attack.numAttackedAndDamage, 0, attack.allDamage, attack.speed, attack.direction, attack.display), false); applyAttack(attack, player, 1); } else if (attack.skill == Aran.COMBO_SMASH || attack.skill == Aran.COMBO_PENRIL || attack.skill == Aran.COMBO_TEMPEST) { player.getMap().broadcastMessage(player, MaplePacketCreator.rangedAttack(player, attack.skill, attack.skilllevel, attack.stance, attack.numAttackedAndDamage, 0, attack.allDamage, attack.speed, attack.direction, attack.display), false); if (attack.skill == Aran.COMBO_SMASH && player.getCombo() >= 30) { applyAttack(attack, player, 1); } else if (attack.skill == Aran.COMBO_PENRIL && player.getCombo() >= 100) { applyAttack(attack, player, 2); } else if (attack.skill == Aran.COMBO_TEMPEST && player.getCombo() >= 200) { applyAttack(attack, player, 4); } } else { IItem weapon = player.getInventory(MapleInventoryType.EQUIPPED).getItem((byte) -11); MapleWeaponType type = MapleItemInformationProvider.getInstance().getWeaponType(weapon.getItemId()); if (type == MapleWeaponType.NOT_A_WEAPON) { return; } int projectile = 0; byte bulletCount = 1; MapleStatEffect effect = null; if (attack.skill != 0) { effect = attack.getAttackEffect(player, null); bulletCount = effect.getBulletCount(); if (effect.getCooldown() > 0) { c.announce(MaplePacketCreator.skillCooldown(attack.skill, effect.getCooldown())); } } boolean hasShadowPartner = player.getBuffedValue(MapleBuffStat.SHADOWPARTNER) != null; if (hasShadowPartner) { bulletCount *= 2; } MapleInventory inv = player.getInventory(MapleInventoryType.USE); for (byte i = 0; i < inv.getSlotLimit(); i++) { IItem item = inv.getItem(i); if (item != null) { int id = item.getItemId(); boolean bow = ItemConstants.isArrowForBow(id); boolean cbow = ItemConstants.isArrowForCrossBow(id); if (item.getQuantity() > (bulletCount == 1 ? 0 : bulletCount)) { if (type == MapleWeaponType.CLAW && ItemConstants.isThrowingStar(id) && weapon.getItemId() != 1472063) { if (((id == 2070007 || id == 2070018) && player.getLevel() < 70) || (id == 2070016 && player.getLevel() < 50)) { } else { projectile = id; break; } } else if ((type == MapleWeaponType.GUN && ItemConstants.isBullet(id))) { if (id == 2331000 && id == 2332000) { if (player.getLevel() > 69) { projectile = id; break; } } else if (player.getLevel() > (id % 10) * 20 + 9) { projectile = id; break; } } else if ((type == MapleWeaponType.BOW && bow) || (type == MapleWeaponType.CROSSBOW && cbow) || (weapon.getItemId() == 1472063 && (bow || cbow))) { projectile = id; break; } } } } boolean soulArrow = player.getBuffedValue(MapleBuffStat.SOULARROW) != null; boolean shadowClaw = player.getBuffedValue(MapleBuffStat.SHADOW_CLAW) != null; if (!soulArrow && !shadowClaw && attack.skill != 11101004 && attack.skill != 15111007 && attack.skill != 14101006) { byte bulletConsume = bulletCount; if (effect != null && effect.getBulletConsume() != 0) { bulletConsume = (byte) (effect.getBulletConsume() * (hasShadowPartner ? 2 : 1)); } if (!ServerConstants.UNLIMITED_PROJECTILES) { MapleInventoryManipulator.removeById(c, MapleInventoryType.USE, projectile, bulletConsume, false, true); } } if (projectile != 0 || soulArrow || attack.skill == 11101004 || attack.skill == 15111007 || attack.skill == 14101006) { int visProjectile = projectile; // visible projectile sent to // players if (ItemConstants.isThrowingStar(projectile)) { MapleInventory cash = player.getInventory(MapleInventoryType.CASH); for (int i = 0; i < 96; i++) { // impose order... IItem item = cash.getItem((byte) i); if (item != null) { if (item.getItemId() / 1000 == 5021) { visProjectile = item.getItemId(); break; } } } } else // bow, crossbow if (soulArrow || attack.skill == 3111004 || attack.skill == 3211004 || attack.skill == 11101004 || attack.skill == 15111007 || attack.skill == 14101006) { visProjectile = 0; } MaplePacket packet; switch (attack.skill) { case 3121004: // Hurricane case 3221001: // Pierce case 5221004: // Rapid Fire case 13111002: // KoC Hurricane packet = MaplePacketCreator.rangedAttack(player, attack.skill, attack.skilllevel, attack.rangedirection, attack.numAttackedAndDamage, visProjectile, attack.allDamage, attack.speed, attack.direction, attack.display); break; default: packet = MaplePacketCreator.rangedAttack(player, attack.skill, attack.skilllevel, attack.stance, attack.numAttackedAndDamage, visProjectile, attack.allDamage, attack.speed, attack.direction, attack.display); break; } player.getMap().broadcastMessage(player, packet, false, true); if (effect != null) { int money = effect.getMoneyCon(); if (money != 0) { int moneyMod = money / 2; money += Randomizer.nextInt(moneyMod); if (money > player.getMeso()) { money = player.getMeso(); } player.gainMeso(-money, false); } } if (attack.skill != 0) { ISkill skill = SkillFactory.getSkill(attack.skill); MapleStatEffect effect_ = skill.getEffect(player.getSkillLevel(skill)); if (effect_.getCooldown() > 0) { if (player.skillisCooling(attack.skill)) { return; } else { c.announce(MaplePacketCreator.skillCooldown(attack.skill, effect_.getCooldown())); player.addCooldown(attack.skill, System.currentTimeMillis(), effect_.getCooldown() * 1000, TimerManager.getInstance().schedule(new CancelCooldownAction(player, attack.skill), effect_.getCooldown() * 1000)); } } } if ((player.getSkillLevel(SkillFactory.getSkill(NightWalker.VANISH)) > 0 || player.getSkillLevel(SkillFactory.getSkill(WindArcher.WIND_WALK)) > 0) && player.getBuffedValue(MapleBuffStat.DARKSIGHT) != null && attack.numAttacked > 0 && player.getBuffSource(MapleBuffStat.DARKSIGHT) != 9101004) { player.cancelEffectFromBuffStat(MapleBuffStat.DARKSIGHT); player.cancelBuffStats(MapleBuffStat.DARKSIGHT); } applyAttack(attack, player, bulletCount); } } } }
agpl-3.0
colosa/processmaker
workflow/engine/config/paths.php
6279
<?php /** * paths.php * * ProcessMaker Open Source Edition * Copyright (C) 2004 - 2008 Colosa Inc.23 * * 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/>. * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. * */ /** * System Directories & Paths */ // Defining RBAC Paths constants define( 'PATH_RBAC_HOME', PATH_TRUNK . 'rbac' . PATH_SEP ); // Defining Gulliver framework paths constants define( 'PATH_GULLIVER_HOME', PATH_TRUNK . 'gulliver' . PATH_SEP ); define( 'PATH_GULLIVER', PATH_GULLIVER_HOME . 'system' . PATH_SEP ); //gulliver system classes define( 'PATH_GULLIVER_BIN', PATH_GULLIVER_HOME . 'bin' . PATH_SEP ); //gulliver bin classes define( 'PATH_TEMPLATE', PATH_GULLIVER_HOME . 'templates' . PATH_SEP ); define( 'PATH_THIRDPARTY', PATH_TRUNK . 'thirdparty' . PATH_SEP ); define( 'PATH_RBAC', PATH_RBAC_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP ); //to enable rbac version 2 define( 'PATH_RBAC_CORE', PATH_RBAC_HOME . 'engine' . PATH_SEP ); define( 'PATH_HTML', PATH_HOME . 'public_html' . PATH_SEP ); // Defining PMCore Path constants define( 'PATH_CORE', PATH_HOME . 'engine' . PATH_SEP ); define( 'PATH_SKINS', PATH_CORE . 'skins' . PATH_SEP ); define( 'PATH_SKIN_ENGINE', PATH_CORE . 'skinEngine' . PATH_SEP ); define( 'PATH_METHODS', PATH_CORE . 'methods' . PATH_SEP ); define( 'PATH_XMLFORM', PATH_CORE . 'xmlform' . PATH_SEP ); define( 'PATH_CONFIG', PATH_CORE . 'config' . PATH_SEP ); define( 'PATH_PLUGINS', PATH_CORE . 'plugins' . PATH_SEP ); define( 'PATH_HTMLMAIL', PATH_CORE . 'html_templates' . PATH_SEP ); define( 'PATH_TPL', PATH_CORE . 'templates' . PATH_SEP ); define( 'PATH_TEST', PATH_CORE . 'test' . PATH_SEP ); define( 'PATH_FIXTURES', PATH_TEST . 'fixtures' . PATH_SEP ); define( 'PATH_RTFDOCS' , PATH_CORE . 'rtf_templates' . PATH_SEP ); define( 'PATH_DYNACONT', PATH_CORE . 'content' . PATH_SEP . 'dynaform' . PATH_SEP ); //define( 'PATH_LANGUAGECONT',PATH_CORE . 'content' . PATH_SEP . 'languages' . PATH_SEP ); define( 'SYS_UPLOAD_PATH', PATH_HOME . "public_html/files/" ); define( 'PATH_UPLOAD', PATH_HTML . 'files' . PATH_SEP); define( 'PATH_WORKFLOW_MYSQL_DATA', PATH_CORE . 'data' . PATH_SEP.'mysql'.PATH_SEP); define( 'PATH_RBAC_MYSQL_DATA', PATH_RBAC_CORE . 'data' . PATH_SEP.'mysql'.PATH_SEP); define( 'FILE_PATHS_INSTALLED', PATH_CORE . 'config' . PATH_SEP . 'paths_installed.php' ); define( 'PATH_WORKFLOW_MSSQL_DATA', PATH_CORE . 'data' . PATH_SEP.'mssql'.PATH_SEP); define( 'PATH_RBAC_MSSQL_DATA', PATH_RBAC_CORE . 'data' . PATH_SEP.'mssql'.PATH_SEP); define( 'PATH_CONTROLLERS', PATH_CORE . 'controllers' . PATH_SEP ); define( 'PATH_SERVICES_REST', PATH_CORE . 'services' . PATH_SEP . 'rest' . PATH_SEP); // include Gulliver Class require_once( PATH_GULLIVER . PATH_SEP . 'class.g.php'); // include Bootstrap Class if(file_exists(FILE_PATHS_INSTALLED)) { // backward compatibility; parsing old definitions in the compiled path constant $tmp = file_get_contents(FILE_PATHS_INSTALLED); if (strpos($tmp, 'PATH_OUTTRUNK') !== false) { @file_put_contents(FILE_PATHS_INSTALLED, str_replace('PATH_OUTTRUNK', 'PATH_DATA', $tmp)); } // end backward compatibility // include the workspace installed configuration require_once FILE_PATHS_INSTALLED; // defining system constant when a valid workspace environment exists define('PATH_LANGUAGECONT', PATH_DATA . "META-INF" . PATH_SEP); define('PATH_CUSTOM_SKINS', PATH_DATA . 'skins' . PATH_SEP); define('PATH_TEMPORAL', PATH_C . 'dynEditor/'); define('PATH_DB', PATH_DATA . 'sites' . PATH_SEP); // smarty constants define('PATH_SMARTY_C', PATH_C . 'smarty' . PATH_SEP . 'c'); define('PATH_SMARTY_CACHE', PATH_C . 'smarty' . PATH_SEP . 'cache'); if (!is_dir(PATH_SMARTY_C)) { G::mk_dir(PATH_SMARTY_C); } if (!is_dir(PATH_SMARTY_CACHE)) { G::mk_dir(PATH_SMARTY_CACHE); } } // set include path set_include_path( PATH_CORE . PATH_SEPARATOR . PATH_THIRDPARTY . PATH_SEPARATOR . PATH_THIRDPARTY . 'pear'. PATH_SEPARATOR . PATH_RBAC_CORE . PATH_SEPARATOR . get_include_path() ); /** * Global definitions, before it was the defines.php file */ // URL Key define("URL_KEY", 'c0l0s40pt1mu59r1m3' ); // Other definitions define('TIMEOUT_RESPONSE', 100 ); //web service timeout define('APPLICATION_CODE', 'ProcessMaker' ); //to login like workflow system define('MAIN_POFILE', 'processmaker'); define('PO_SYSTEM_VERSION', 'PM 4.0.1'); $G_CONTENT = NULL; $G_MESSAGE = ""; $G_MESSAGE_TYPE = "info"; $G_MENU_SELECTED = -1; $G_MAIN_MENU = "default"; // Environment definitions define('G_PRO_ENV', 'PRODUCTION'); define('G_DEV_ENV', 'DEVELOPMENT'); define('G_TEST_ENV', 'TEST'); // Number of files per folder at PATH_UPLOAD (cases documents) define('APPLICATION_DOCUMENTS_PER_FOLDER', 1000); // Server of ProcessMaker Library define('PML_SERVER' , 'http://library.processmaker.com'); define('PML_WSDL_URL' , PML_SERVER . '/syspmLibrary/en/green/services/wsdl'); define('PML_UPLOAD_URL', PML_SERVER . '/syspmLibrary/en/green/services/uploadProcess'); define('PML_DOWNLOAD_URL', PML_SERVER . '/syspmLibrary/en/green/services/download'); G::defineConstants();
agpl-3.0
Crowducate/crowducate-platform
server/methods/users.js
433
Meteor.methods({ 'User.update': function(modifier, documentId) { check(modifier, Schema.User); Meteor.users.update(documentId, modifier); }, 'changeUserPassword': function(doc) { //TODO Refactor to submit form without method check(doc, Schema.User); }, 'User.biography.update': function(userId, doc) { Meteor.users.update(userId, { $set: { 'profile.biography': doc } }); } });
agpl-3.0
ESOedX/edx-platform
common/lib/xmodule/xmodule/contentstore/django.py
944
from __future__ import absolute_import from importlib import import_module from django.conf import settings _CONTENTSTORE = {} def load_function(path): """ Load a function by name. path is a string of the form "path.to.module.function" returns the imported python object `function` from `path.to.module` """ module_path, _, name = path.rpartition('.') return getattr(import_module(module_path), name) def contentstore(name='default'): if name not in _CONTENTSTORE: class_ = load_function(settings.CONTENTSTORE['ENGINE']) options = {} options.update(settings.CONTENTSTORE['DOC_STORE_CONFIG']) if 'ADDITIONAL_OPTIONS' in settings.CONTENTSTORE: if name in settings.CONTENTSTORE['ADDITIONAL_OPTIONS']: options.update(settings.CONTENTSTORE['ADDITIONAL_OPTIONS'][name]) _CONTENTSTORE[name] = class_(**options) return _CONTENTSTORE[name]
agpl-3.0
printedheart/opennars
nars_lab/src/main/java/jhelp/util/thread/MessageHandler.java
9654
package jhelp.util.thread; import java.util.PriorityQueue; import java.util.concurrent.atomic.AtomicBoolean; /** * Handler of messages.<br> * It reacts to messages posted for him.<br> * Its thread safe, that is to say, if 2 threads post a message in "same time", the {@link #messageArrived(Object)} is called * for one of them, then AFTER the code execution its done, its called again.<br> * In other words, {@link #messageArrived(Object)} will never called in "same time". It also means, it waits that a message is * completely manage (exit from {@link #messageArrived(Object)}) before doing an other stuff<br> * You have to call {@link #terminate()} when you need no more the handler * * @author JHelp * @param <MESSAGE> * Message type */ public abstract class MessageHandler<MESSAGE> { /** * A message * * @author JHelp * @param <ELEMENT> * Element type */ private static class Message<ELEMENT> implements Comparable<Message<ELEMENT>> { /** Message content */ ELEMENT element; /** Time when message should arrived */ long time; /** * Create a new instance of Message * * @param time * Time when message should arrived * @param element * Message content */ public Message(final long time, final ELEMENT element) { this.time = time; this.element = element; } /** * Compare with an other message, to know if this message must be receive before, after or in same time <br> * <br> * <b>Parent documentation:</b><br> * {@inheritDoc} * * @param message * Message to compare with * @return -1 (Before), 1 (After) or 0 (Same time) * @see Comparable#compareTo(Object) */ @Override public int compareTo(final Message<ELEMENT> message) { if(this.time < message.time) { return -1; } if(this.time > message.time) { return 1; } return 0; } /** * Indicates if an object is a message with same content <br> * <br> * <b>Parent documentation:</b><br> * {@inheritDoc} * * @param object * Object to compare with * @return {@code true} if the object is a message with same content * @see Object#equals(Object) */ @SuppressWarnings("unchecked") @Override public boolean equals(final Object object) { if((object == null) || (object.getClass().equals(this.getClass()) == false)) { return false; } return this.element.equals(((Message<ELEMENT>) object).element); } } /** Default waiting time */ private static final int DEFAULT_WAIT = 16864; /** Indicates if handler still alive */ private boolean alive; /** Internal thread */ private Thread internalThread = new Thread() { /** * Execute the internal thread <br> * <br> * <b>Parent documentation:</b><br> * {@inheritDoc} * * @see Thread#run() */ @Override public void run() { MessageHandler.this.doTheJob(); } }; /** Indicates if lock is on or off */ private final AtomicBoolean isLocked; /** Object for synchronization */ private final Object LOCK = new Object(); /** Mutex for exclusive access */ private final Mutex mutex; /** Queue of messages to give */ private final PriorityQueue<Message<MESSAGE>> priorityQueue; /** * Create a new instance of MessageHandler */ public MessageHandler() { this.priorityQueue = new PriorityQueue<Message<MESSAGE>>(); this.mutex = new Mutex(); this.isLocked = new AtomicBoolean(false); this.alive = true; this.internalThread.start(); } /** * Manage the messages to delivered */ final void doTheJob() { int wait; Message<MESSAGE> message = null; while(this.alive == true) { this.mutex.lock(); if(this.priorityQueue.isEmpty() == true) { message = null; } else { message = this.priorityQueue.peek(); } this.mutex.unlock(); if(message == null) { wait = MessageHandler.DEFAULT_WAIT; } else { wait = (int) (message.time - System.currentTimeMillis()); if(wait < 1) { this.messageArrived(message.element); this.priorityQueue.poll(); wait = 1; } } synchronized(this.LOCK) { this.isLocked.set(true); try { this.LOCK.wait(wait); } catch(final Exception exception) { } this.isLocked.set(false); } } } /** * Try to free memory if user forget to call {@link #terminate()} and the object is garbage collected <br> * <br> * <b>Parent documentation:</b><br> * {@inheritDoc} * * @throws Throwable * On issue * @see Object#finalize() */ @Override protected void finalize() throws Throwable { this.terminate(); super.finalize(); } /** * Called when a message arrived.<br> * It is their that the user can do the dedicated job * * @param message * Message arrived */ protected abstract void messageArrived(MESSAGE message); /** * Called just before handler will be destroyed, to do some safe stufs.<br> * Do nothing be default */ protected void willBeTerminated() { } /** * Cancel a message.<br> * Usually used with message post with {@link #postDelayedMessage(Object, int)} to cancel it before it is called.<br> * If the message already delivered, this method does nothing<br> * Can be used for timeout for example * * @param message * Message to cancel */ public final void cancelMessage(final MESSAGE message) { if(this.alive == false) { return; } if(message == null) { throw new NullPointerException("message musn't be null"); } this.mutex.lock(); this.priorityQueue.remove(new Message<MESSAGE>(0, message)); this.mutex.unlock(); } /** * Indicates if the handler still alive and can be used * * @return {@code true} if the handler still alive and can be used */ public final boolean isAlive() { return this.alive; } /** * Post a message delayed in a given time * * @param message * Message to delivered * @param millisecond * Time in millisecond to wait before sending the message */ public final void postDelayedMessage(final MESSAGE message, final int millisecond) { if(this.alive == false) { return; } if(message == null) { throw new NullPointerException("message musn't be null"); } this.mutex.lock(); this.priorityQueue.offer(new Message<MESSAGE>(System.currentTimeMillis() + Math.max(1, millisecond), message)); this.mutex.unlock(); synchronized(this.LOCK) { if(this.isLocked.get() == true) { this.LOCK.notify(); } } } /** * Post a message and deliver it as soon as possible * * @param message * Message to post */ public final void postMessage(final MESSAGE message) { if(this.alive == false) { return; } if(message == null) { throw new NullPointerException("message musn't be null"); } this.postDelayedMessage(message, 1); } /** * Stop the handler and destroy it.<br> * It can't be used after the calling of this method.<br> * It is strongly recommend to call it as soon as the handler is not still necessary */ public final void terminate() { if(this.alive == false) { return; } this.alive = false; this.willBeTerminated(); synchronized(this.LOCK) { if(this.isLocked.get() == true) { this.LOCK.notify(); } } this.internalThread = null; } }
agpl-3.0
petrjasek/superdesk-core
prod_api/users/service.py
217
from ..service import ProdApiService class UsersService(ProdApiService): excluded_fields = { "user_preferences", "session_preferences", "password", } | ProdApiService.excluded_fields
agpl-3.0
laclasse-com/service-cahiertextes
public/node_modules/sweetalert2/src/utils/isNodeEnv.js
115
// Detect Node env export const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined'
agpl-3.0
armycreator/armycreator-website
web/forum/includes/ucp/ucp_register.php
18484
<?php /** * * This file is part of the phpBB Forum Software package. * * @copyright (c) phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ /** * @ignore */ if (!defined('IN_PHPBB')) { exit; } /** * ucp_register * Board registration */ class ucp_register { var $u_action; function main($id, $mode) { global $config, $db, $user, $template, $phpbb_root_path, $phpEx; global $request, $phpbb_container, $phpbb_dispatcher; // if ($config['require_activation'] == USER_ACTIVATION_DISABLE || (in_array($config['require_activation'], array(USER_ACTIVATION_SELF, USER_ACTIVATION_ADMIN)) && !$config['email_enable'])) { trigger_error('UCP_REGISTER_DISABLE'); } $coppa = $request->is_set('coppa') ? (int) $request->variable('coppa', false) : false; $agreed = $request->variable('agreed', false); $submit = $request->is_set_post('submit'); $change_lang = $request->variable('change_lang', ''); $user_lang = $request->variable('lang', $user->lang_name); /** * Add UCP register data before they are assigned to the template or submitted * * To assign data to the template, use $template->assign_vars() * * @event core.ucp_register_requests_after * @var bool coppa Is set coppa * @var bool agreed Did user agree to coppa? * @var bool submit Is set post submit? * @var string change_lang Change language request * @var string user_lang User language request * @since 3.1.11-RC1 */ $vars = array( 'coppa', 'agreed', 'submit', 'change_lang', 'user_lang', ); extract($phpbb_dispatcher->trigger_event('core.ucp_register_requests_after', compact($vars))); if ($agreed) { add_form_key('ucp_register'); } else { add_form_key('ucp_register_terms'); } if ($change_lang || $user_lang != $config['default_lang']) { $use_lang = ($change_lang) ? basename($change_lang) : basename($user_lang); if (!validate_language_iso_name($use_lang)) { if ($change_lang) { $submit = false; // Setting back agreed to let the user view the agreement in his/her language $agreed = false; } $user_lang = $use_lang; } else { $change_lang = ''; $user_lang = $user->lang_name; } } /* @var $cp \phpbb\profilefields\manager */ $cp = $phpbb_container->get('profilefields.manager'); $error = $cp_data = $cp_error = array(); $s_hidden_fields = array(); // Handle login_link data added to $_hidden_fields $login_link_data = $this->get_login_link_data_array(); if (!empty($login_link_data)) { // Confirm that we have all necessary data /* @var $provider_collection \phpbb\auth\provider_collection */ $provider_collection = $phpbb_container->get('auth.provider_collection'); $auth_provider = $provider_collection->get_provider($request->variable('auth_provider', '')); $result = $auth_provider->login_link_has_necessary_data($login_link_data); if ($result !== null) { $error[] = $user->lang[$result]; } $s_hidden_fields = array_merge($s_hidden_fields, $this->get_login_link_data_for_hidden_fields($login_link_data)); } if (!$agreed || ($coppa === false && $config['coppa_enable']) || ($coppa && !$config['coppa_enable'])) { $add_coppa = ($coppa !== false) ? '&amp;coppa=' . $coppa : ''; $s_hidden_fields = array_merge($s_hidden_fields, array( 'change_lang' => '', )); // If we change the language, we want to pass on some more possible parameter. if ($change_lang) { // We do not include the password $s_hidden_fields = array_merge($s_hidden_fields, array( 'username' => $request->variable('username', '', true), 'email' => strtolower($request->variable('email', '')), 'lang' => $user->lang_name, 'tz' => $request->variable('tz', $config['board_timezone']), )); } // Checking amount of available languages $sql = 'SELECT lang_id FROM ' . LANG_TABLE; $result = $db->sql_query($sql); $lang_row = array(); while ($row = $db->sql_fetchrow($result)) { $lang_row[] = $row; } $db->sql_freeresult($result); if ($coppa === false && $config['coppa_enable']) { $now = getdate(); $coppa_birthday = $user->create_datetime() ->setDate($now['year'] - 13, $now['mon'], $now['mday'] - 1) ->setTime(0, 0, 0) ->format($user->lang['DATE_FORMAT'], true); unset($now); $template->assign_vars(array( 'S_LANG_OPTIONS' => (sizeof($lang_row) > 1) ? language_select($user_lang) : '', 'L_COPPA_NO' => sprintf($user->lang['UCP_COPPA_BEFORE'], $coppa_birthday), 'L_COPPA_YES' => sprintf($user->lang['UCP_COPPA_ON_AFTER'], $coppa_birthday), 'U_COPPA_NO' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register&amp;coppa=0'), 'U_COPPA_YES' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register&amp;coppa=1'), 'S_SHOW_COPPA' => true, 'S_HIDDEN_FIELDS' => build_hidden_fields($s_hidden_fields), 'S_UCP_ACTION' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register'), 'COOKIE_NAME' => $config['cookie_name'], 'COOKIE_PATH' => $config['cookie_path'], )); } else { $template->assign_vars(array( 'S_LANG_OPTIONS' => (sizeof($lang_row) > 1) ? language_select($user_lang) : '', 'L_TERMS_OF_USE' => sprintf($user->lang['TERMS_OF_USE_CONTENT'], $config['sitename'], generate_board_url()), 'S_SHOW_COPPA' => false, 'S_REGISTRATION' => true, 'S_HIDDEN_FIELDS' => build_hidden_fields($s_hidden_fields), 'S_UCP_ACTION' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register' . $add_coppa), 'COOKIE_NAME' => $config['cookie_name'], 'COOKIE_PATH' => $config['cookie_path'], ) ); } unset($lang_row); /** * Allows to modify the agreements. * * To assign data to the template, use $template->assign_vars() * * @event core.ucp_register_agreement * @since 3.1.6-RC1 */ $phpbb_dispatcher->dispatch('core.ucp_register_agreement'); $this->tpl_name = 'ucp_agreement'; return; } // The CAPTCHA kicks in here. We can't help that the information gets lost on language change. if ($config['enable_confirm']) { $captcha = $phpbb_container->get('captcha.factory')->get_instance($config['captcha_plugin']); $captcha->init(CONFIRM_REG); } $timezone = $config['board_timezone']; $data = array( 'username' => $request->variable('username', '', true), 'new_password' => $request->variable('new_password', '', true), 'password_confirm' => $request->variable('password_confirm', '', true), 'email' => strtolower($request->variable('email', '')), 'lang' => basename($request->variable('lang', $user->lang_name)), 'tz' => $request->variable('tz', $timezone), ); /** * Add UCP register data before they are assigned to the template or submitted * * To assign data to the template, use $template->assign_vars() * * @event core.ucp_register_data_before * @var bool submit Do we display the form only * or did the user press submit * @var array data Array with current ucp registration data * @since 3.1.4-RC1 */ $vars = array('submit', 'data'); extract($phpbb_dispatcher->trigger_event('core.ucp_register_data_before', compact($vars))); // Check and initialize some variables if needed if ($submit) { $error = validate_data($data, array( 'username' => array( array('string', false, $config['min_name_chars'], $config['max_name_chars']), array('username', '')), 'new_password' => array( array('string', false, $config['min_pass_chars'], $config['max_pass_chars']), array('password')), 'password_confirm' => array('string', false, $config['min_pass_chars'], $config['max_pass_chars']), 'email' => array( array('string', false, 6, 60), array('user_email')), 'tz' => array('timezone'), 'lang' => array('language_iso_name'), )); if (!check_form_key('ucp_register')) { $error[] = $user->lang['FORM_INVALID']; } // Replace "error" strings with their real, localised form $error = array_map(array($user, 'lang'), $error); if ($config['enable_confirm']) { $vc_response = $captcha->validate($data); if ($vc_response !== false) { $error[] = $vc_response; } if ($config['max_reg_attempts'] && $captcha->get_attempt_count() > $config['max_reg_attempts']) { $error[] = $user->lang['TOO_MANY_REGISTERS']; } } // DNSBL check if ($config['check_dnsbl']) { if (($dnsbl = $user->check_dnsbl('register')) !== false) { $error[] = sprintf($user->lang['IP_BLACKLISTED'], $user->ip, $dnsbl[1]); } } // validate custom profile fields $cp->submit_cp_field('register', $user->get_iso_lang_id(), $cp_data, $error); if (!sizeof($error)) { if ($data['new_password'] != $data['password_confirm']) { $error[] = $user->lang['NEW_PASSWORD_ERROR']; } } /** * Check UCP registration data after they are submitted * * @event core.ucp_register_data_after * @var bool submit Do we display the form only * or did the user press submit * @var array data Array with current ucp registration data * @var array cp_data Array with custom profile fields data * @var array error Array with list of errors * @since 3.1.4-RC1 */ $vars = array('submit', 'data', 'cp_data', 'error'); extract($phpbb_dispatcher->trigger_event('core.ucp_register_data_after', compact($vars))); if (!sizeof($error)) { $server_url = generate_board_url(); // Which group by default? $group_name = ($coppa) ? 'REGISTERED_COPPA' : 'REGISTERED'; $sql = 'SELECT group_id FROM ' . GROUPS_TABLE . " WHERE group_name = '" . $db->sql_escape($group_name) . "' AND group_type = " . GROUP_SPECIAL; $result = $db->sql_query($sql); $row = $db->sql_fetchrow($result); $db->sql_freeresult($result); if (!$row) { trigger_error('NO_GROUP'); } $group_id = $row['group_id']; if (($coppa || $config['require_activation'] == USER_ACTIVATION_SELF || $config['require_activation'] == USER_ACTIVATION_ADMIN) && $config['email_enable']) { $user_actkey = gen_rand_string(mt_rand(6, 10)); $user_type = USER_INACTIVE; $user_inactive_reason = INACTIVE_REGISTER; $user_inactive_time = time(); } else { $user_type = USER_NORMAL; $user_actkey = ''; $user_inactive_reason = 0; $user_inactive_time = 0; } // Instantiate passwords manager /* @var $passwords_manager \phpbb\passwords\manager */ $passwords_manager = $phpbb_container->get('passwords.manager'); $user_row = array( 'username' => $data['username'], 'user_password' => $passwords_manager->hash($data['new_password']), 'user_email' => $data['email'], 'group_id' => (int) $group_id, 'user_timezone' => $data['tz'], 'user_lang' => $data['lang'], 'user_type' => $user_type, 'user_actkey' => $user_actkey, 'user_ip' => $user->ip, 'user_regdate' => time(), 'user_inactive_reason' => $user_inactive_reason, 'user_inactive_time' => $user_inactive_time, ); if ($config['new_member_post_limit']) { $user_row['user_new'] = 1; } /** * Add into $user_row before user_add * * user_add allows adding more data into the users table * * @event core.ucp_register_user_row_after * @var bool submit Do we display the form only * or did the user press submit * @var array cp_data Array with custom profile fields data * @var array user_row Array with current ucp registration data * @since 3.1.4-RC1 */ $vars = array('submit', 'cp_data', 'user_row'); extract($phpbb_dispatcher->trigger_event('core.ucp_register_user_row_after', compact($vars))); // Register user... $user_id = user_add($user_row, $cp_data); // This should not happen, because the required variables are listed above... if ($user_id === false) { trigger_error('NO_USER', E_USER_ERROR); } // Okay, captcha, your job is done. if ($config['enable_confirm'] && isset($captcha)) { $captcha->reset(); } if ($coppa && $config['email_enable']) { $message = $user->lang['ACCOUNT_COPPA']; $email_template = 'coppa_welcome_inactive'; } else if ($config['require_activation'] == USER_ACTIVATION_SELF && $config['email_enable']) { $message = $user->lang['ACCOUNT_INACTIVE']; $email_template = 'user_welcome_inactive'; } else if ($config['require_activation'] == USER_ACTIVATION_ADMIN && $config['email_enable']) { $message = $user->lang['ACCOUNT_INACTIVE_ADMIN']; $email_template = 'admin_welcome_inactive'; } else { $message = $user->lang['ACCOUNT_ADDED']; $email_template = 'user_welcome'; } if ($config['email_enable']) { include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx); $messenger = new messenger(false); $messenger->template($email_template, $data['lang']); $messenger->to($data['email'], $data['username']); $messenger->anti_abuse_headers($config, $user); $messenger->assign_vars(array( 'WELCOME_MSG' => htmlspecialchars_decode(sprintf($user->lang['WELCOME_SUBJECT'], $config['sitename'])), 'USERNAME' => htmlspecialchars_decode($data['username']), 'PASSWORD' => htmlspecialchars_decode($data['new_password']), 'U_ACTIVATE' => "$server_url/ucp.$phpEx?mode=activate&u=$user_id&k=$user_actkey") ); if ($coppa) { $messenger->assign_vars(array( 'FAX_INFO' => $config['coppa_fax'], 'MAIL_INFO' => $config['coppa_mail'], 'EMAIL_ADDRESS' => $data['email']) ); } $messenger->send(NOTIFY_EMAIL); } if ($config['require_activation'] == USER_ACTIVATION_ADMIN) { /* @var $phpbb_notifications \phpbb\notification\manager */ $phpbb_notifications = $phpbb_container->get('notification_manager'); $phpbb_notifications->add_notifications('notification.type.admin_activate_user', array( 'user_id' => $user_id, 'user_actkey' => $user_row['user_actkey'], 'user_regdate' => $user_row['user_regdate'], )); } // Perform account linking if necessary if (!empty($login_link_data)) { $login_link_data['user_id'] = $user_id; $result = $auth_provider->link_account($login_link_data); if ($result) { $message = $message . '<br /><br />' . $user->lang[$result]; } } $message = $message . '<br /><br />' . sprintf($user->lang['RETURN_INDEX'], '<a href="' . append_sid("{$phpbb_root_path}index.$phpEx") . '">', '</a>'); trigger_error($message); } } $s_hidden_fields = array_merge($s_hidden_fields, array( 'agreed' => 'true', 'change_lang' => 0, )); if ($config['coppa_enable']) { $s_hidden_fields['coppa'] = $coppa; } if ($config['enable_confirm']) { $s_hidden_fields = array_merge($s_hidden_fields, $captcha->get_hidden_fields()); } $s_hidden_fields = build_hidden_fields($s_hidden_fields); // Visual Confirmation - Show images if ($config['enable_confirm']) { $template->assign_vars(array( 'CAPTCHA_TEMPLATE' => $captcha->get_template(), )); } // $l_reg_cond = ''; switch ($config['require_activation']) { case USER_ACTIVATION_SELF: $l_reg_cond = $user->lang['UCP_EMAIL_ACTIVATE']; break; case USER_ACTIVATION_ADMIN: $l_reg_cond = $user->lang['UCP_ADMIN_ACTIVATE']; break; } // Assign template vars for timezone select phpbb_timezone_select($template, $user, $data['tz'], true); $template->assign_vars(array( 'ERROR' => (sizeof($error)) ? implode('<br />', $error) : '', 'USERNAME' => $data['username'], 'PASSWORD' => $data['new_password'], 'PASSWORD_CONFIRM' => $data['password_confirm'], 'EMAIL' => $data['email'], 'L_REG_COND' => $l_reg_cond, 'L_USERNAME_EXPLAIN' => $user->lang($config['allow_name_chars'] . '_EXPLAIN', $user->lang('CHARACTERS', (int) $config['min_name_chars']), $user->lang('CHARACTERS', (int) $config['max_name_chars'])), 'L_PASSWORD_EXPLAIN' => $user->lang($config['pass_complex'] . '_EXPLAIN', $user->lang('CHARACTERS', (int) $config['min_pass_chars']), $user->lang('CHARACTERS', (int) $config['max_pass_chars'])), 'S_LANG_OPTIONS' => language_select($data['lang']), 'S_TZ_PRESELECT' => !$submit, 'S_CONFIRM_REFRESH' => ($config['enable_confirm'] && $config['confirm_refresh']) ? true : false, 'S_REGISTRATION' => true, 'S_COPPA' => $coppa, 'S_HIDDEN_FIELDS' => $s_hidden_fields, 'S_UCP_ACTION' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register'), 'COOKIE_NAME' => $config['cookie_name'], 'COOKIE_PATH' => $config['cookie_path'], )); // $user->profile_fields = array(); // Generate profile fields -> Template Block Variable profile_fields $cp->generate_profile_fields('register', $user->get_iso_lang_id()); // $this->tpl_name = 'ucp_register'; $this->page_title = 'UCP_REGISTRATION'; } /** * Creates the login_link data array * * @return array Returns an array of all POST paramaters whose names * begin with 'login_link_' */ protected function get_login_link_data_array() { global $request; $var_names = $request->variable_names(\phpbb\request\request_interface::POST); $login_link_data = array(); $string_start_length = strlen('login_link_'); foreach ($var_names as $var_name) { if (strpos($var_name, 'login_link_') === 0) { $key_name = substr($var_name, $string_start_length); $login_link_data[$key_name] = $request->variable($var_name, '', false, \phpbb\request\request_interface::POST); } } return $login_link_data; } /** * Prepends they key names of an associative array with 'login_link_' for * inclusion on the page as hidden fields. * * @param array $data The array to be modified * @return array The modified array */ protected function get_login_link_data_for_hidden_fields($data) { $new_data = array(); foreach ($data as $key => $value) { $new_data['login_link_' . $key] = $value; } return $new_data; } }
agpl-3.0
rubyu/anki
tests/test_sync.py
10536
# coding: utf-8 import nose, os, shutil, time from anki import Collection as aopen, Collection from anki.utils import intTime from anki.sync import Syncer, LocalServer from tests.shared import getEmptyDeck, getEmptyDeckWith # Local tests ########################################################################## deck1=None deck2=None client=None server=None server2=None def setup_basic(): global deck1, deck2, client, server deck1 = getEmptyDeck() # add a note to deck 1 f = deck1.newNote() f['Front'] = u"foo"; f['Back'] = u"bar"; f.tags = [u"foo"] deck1.addNote(f) # answer it deck1.reset(); deck1.sched.answerCard(deck1.sched.getCard(), 4) # repeat for deck2 deck2 = getEmptyDeckWith(server=True) f = deck2.newNote() f['Front'] = u"bar"; f['Back'] = u"bar"; f.tags = [u"bar"] deck2.addNote(f) deck2.reset(); deck2.sched.answerCard(deck2.sched.getCard(), 4) # start with same schema and sync time deck1.scm = deck2.scm = 0 # and same mod time, so sync does nothing t = intTime(1000) deck1.save(mod=t); deck2.save(mod=t) server = LocalServer(deck2) client = Syncer(deck1, server) def setup_modified(): setup_basic() # mark deck1 as changed time.sleep(0.1) deck1.setMod() deck1.save() @nose.with_setup(setup_basic) def test_nochange(): assert client.sync() == "noChanges" @nose.with_setup(setup_modified) def test_changedSchema(): deck1.scm += 1 deck1.setMod() assert client.sync() == "fullSync" @nose.with_setup(setup_modified) def test_sync(): def check(num): for d in deck1, deck2: for t in ("revlog", "notes", "cards"): assert d.db.scalar("select count() from %s" % t) == num assert len(d.models.all()) == num*4 # the default deck and config have an id of 1, so always 1 assert len(d.decks.all()) == 1 assert len(d.decks.dconf) == 1 assert len(d.tags.all()) == num check(1) origUsn = deck1.usn() assert client.sync() == "success" # last sync times and mod times should agree assert deck1.mod == deck2.mod assert deck1._usn == deck2._usn assert deck1.mod == deck1.ls assert deck1._usn != origUsn # because everything was created separately it will be merged in. in # actual use, we use a full sync to ensure a common starting point. check(2) # repeating it does nothing assert client.sync() == "noChanges" # if we bump mod time, the decks will sync but should remain the same. deck1.setMod() deck1.save() assert client.sync() == "success" check(2) # crt should be synced deck1.crt = 123 deck1.setMod() assert client.sync() == "success" assert deck1.crt == deck2.crt @nose.with_setup(setup_modified) def test_models(): test_sync() # update model one cm = deck1.models.current() cm['name'] = "new" time.sleep(1) deck1.models.save(cm) deck1.save() assert deck2.models.get(cm['id'])['name'].startswith("Basic") assert client.sync() == "success" assert deck2.models.get(cm['id'])['name'] == "new" # deleting triggers a full sync deck1.scm = deck2.scm = 0 deck1.models.rem(cm) deck1.save() assert client.sync() == "fullSync" @nose.with_setup(setup_modified) def test_notes(): test_sync() # modifications should be synced nid = deck1.db.scalar("select id from notes") note = deck1.getNote(nid) assert note['Front'] != "abc" note['Front'] = "abc" note.flush() deck1.save() assert client.sync() == "success" assert deck2.getNote(nid)['Front'] == "abc" # deletions too assert deck1.db.scalar("select 1 from notes where id = ?", nid) deck1.remNotes([nid]) deck1.save() assert client.sync() == "success" assert not deck1.db.scalar("select 1 from notes where id = ?", nid) assert not deck2.db.scalar("select 1 from notes where id = ?", nid) @nose.with_setup(setup_modified) def test_cards(): test_sync() nid = deck1.db.scalar("select id from notes") note = deck1.getNote(nid) card = note.cards()[0] # answer the card locally card.startTimer() deck1.sched.answerCard(card, 4) assert card.reps == 2 deck1.save() assert deck2.getCard(card.id).reps == 1 assert client.sync() == "success" assert deck2.getCard(card.id).reps == 2 # if it's modified on both sides , later mod time should win for test in ((deck1, deck2), (deck2, deck1)): time.sleep(1) c = test[0].getCard(card.id) c.reps = 5; c.flush() test[0].save() time.sleep(1) c = test[1].getCard(card.id) c.reps = 3; c.flush() test[1].save() assert client.sync() == "success" assert test[1].getCard(card.id).reps == 3 assert test[0].getCard(card.id).reps == 3 # removals should work too deck1.remCards([card.id]) deck1.save() assert deck2.db.scalar("select 1 from cards where id = ?", card.id) assert client.sync() == "success" assert not deck2.db.scalar("select 1 from cards where id = ?", card.id) @nose.with_setup(setup_modified) def test_tags(): test_sync() assert deck1.tags.all() == deck2.tags.all() deck1.tags.register(["abc"]) deck2.tags.register(["xyz"]) assert deck1.tags.all() != deck2.tags.all() deck1.save() time.sleep(0.1) deck2.save() assert client.sync() == "success" assert deck1.tags.all() == deck2.tags.all() @nose.with_setup(setup_modified) def test_decks(): test_sync() assert len(deck1.decks.all()) == 1 assert len(deck1.decks.all()) == len(deck2.decks.all()) deck1.decks.id("new") assert len(deck1.decks.all()) != len(deck2.decks.all()) time.sleep(0.1) deck2.decks.id("new2") deck1.save() time.sleep(0.1) deck2.save() assert client.sync() == "success" assert deck1.tags.all() == deck2.tags.all() assert len(deck1.decks.all()) == len(deck2.decks.all()) assert len(deck1.decks.all()) == 3 assert deck1.decks.confForDid(1)['maxTaken'] == 60 deck2.decks.confForDid(1)['maxTaken'] = 30 deck2.decks.save(deck2.decks.confForDid(1)) deck2.save() assert client.sync() == "success" assert deck1.decks.confForDid(1)['maxTaken'] == 30 @nose.with_setup(setup_modified) def test_conf(): test_sync() assert deck2.conf['curDeck'] == 1 deck1.conf['curDeck'] = 2 time.sleep(0.1) deck1.setMod() deck1.save() assert client.sync() == "success" assert deck2.conf['curDeck'] == 2 @nose.with_setup(setup_modified) def test_threeway(): test_sync() deck1.close(save=False) d3path = deck1.path.replace(".anki", "2.anki") shutil.copy2(deck1.path, d3path) deck1.reopen() deck3 = aopen(d3path) client2 = Syncer(deck3, server) assert client2.sync() == "noChanges" # client 1 adds a card at time 1 time.sleep(1) f = deck1.newNote() f['Front'] = u"1"; deck1.addNote(f) deck1.save() # at time 2, client 2 syncs to server time.sleep(1) deck3.setMod() deck3.save() assert client2.sync() == "success" # at time 3, client 1 syncs, adding the older note time.sleep(1) assert client.sync() == "success" assert deck1.noteCount() == deck2.noteCount() # syncing client2 should pick it up assert client2.sync() == "success" assert deck1.noteCount() == deck2.noteCount() == deck3.noteCount() def test_threeway2(): # for this test we want ms precision of notes so we don't have to # sleep a lot import anki.notes intTime = anki.notes.intTime anki.notes.intTime = lambda x=1: intTime(1000) def setup(): # create collection 1 with a single note c1 = getEmptyDeck() f = c1.newNote() f['Front'] = u"startingpoint" nid = f.id c1.addNote(f) cid = f.cards()[0].id c1.beforeUpload() # start both clients and server off in this state s1path = c1.path.replace(".anki2", "-s1.anki2") c2path = c1.path.replace(".anki2", "-c2.anki2") shutil.copy2(c1.path, s1path) shutil.copy2(c1.path, c2path) # open them c1 = Collection(c1.path) c2 = Collection(c2path) s1 = Collection(s1path, server=True) return c1, c2, s1, nid, cid c1, c2, s1, nid, cid = setup() # modify c1 then sync c1->s1 n = c1.getNote(nid) t = "firstmod" n['Front'] = t n.flush() c1.db.execute("update cards set mod=1, usn=-1") srv = LocalServer(s1) clnt1 = Syncer(c1, srv) clnt1.sync() n.load() assert n['Front'] == t assert s1.getNote(nid)['Front'] == t assert s1.db.scalar("select mod from cards") == 1 # sync s1->c2 clnt2 = Syncer(c2, srv) clnt2.sync() assert c2.getNote(nid)['Front'] == t assert c2.db.scalar("select mod from cards") == 1 # modify c1 and sync time.sleep(0.001) t = "secondmod" n = c1.getNote(nid) n['Front'] = t n.flush() c1.db.execute("update cards set mod=2, usn=-1") clnt1.sync() # modify c2 and sync - both c2 and server should be the same time.sleep(0.001) t2 = "thirdmod" n = c2.getNote(nid) n['Front'] = t2 n.flush() c2.db.execute("update cards set mod=3, usn=-1") clnt2.sync() n.load() assert n['Front'] == t2 assert c2.db.scalar("select mod from cards") == 3 n = s1.getNote(nid) assert n['Front'] == t2 assert s1.db.scalar("select mod from cards") == 3 # and syncing c1 again should yield the updated note as well clnt1.sync() n = s1.getNote(nid) assert n['Front'] == t2 assert s1.db.scalar("select mod from cards") == 3 n = c1.getNote(nid) assert n['Front'] == t2 assert c1.db.scalar("select mod from cards") == 3 def _test_speed(): t = time.time() deck1 = aopen(os.path.expanduser("~/rapid.anki")) for tbl in "revlog", "cards", "notes", "graves": deck1.db.execute("update %s set usn = -1 where usn != -1"%tbl) for m in deck1.models.all(): m['usn'] = -1 for tx in deck1.tags.all(): deck1.tags.tags[tx] = -1 deck1._usn = -1 deck1.save() deck2 = getEmptyDeckWith(server=True) deck1.scm = deck2.scm = 0 server = LocalServer(deck2) client = Syncer(deck1, server) print "load %d" % ((time.time() - t)*1000); t = time.time() assert client.sync() == "success" print "sync %d" % ((time.time() - t)*1000); t = time.time()
agpl-3.0
andreas-p/nextcloud-server
apps/encryption/l10n/es_AR.js
8737
OC.L10N.register( "encryption", { "Missing recovery key password" : "Contraseña de llave de recuperacion faltante", "Please repeat the recovery key password" : "Favor de reingresar la contraseña de recuperación", "Repeated recovery key password does not match the provided recovery key password" : "Las contraseñas de la llave de recuperación no coinciden", "Recovery key successfully enabled" : "Llave de recuperación habilitada exitosamente", "Could not enable recovery key. Please check your recovery key password!" : "No fue posible habilitar la llave de recuperación. ¡Favor de comprobar la contraseña de su llave de recuperación!", "Recovery key successfully disabled" : "Llave de recuperación deshabilitada exitosamente", "Could not disable recovery key. Please check your recovery key password!" : "No fue posible deshabilitar la llave de recuperación. ¡Favor de comprobar la contraseña de la llave de recuperación!", "Missing parameters" : "Parámetros faltantes", "Please provide the old recovery password" : "Favor de proporcionar su contraseña de recuperación anterior", "Please provide a new recovery password" : "Favor de proporcionar una nueva contraseña de recuperación", "Please repeat the new recovery password" : "Favor de reingresar la nueva contraseña de recuperación", "Password successfully changed." : "La contraseña ha sido cambiada exitosamente", "Could not change the password. Maybe the old password was not correct." : "No fue posible cambiar la contraseña. Favor de verificar que contraseña anterior sea correcta.", "Recovery Key disabled" : "Llave de recuperación deshabilitada", "Recovery Key enabled" : "Llave de recuperación habilitada", "Could not enable the recovery key, please try again or contact your administrator" : "No fue posible habilitar la llave de recuperación, favor de intentarlo de nuevo o contacte a su administrador", "Could not update the private key password." : "No fue posible actualizar la contraseña de la llave privada.", "The old password was not correct, please try again." : "La contraseña anterior no es correcta, favor de intentar de nuevo. ", "The current log-in password was not correct, please try again." : "La contraseña actual para iniciar sesión fue incorrecta, favor de volverlo a intentar. ", "Private key password successfully updated." : "Contraseña de llave privada actualizada exitosamente.", "Invalid private key for encryption app. Please update your private key password in your personal settings to recover access to your encrypted files." : "La llave de encriptación privada es inválida para la aplicación de encriptación. Favor de actualizar la contraseña de su llave privada en sus configuraciones personales para recuperar el acceso a sus archivos encriptados. ", "Encryption App is enabled, but your keys are not initialized. Please log-out and log-in again." : "La aplicación de encripción está habilitada, pero sus llaves no han sido inicializadas. Favor de cerrar sesión e iniciar sesión de nuevo. ", "Encryption app is enabled and ready" : "La aplicación de encripción se cuentra habilitada y lista", "Bad Signature" : "Firma equivocada", "Missing Signature" : "Firma faltante", "one-time password for server-side-encryption" : "Contraseña de una-sola-vez para la encripción del lado del servidor", "Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you." : "No es posible decriptar este archivo, posiblemente sea un archivo compartido. Favor de solicitar al dueño del archivo que lo vuelva a compartir con usted.", "Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you." : "No es posible leer este archivo, posiblemente sea un archivo compatido. Favor de solicitar al dueño que vuelva a compartirlo con usted. ", "Default encryption module" : "Módulo de encripción predeterminado", "Hey there,\n\nthe admin enabled server-side-encryption. Your files were encrypted using the password '%s'.\n\nPlease login to the web interface, go to the section 'basic encryption module' of your personal settings and update your encryption password by entering this password into the 'old log-in password' field and your current login-password.\n\n" : "Hola,\n\nel administrador ha habilitado la encripción de lado del servidor. Sus archivos fueron encriptados usando la contraseña '%s'\n\nFavor de iniciar sesión en la interface web, vaya a la sección \"módulo de encripción básica\" de sus configuraciones personales y actualice su contraseña de encripción ingresando esta contraseña en el campo 'contraseña de inicio de sesión anterior' y su contraseña de inicio de sesión actual. \n", "The share will expire on %s." : "El elemento compartido expirará el %s.", "Cheers!" : "¡Saludos!", "Hey there,<br><br>the admin enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.<br><br>Please login to the web interface, go to the section \"basic encryption module\" of your personal settings and update your encryption password by entering this password into the \"old log-in password\" field and your current login-password.<br><br>" : "Hola, <br><br>el administrador ha habilitado la encripción del lado del servidor. Sus archivos fueron encriptados usando la contraseña <strong>%s</strong>.<br><br> Favor de iniciar sesisón en la interface web, vaya a la sección \"módulo de encripción básica\" de sus configuraciones personales y actualice su contraseña de encripción ingresando esta contraseña en el campo \"contraseña de inicio de sesión anterior\" y su contraseña de inicio de sesión actual. <br><br>", "Encryption app is enabled but your keys are not initialized, please log-out and log-in again" : "La aplicación de encripción esta habilitada pero sus llaves no han sido inicializadas, favor de salir y volver a entrar a la sesion", "Encrypt the home storage" : "Encriptar el almacenamiento de inicio", "Enabling this option encrypts all files stored on the main storage, otherwise only files on external storage will be encrypted" : "Habilitar esta opción encripta todos los archivos almacenados en el almacenamiento principal, de otro modo, sólo los archivos en el almacenamiento externo serán encriptados", "Enable recovery key" : "Habilitar llave de recuperación", "Disable recovery key" : "Deshabilitar llave de recuperación", "The recovery key is an extra encryption key that is used to encrypt files. It allows recovery of a user's files if the user forgets his or her password." : "La llave de recuperación es una llave de encripción que se usa para encriptar archivos. Permite la recuperación de los archivos del usuario si este olvida su contraseña. ", "Recovery key password" : "Contraseña de llave de recuperación", "Repeat recovery key password" : "Repetir la contraseña de la llave de recuperación", "Change recovery key password:" : "Cambiar la contraseña de la llave de recuperación:", "Old recovery key password" : "Anterior contraseña de llave de recuperación", "New recovery key password" : "Nueva contraseña de llave de recuperación", "Repeat new recovery key password" : "Reingresar la nueva contraseña de llave de recuperación", "Change Password" : "Cambiar contraseña", "Basic encryption module" : "Módulo de encripción básica", "Your private key password no longer matches your log-in password." : "Su contraseña de llave privada ya no corresónde con su contraseña de inicio de sesión. ", "Set your old private key password to your current log-in password:" : "Establezca su contraseña de llave privada a su contraseña actual de inicio de seisón:", " If you don't remember your old password you can ask your administrator to recover your files." : "Si no recuerda su contraseña anterior le puede pedir a su administrador que recupere sus archivos.", "Old log-in password" : "Contraseña anterior", "Current log-in password" : "Contraseña actual", "Update Private Key Password" : "Actualizar Contraseña de Llave Privada", "Enable password recovery:" : "Habilitar la recuperación de contraseña:", "Enabling this option will allow you to reobtain access to your encrypted files in case of password loss" : "Habilitar esta opción le permitirá volver a tener acceso a sus archivos encriptados en caso de perder la contraseña", "Enabled" : "Habilitado", "Disabled" : "Deshabilitado" }, "nplurals=2; plural=(n != 1);");
agpl-3.0
Dahlgren/PHP-Fusion
infusions/downloads/downloads_admin.php
10363
<?php /*-------------------------------------------------------+ | PHP-Fusion Content Management System | Copyright (C) PHP-Fusion Inc | https://www.php-fusion.co.uk/ +--------------------------------------------------------+ | Filename: downloads.php | Author: PHP-Fusion Development Team | Co-Author: PHP-Fusion Development Team +--------------------------------------------------------+ | This program is released as free software under the | Affero GPL license. You can redistribute it and/or | modify it under the terms of this license which you | can read by viewing the included agpl.txt or online | at www.gnu.org/licenses/agpl.html. Removal of this | copyright header is strictly prohibited without | written permission from the original author(s). +--------------------------------------------------------*/ require_once "../../maincore.php"; pageAccess('D'); require_once THEMES."templates/admin_header.php"; $downloads_locale = (file_exists(DOWNLOADS."locale/".LOCALESET."downloads_admin.php")) ? DOWNLOADS."locale/".LOCALESET."downloads_admin.php" : DOWNLOADS."locale/English/downloads_admin.php"; $settings_locale = file_exists(LOCALE.LOCALESET."admin/settings.php") ? LOCALE.LOCALESET."admin/settings.php" : LOCALE."English/admin/settings.php"; $locale = fusion_get_locale('', [$downloads_locale, $settings_locale]); require_once INCLUDES."infusions_include.php"; $dl_settings = get_settings("downloads"); \PHPFusion\BreadCrumbs::getInstance()->addBreadCrumb(['link' => INFUSIONS.'downloads/downloads_admin.php'.$aidlink, 'title' => $locale['download_0001']]); add_to_title($locale['download_0001']); $allowed_section = array("downloads", "download_form", "download_settings", "download_category", "submissions"); $_GET['section'] = isset($_GET['section']) && in_array($_GET['section'], $allowed_section) ? $_GET['section'] : 'downloads'; $_GET['download_cat_id'] = isset($_GET['download_cat_id']) && isnum($_GET['download_cat_id']) ? $_GET['download_cat_id'] : 0; $edit = (isset($_GET['action']) && $_GET['action'] == 'edit') && isset($_GET['download_id']) ? TRUE : FALSE; $catEdit = isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['cat_id']) ? TRUE : FALSE; // master template $master_tab_title['title'][] = $locale['download_0000']; $master_tab_title['id'][] = "downloads"; $master_tab_title['icon'][] = "fa fa-cloud-download"; $master_tab_title['title'][] = $edit ? $locale['download_0003'] : $locale['download_0002']; $master_tab_title['id'][] = "download_form"; $master_tab_title['icon'][] = $edit ? "fa fa-pencil" : "fa fa-plus"; $master_tab_title['title'][] = $catEdit ? $locale['download_0021'] : $locale['download_0022']; $master_tab_title['id'][] = "download_category"; $master_tab_title['icon'][] = $catEdit ? "fa fa-pencil" : "fa fa-folder"; $master_tab_title['title'][] = $locale['download_0049']."&nbsp;<span class='badge'>".dbcount("(submit_id)", DB_SUBMISSIONS, "submit_type='d'")."</span>"; $master_tab_title['id'][] = "submissions"; $master_tab_title['icon'][] = "fa fa-inbox"; $master_tab_title['title'][] = $locale['download_0006']; $master_tab_title['id'][] = "download_settings"; $master_tab_title['icon'][] = "fa fa-cogs"; opentable($locale['download_0001']); echo opentab($master_tab_title, $_GET['section'], "download_admin", TRUE); switch ($_GET['section']) { case "download_form": \PHPFusion\BreadCrumbs::getInstance()->addBreadCrumb(['link' => FUSION_REQUEST, 'title' => $master_tab_title['title'][1]]); if (dbcount("('download_cat_id')", DB_DOWNLOAD_CATS, "")) { include "admin/downloads.php"; } else { echo "<div class='well text-center'>\n"; echo $locale['download_0251']."<br />\n".$locale['download_0252']."<br />\n"; echo "<a href='".INFUSIONS."downloads/downloads_admin.php".$aidlink."&amp;section=download_category'>".$locale['download_0253']."</a>".$locale['download_0254']; echo "</div>\n"; } break; case "download_category": \PHPFusion\BreadCrumbs::getInstance()->addBreadCrumb(['link' => FUSION_REQUEST, 'title' => $master_tab_title['title'][2]]); include "admin/download_cats.php"; break; case "download_settings": \PHPFusion\BreadCrumbs::getInstance()->addBreadCrumb(['link' => FUSION_REQUEST, 'title' => $master_tab_title['title'][4]]); include "admin/download_settings.php"; break; case "submissions": \PHPFusion\BreadCrumbs::getInstance()->addBreadCrumb(["link" => FUSION_REQUEST, "title" => $locale['download_0049']]); include "admin/download_submissions.php"; break; default: download_listing(); break; } echo closetab(); closetable(); require_once THEMES."templates/footer.php"; /* Download Listing */ function download_listing() { global $aidlink, $locale; $limit = 15; $total_rows = dbcount("(download_id)", DB_DOWNLOADS, ""); $rowstart = isset($_GET['rowstart']) && ($_GET['rowstart'] <= $total_rows) ? $_GET['rowstart'] : 0; // add a filter browser $catOpts['all'] = $locale['download_0004']; $categories = dbquery("select download_cat_id, download_cat_name from ".DB_DOWNLOAD_CATS." ".(multilang_table("DL") ? "WHERE download_cat_language='".LANGUAGE."'" : "").""); if (dbrows($categories) > 0) { while ($cat_data = dbarray($categories)) { $catOpts[$cat_data['download_cat_id']] = $cat_data['download_cat_name']; } } // prevent xss $catFilter = ""; if (isset($_GET['filter_cid']) && isnum($_GET['filter_cid']) && isset($catOpts[$_GET['filter_cid']])) { if ($_GET['filter_cid'] > 0) { $catFilter = "download_cat='".intval($_GET['filter_cid'])."'"; } } $langFilter = multilang_table("DL") ? "download_cat_language='".LANGUAGE."'" : ""; if ($catFilter && $langFilter) { $filter = $catFilter." AND ".$langFilter; } else { $filter = $catFilter.$langFilter; } $list_query = "SELECT d.*, dc.download_cat_id, dc.download_cat_name FROM ".DB_DOWNLOADS." d INNER JOIN ".DB_DOWNLOAD_CATS." dc on d.download_cat = dc.download_cat_id ".($filter ? "WHERE $filter " : "")." ORDER BY dc.download_cat_sorting LIMIT $rowstart, $limit"; $result = dbquery($list_query); $rows = dbrows($result); echo "<div class='clearfix'>\n"; echo "<span class='pull-right m-t-10'>".sprintf($locale['download_0005'], $rows, $total_rows)."</span>\n"; if (!empty($catOpts) > 0 && $total_rows > 0) { echo "<div class='dropdown'>\n"; echo "<a class='btn btn-default dropdown-toggle ' style='width: 200px;' data-toggle='dropdown'>\n"; if (isset($_GET['filter_cid']) && isset($catOpts[$_GET['filter_cid']])) { echo $catOpts[$_GET['filter_cid']]; } else { echo $locale['download_0011']; } echo " <span class='caret'></span></a>\n"; echo "<ul class='dropdown-menu' style='max-height:180px; width:200px; overflow-y: auto'>\n"; foreach ($catOpts as $catID => $catName) { $active = isset($_GET['filter_cid']) && $_GET['filter_cid'] == $catID ? TRUE : FALSE; echo "<li".($active ? " class='active'" : "").">\n<a class='text-smaller' href='".clean_request("filter_cid=".$catID, array("section", "rowstart", "aid"), TRUE)."'>\n"; echo $catName; echo "</a>\n</li>\n"; } echo "</ul>\n"; echo "</div>\n"; } if ($total_rows > $rows) { echo makepagenav($rowstart, $limit, $total_rows, $limit, clean_request("", array("aid", "section"), TRUE)."&amp;"); } echo "</div>\n"; echo "<ul class='list-group spacer-xs block'>\n"; if ($rows > 0) { while ($data2 = dbarray($result)) { $download_url = ''; if (!empty($data2['download_file']) && file_exists(DOWNLOADS."files/".$data2['download_file'])) { $download_url = INFUSIONS."downloads/downloads.php?file_id=".$data2['download_id']; } elseif (!strstr($data2['download_url'], "http://") && !strstr($data2['download_url'], "../")) { $download_url = $data2['download_url']; } echo "<li class='list-group-item'>\n"; echo "<div class='pull-right'>\n".$locale['download_0207']." <a style='width:auto;' href='".FUSION_SELF.$aidlink."&amp;section=download_category&amp;action=edit&amp;cat_id=".$data2['download_cat_id']."' class='badge'> ".$data2['download_cat_name']."</a> </div>\n"; echo "<div class='pull-left m-r-10'>\n"; echo thumbnail(DOWNLOADS."images/".$data2['download_image_thumb'], '50px'); echo "</div>\n"; echo "<div class='overflow-hide'>\n"; echo "<span class='strong text-dark'>".$data2['download_title']."</span><br/>\n"; $dlText = strip_tags(parse_textarea($data2['download_description_short'])); echo fusion_first_words($dlText, '50'); echo "<div class='m-t-5'>\n"; echo "<a class='m-r-10' target='_blank' href='$download_url'>".$locale['download_0226']."</a>\n"; echo "<a class='m-r-10' href='".FUSION_SELF.$aidlink."&amp;action=edit&amp;section=download_form&amp;download_id=".$data2['download_id']."'>".$locale['edit']."</a>\n"; echo "<a class='m-r-10' href='".FUSION_SELF.$aidlink."&amp;action=delete&amp;section=download_form&amp;download_id=".$data2['download_id']."' onclick=\"return confirm('".$locale['download_0255']."');\">".$locale['delete']."</a>\n"; echo "</div>\n"; echo "</div>\n"; echo "</li>\n"; } } else { echo "<li class='panel-body text-center'>\n"; echo $locale['download_0250']; echo "</li>\n"; } echo "</ul>\n"; } function calculate_byte($download_max_b) { $calc_opts = array(1 => 'Bytes (bytes)', 1000 => 'KB (Kilobytes)', 1000000 => 'MB (Megabytes)'); foreach ($calc_opts as $byte => $val) { if ($download_max_b / $byte <= 999) { return $byte; } } return 1000000; }
agpl-3.0
RysavyD/platby
controllers/organizator.py
13965
# coding: utf8 from mz_wkasa_platby import sa_ss, Uc_sa, vs2id @auth.requires_login() def pokladna(): adm = auth.has_membership('vedeni') if adm and request.args(0)=='vse': query = db.pohyb.idorganizator!=None else: organizator = adm and vs2id(db, request.args(0) ) or auth.user_id # lze zadat parametrem query = db.pohyb.idorganizator==organizator zapisy = db(query).select( db.pohyb.ALL, db.auth_user.nick, left=db.auth_user.on(db.auth_user.id==db.pohyb.idauth_user), orderby=~db.pohyb.datum) mam = 0 for zapis in zapisy: if zapis.pohyb.iddal == Uc_sa.org: # organizátor vydal mam -= zapis.pohyb.castka else: # organizátor získal mam += zapis.pohyb.castka return dict(zapisy=zapisy, mam=mam, adm=adm, pokladnik=auth.has_membership('pokladna'), arg=request.args(0) or '') u'''význam pohyb.ks(konst.sym.) 1.pozice peníze, 2.pozice doklad 0 není, 1 předat, 2 předáno, 3 odsouhlaseno, ? neví se, ! doklad ztracen, # neví se, ale bylo dříve označeno jako odsouhlasené kombinace pro Vyřízeno: 33, 30, 3#, 3! statusy, které zobrazí Odsouhlasit: 22, 23, 2#, 2!, 32 ''' @auth.requires_membership('vedeni') def dluhy(): zapisy = db(db.pohyb.idorganizator!=None).select( db.pohyb.castka, db.pohyb.idma_dati, db.pohyb.iddal, db.pohyb.idorganizator, db.auth_user.nick, db.auth_user.email, db.auth_user.vs, left=db.auth_user.on(db.auth_user.id==db.pohyb.idorganizator), orderby=db.pohyb.idorganizator) dluhy = {} id_last = -999 for zapis in zapisy: if id_last!=zapis.pohyb.idorganizator: id_last = zapis.pohyb.idorganizator klic = zapis.auth_user.nick or ('id %s' % zapis.pohyb.idorganizator) dluhy[klic] = [0, zapis.auth_user.email, zapis.auth_user.vs] if zapis.pohyb.iddal==Uc_sa.org: # organizátor vydal dluhy[klic][0] -= zapis.pohyb.castka else: # organizátor získal dluhy[klic][0] += zapis.pohyb.castka return dict(dluhy=dluhy) @auth.requires_login() def pokladnikovi(): organizator = auth.has_membership('vedeni' ) and vs2id(db, request.args(0)) or auth.user_id # lze zadat parametrem _skryj(2) form = SQLFORM(db.pohyb) if form.validate(): db.pohyb.insert(idorganizator=organizator, id_pokynu=TFu('do pokladny'), idma_dati=Uc_sa.pokladna, iddal=Uc_sa.org, ks='20', **dict(form.vars)) redirect(URL('pokladna')) response.view = 'organizator/novy_pohyb.html' return dict(form=form, warning=False) @auth.requires_login() def od_pokladnika(): organizator = auth.has_membership('vedeni' ) and vs2id(db, request.args(0)) or auth.user_id # lze zadat parametrem _skryj(2) form = SQLFORM(db.pohyb) if form.validate(): db.pohyb.insert(idorganizator=organizator, id_pokynu=TFu('z pokladny'), idma_dati=Uc_sa.org, iddal=Uc_sa.pokladna, ks='20', **dict(form.vars)) redirect(URL('pokladna')) response.view = 'organizator/novy_pohyb.html' return dict(form=form, warning=False) @auth.requires_login() def dar(): organizator = auth.has_membership('vedeni' ) and vs2id(db, request.args(0)) or auth.user_id # lze zadat parametrem _skryj() form = SQLFORM(db.pohyb) for idx in xrange(len(form[0])-1, -1, -1): row = form[0][idx] _na_konec(row, idx, form, 'pohyb_idauth_user__row', -2) _na_konec(row, idx, form, 'pohyb_cislo_uctu__row') _set_akce(form) if form.validate(): idpokynu = TFu('dar') iddal = Uc_sa.dary db.pohyb.insert(idorganizator=organizator, id_pokynu=idpokynu, idma_dati=Uc_sa.org, iddal=iddal, ks='10', **dict(form.vars)) _get_akce(form) redirect(URL('pokladna')) response.view = 'organizator/novy_pohyb.html' return dict(form=form, warning=False) @auth.requires_login() def strhnout(): organizator = auth.has_membership('vedeni' ) and vs2id(db, request.args(0)) or auth.user_id # lze zadat parametrem _skryj(warning=True) form = SQLFORM(db.pohyb) for idx in xrange(len(form[0])-1, -1, -1): row = form[0][idx] _na_konec(row, idx, form, 'pohyb_idauth_user__row', -2) _na_konec(row, idx, form, 'pohyb_cislo_uctu__row') _set_akce(form) if form.validate(): if form.vars.idauth_user: idpokynu = TFu('za akci (strhnout z os.zál.)') iddal = Uc_sa.oz uzivatel = db.auth_user[form.vars.idauth_user] uzivatel.update_record(zaloha=uzivatel.zaloha + form.vars.castka) else: idpokynu = TFu('za akci (kdo ???)') iddal = Uc_sa.oz_x db.pohyb.insert(idorganizator=organizator, id_pokynu=idpokynu, idma_dati=Uc_sa.org, iddal=iddal, ks='10', **dict(form.vars)) _get_akce(form) redirect(URL('pokladna')) response.view = 'organizator/novy_pohyb.html' return dict(form=form, warning=True) @auth.requires_login() def hotovka(): organizator = auth.has_membership('vedeni' ) and vs2id(db, request.args(0)) or auth.user_id # lze zadat parametrem _skryj() form = SQLFORM(db.pohyb) for idx in xrange(len(form[0])-1, -1, -1): row = form[0][idx] _na_konec(row, idx, form, 'pohyb_idauth_user__row', -2) _na_konec(row, idx, form, 'pohyb_cislo_uctu__row') _set_akce(form) if form.validate(): idpokynu = TFu('za akci (ne na os.zálohu)') iddal = Uc_sa.vynos db.pohyb.insert(idorganizator=organizator, id_pokynu=idpokynu, idma_dati=Uc_sa.org, iddal=iddal, ks='10', **dict(form.vars)) _get_akce(form) redirect(URL('pokladna')) response.view = 'organizator/novy_pohyb.html' return dict(form=form, warning=False) @auth.requires_login() def hotov_vydaj(): organizator = auth.has_membership('vedeni' ) and vs2id(db, request.args(0)) or auth.user_id # lze zadat parametrem _skryj(1) form = SQLFORM(db.pohyb) _set_akce(form) if form.validate(): db.pohyb.insert(idorganizator=organizator, id_pokynu=TFu('výdaj'), idma_dati=Uc_sa.akce, iddal=Uc_sa.org, ks='11', **dict(form.vars)) _get_akce(form) redirect(URL('pokladna')) response.view = 'organizator/novy_pohyb.html' return dict(form=form, warning=False) @auth.requires_membership('pokladna') def cokoliv(): for fld in db.pohyb: fld.readable = True fld.writable = True form = SQLFORM(db.pohyb) if form.process().accepted: if form.vars.idauth_user: redirect(URL('platby', 'pohyby', args=db.auth_user[form.vars.idauth_user].vs)) else: redirect(URL('pokladna')) response.view = 'organizator/novy_pohyb.html' return dict(form=form, warning=False) def _skryj(vic=0, warning=False): '''oba parametry řeší různé varianty skrývání/ukázání údajů - mohly by tedy být sloučeny do jednoho další nesystematické informace jsou pro request.function v šabloně ''' db.pohyb.partner_id.readable=db.pohyb.partner_id.writable=False db.pohyb.fp_id.readable=db.pohyb.fp_id.writable=False db.pohyb.idma_dati.readable=db.pohyb.idma_dati.writable=False db.pohyb.iddal.readable=db.pohyb.iddal.writable=False db.pohyb.id_pokynu.readable=db.pohyb.id_pokynu.writable=False db.pohyb.kod_banky.readable=db.pohyb.kod_banky.writable=False db.pohyb.idorganizator.readable=db.pohyb.idorganizator.writable=False db.pohyb.zakaznik.readable=db.pohyb.zakaznik.writable=False db.pohyb.ks.readable=db.pohyb.ks.writable=False db.pohyb.id_pohybu.readable=db.pohyb.id_pohybu.writable=False db.pohyb.datum.comment = TFu('skutečné datum příjmu') db.pohyb.vs.readable=db.pohyb.vs.writable=False if vic>=1: db.pohyb.popis.comment = TFu( 'cokoli, co chceš sdělit pokladníkovi, nebo co má u tohoto pohybu zůstat poznamenáno') db.pohyb.idauth_user.readable=db.pohyb.idauth_user.writable=False db.pohyb.cislo_uctu.readable=db.pohyb.cislo_uctu.writable=False db.pohyb.datum.comment = TFu('datum podle dokladu') if vic>=2: db.pohyb.ss.readable=db.pohyb.ss.writable=False db.pohyb.nazev_banky.readable=db.pohyb.nazev_banky.writable=False db.pohyb.popis.comment = TFu('místo předání, apod.') db.pohyb.datum.comment = TFu('skutečné datum předání') else: db.pohyb.popis.comment = TFu('Zapiš cokoli, co chceš vysvětlit pokladníkovi.') if warning: db.pohyb.idauth_user.comment=TFu('musí být uvedeno') db.pohyb.cislo_uctu.readable=db.pohyb.cislo_uctu.writable=False else: db.pohyb.idauth_user.comment=TFu('přednostně zde; jen v nouzi v následujícím údaji') db.pohyb.cislo_uctu.label = TFu('Nick nereg. uživatele') db.pohyb.cislo_uctu.comment = TFu('zadej, jestliže nemůžeš nalézt/vybrat uživatele v předchozím údaji; můžeš zapsat i něco jako "host" nebo "kamarádka Kajouska"') #db.pohyb.vs.label = TFu('Symbol uživatele') #db.pohyb.vs.comment = TFu('pokud ho náhodou víte, je to ideální (101+ z sa nebo 80111+ přidělené zde); když ne, nevadí') db.pohyb.castka.label = TFu('Částka') db.pohyb.castka.comment = TFu('kladné číslo') db.pohyb.ss.label = TFu('Číslo akce') db.pohyb.ss.comment = TFu('číslo akce (fu:9000+, sa:2000+) -- pokud máš doklad, poznamenej na něj tužkou toto číslo') db.pohyb.nazev_banky.label = 'Akce' db.pohyb.nazev_banky.comment = '(pokud možno..) datum a název akce' #db.pohyb.nazev_banky.requires = IS_NOT_EMPTY() db.pohyb.castka.requires = IS_DECIMAL_IN_RANGE(0.1, 999999.0) def _na_konec(row, idx, form, rowid, pozice=-1): if row.attributes['_id']==rowid: form[0].insert(pozice, row) del form[0][idx] def _set_akce(form): if session.nazev_banky: form.vars.nazev_banky = session.nazev_banky form.vars.ss = session.ss form.vars.datum = session.datum.strftime('%d.%m.%Y') def _get_akce(form): session.nazev_banky = form.vars.nazev_banky session.ss = form.vars.ss session.datum = form.vars.datum def st33(): if len(request.args)>0: db(db.pohyb.id==request.args[0]).update(ks='33') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st30(): if len(request.args)>0: db(db.pohyb.id==request.args[0]).update(ks='30') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st1_(): if len(request.args)>0: stx_(request.args[0], '1') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st2_(): if len(request.args)>0: stx_(request.args[0], '2') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st3_(): if len(request.args)>0: stx_(request.args[0], '3') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def stq_(): if len(request.args)>0: stx_(request.args[0], '?') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def stx_(pohyb_id, new): rec = db(db.pohyb.id==pohyb_id).select(db.pohyb.id, db.pohyb.ks).first() rec.update_record(ks=new+rec.ks[1]) def st_0(): if len(request.args)>0: st_x(request.args[0], '0') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st_1(): if len(request.args)>0: st_x(request.args[0], '1') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st_2(): if len(request.args)>0: st_x(request.args[0], '2') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st_3(): if len(request.args)>0: st_x(request.args[0], '3') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st_q(): if len(request.args)>0: st_x(request.args[0], '?') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st_jako_mam(): if len(request.args)>0: st_x(request.args[0], '#') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st_ztracen(): if len(request.args)>0: st_x(request.args[0], '!') redirect(URL('pokladna', args=request.args(1) if request.args(1) else ())) def st_x(pohyb_id, new): rec = db(db.pohyb.id==pohyb_id).select(db.pohyb.id, db.pohyb.ks).first() rec.update_record(ks=rec.ks[0]+new) def odstran_chybny(): if len(request.args)>0: pohyb = db.pohyb[request.args[0]] if pohyb.idauth_user: uzivatel = db.auth_user[pohyb.idauth_user] uzivatel.update_record(zaloha=uzivatel.zaloha - pohyb.castka) pohyb.delete_record() redirect(URL('pokladna', args=request.args(1) if request.args(1) else ()))
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/core/vo/beans/PatientDocumentSearchListVoBean.java
7238
//############################################################################# //# # //# 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.core.vo.beans; public class PatientDocumentSearchListVoBean extends ims.vo.ValueObjectBean { public PatientDocumentSearchListVoBean() { } public PatientDocumentSearchListVoBean(ims.core.vo.PatientDocumentSearchListVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.creationtype = vo.getCreationType() == null ? null : (ims.vo.LookupInstanceBean)vo.getCreationType().getBean(); this.category = vo.getCategory() == null ? null : (ims.vo.LookupInstanceBean)vo.getCategory().getBean(); this.specialty = vo.getSpecialty() == null ? null : (ims.vo.LookupInstanceBean)vo.getSpecialty().getBean(); this.authoringhcp = vo.getAuthoringHCP() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getAuthoringHCP().getBean(); this.documentdate = vo.getDocumentDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getDocumentDate().getBean(); this.recordingdatetime = vo.getRecordingDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getRecordingDateTime().getBean(); this.currentdocumentstatus = vo.getCurrentDocumentStatus() == null ? null : (ims.core.vo.beans.PatientDocumentStatusVoBean)vo.getCurrentDocumentStatus().getBean(); this.responsiblehcp = vo.getResponsibleHCP() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getResponsibleHCP().getBean(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.core.vo.PatientDocumentSearchListVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.creationtype = vo.getCreationType() == null ? null : (ims.vo.LookupInstanceBean)vo.getCreationType().getBean(); this.category = vo.getCategory() == null ? null : (ims.vo.LookupInstanceBean)vo.getCategory().getBean(); this.specialty = vo.getSpecialty() == null ? null : (ims.vo.LookupInstanceBean)vo.getSpecialty().getBean(); this.authoringhcp = vo.getAuthoringHCP() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getAuthoringHCP().getBean(map); this.documentdate = vo.getDocumentDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getDocumentDate().getBean(); this.recordingdatetime = vo.getRecordingDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getRecordingDateTime().getBean(); this.currentdocumentstatus = vo.getCurrentDocumentStatus() == null ? null : (ims.core.vo.beans.PatientDocumentStatusVoBean)vo.getCurrentDocumentStatus().getBean(map); this.responsiblehcp = vo.getResponsibleHCP() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getResponsibleHCP().getBean(map); } public ims.core.vo.PatientDocumentSearchListVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.core.vo.PatientDocumentSearchListVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.core.vo.PatientDocumentSearchListVo vo = null; if(map != null) vo = (ims.core.vo.PatientDocumentSearchListVo)map.getValueObject(this); if(vo == null) { vo = new ims.core.vo.PatientDocumentSearchListVo(); 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.vo.LookupInstanceBean getCreationType() { return this.creationtype; } public void setCreationType(ims.vo.LookupInstanceBean value) { this.creationtype = value; } public ims.vo.LookupInstanceBean getCategory() { return this.category; } public void setCategory(ims.vo.LookupInstanceBean value) { this.category = value; } public ims.vo.LookupInstanceBean getSpecialty() { return this.specialty; } public void setSpecialty(ims.vo.LookupInstanceBean value) { this.specialty = value; } public ims.core.vo.beans.HcpLiteVoBean getAuthoringHCP() { return this.authoringhcp; } public void setAuthoringHCP(ims.core.vo.beans.HcpLiteVoBean value) { this.authoringhcp = value; } public ims.framework.utils.beans.DateBean getDocumentDate() { return this.documentdate; } public void setDocumentDate(ims.framework.utils.beans.DateBean value) { this.documentdate = value; } public ims.framework.utils.beans.DateTimeBean getRecordingDateTime() { return this.recordingdatetime; } public void setRecordingDateTime(ims.framework.utils.beans.DateTimeBean value) { this.recordingdatetime = value; } public ims.core.vo.beans.PatientDocumentStatusVoBean getCurrentDocumentStatus() { return this.currentdocumentstatus; } public void setCurrentDocumentStatus(ims.core.vo.beans.PatientDocumentStatusVoBean value) { this.currentdocumentstatus = value; } public ims.core.vo.beans.HcpLiteVoBean getResponsibleHCP() { return this.responsiblehcp; } public void setResponsibleHCP(ims.core.vo.beans.HcpLiteVoBean value) { this.responsiblehcp = value; } private Integer id; private int version; private ims.vo.LookupInstanceBean creationtype; private ims.vo.LookupInstanceBean category; private ims.vo.LookupInstanceBean specialty; private ims.core.vo.beans.HcpLiteVoBean authoringhcp; private ims.framework.utils.beans.DateBean documentdate; private ims.framework.utils.beans.DateTimeBean recordingdatetime; private ims.core.vo.beans.PatientDocumentStatusVoBean currentdocumentstatus; private ims.core.vo.beans.HcpLiteVoBean responsiblehcp; }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/core/vo/lookups/MaritalStatusCollection.java
4422
//############################################################################# //# # //# 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.core.vo.lookups; import ims.framework.cn.data.TreeModel; import ims.framework.cn.data.TreeNode; import ims.vo.LookupInstanceCollection; import ims.vo.LookupInstVo; public class MaritalStatusCollection extends LookupInstanceCollection implements ims.vo.ImsCloneable, TreeModel { private static final long serialVersionUID = 1L; public void add(MaritalStatus value) { super.add(value); } public int indexOf(MaritalStatus instance) { return super.indexOf(instance); } public boolean contains(MaritalStatus instance) { return indexOf(instance) >= 0; } public MaritalStatus get(int index) { return (MaritalStatus)super.getIndex(index); } public void remove(MaritalStatus instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public Object clone() { MaritalStatusCollection newCol = new MaritalStatusCollection(); MaritalStatus item; for (int i = 0; i < super.size(); i++) { item = this.get(i); newCol.add(new MaritalStatus(item.getID(), item.getText(), item.isActive(), item.getParent(), item.getImage(), item.getColor(), item.getOrder())); } for (int i = 0; i < newCol.size(); i++) { item = newCol.get(i); if (item.getParent() != null) { int parentIndex = this.indexOf(item.getParent()); if(parentIndex >= 0) item.setParent(newCol.get(parentIndex)); else item.setParent((MaritalStatus)item.getParent().clone()); } } return newCol; } public MaritalStatus getInstance(int instanceId) { return (MaritalStatus)super.getInstanceById(instanceId); } public TreeNode[] getRootNodes() { LookupInstVo[] roots = super.getRoots(); TreeNode[] nodes = new TreeNode[roots.length]; System.arraycopy(roots, 0, nodes, 0, roots.length); return nodes; } public MaritalStatus[] toArray() { MaritalStatus[] arr = new MaritalStatus[this.size()]; super.toArray(arr); return arr; } public static MaritalStatusCollection buildFromBeanCollection(java.util.Collection beans) { MaritalStatusCollection coll = new MaritalStatusCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while(iter.hasNext()) { coll.add(MaritalStatus.buildLookup((ims.vo.LookupInstanceBean)iter.next())); } return coll; } public static MaritalStatusCollection buildFromBeanCollection(ims.vo.LookupInstanceBean[] beans) { MaritalStatusCollection coll = new MaritalStatusCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(MaritalStatus.buildLookup(beans[x])); } return coll; } }
agpl-3.0
fanf/cf-clerk
src/main/scala/com/normation/cfclerk/domain/VariableAndSection.scala
10587
/* ************************************************************************************* * Copyright 2011 Normation SAS ************************************************************************************* * * 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. * * In accordance with the terms of section 7 (7. Additional Terms.) of * the GNU Affero GPL v3, the copyright holders add the following * Additional permissions: * Notwithstanding to the terms of section 5 (5. Conveying Modified Source * Versions) and 6 (6. Conveying Non-Source Forms.) of the GNU Affero GPL v3 * licence, when you create a Related Module, this Related Module is * not considered as a part of the work and may be distributed under the * license agreement of your choice. * A "Related Module" means a set of sources files including their * documentation that, without modification of the Source Code, enables * supplementary functions or services in addition to those offered by * the Software. * * 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/agpl.html>. * ************************************************************************************* */ package com.normation.cfclerk.domain import scala.collection._ import com.normation.cfclerk.exceptions._ import scala.xml._ import org.joda.time._ import org.joda.time.format._ import com.normation.utils.XmlUtils._ import net.liftweb.common._ import mutable.Buffer import com.normation.utils.Control.bestEffort import com.normation.utils.HashcodeCaching /* A SectionChild is either a Variable or a Section*/ sealed trait SectionChild case class Section(val spec: SectionSpec) extends SectionChild with HashcodeCaching /** * * Variable class, to describe what must be replaced in the template files * @author nicolas * */ trait Variable extends Loggable { //define in sub classes type T <: VariableSpec val spec: T override def clone = Variable.matchCopy(this) // selected values protected val defaultValues: Seq[String] // override in subclasses protected val internalValues: Buffer[String] = defaultValues.toBuffer // this is the internal representation of the data override def toString() = "%s %s : %s".format(spec.name, spec.description, internalValues) /** * ********************************* * new variable part */ def values: Seq[String] = internalValues.toSeq def values_=(x: Seq[String]) = saveValues(x) def getTypedValues(): Box[Seq[Any]] = { bestEffort(internalValues) { x => castValue(x) } } // the comments below contains implementations and should be reused in SelectVariable and SelectOne variable /** * Only deals with the first entry */ def saveValue(s: String): Unit = { spec match { case vl: ValueLabelVariableSpec => if (!(vl.valueslabels.map(x => x.value).contains(s))) throw new VariableException("Wrong value for variable " + vl.name + " : " + s) case _ => //OK } Variable.setUniqueValue(this, s) } /** * Save the whole seq as value */ def saveValues(seq: Seq[String]): Unit = { spec match { case vl: ValueLabelVariableSpec => if ((null != vl.valueslabels) && (vl.valueslabels.size > 0)) { for (item <- seq) if (!(vl.valueslabels.map(x => x.value).contains(item))) throw new VariableException("Wrong value for variable " + vl.name + " : " + item) } case _ => } Variable.setValues(this, seq) } /** * Append the seq to the values */ def appendValues(seq: Seq[String]): Unit = { spec match { case vl: ValueLabelVariableSpec => if ((null != vl.valueslabels) && (vl.valueslabels.size > 0)) { for (item <- seq) if (!(vl.valueslabels.map(x => x.value).contains(item))) throw new VariableException("Wrong value for variable " + vl.name + " : " + item) } case _ => } Variable.appendValues(this, seq) } def getValuesLength() = { internalValues.size } protected def castValue(x: String) : Box[Any] = { val typeName = spec.constraint.typeName.toLowerCase //we don't want to check constraint on empty value // when the variable is optionnal if(this.spec.constraint.mayBeEmpty && x.length < 1) Full("") else if(Constraint.stringTypes.contains(typeName)) Full(x) else typeName match { case "datetime" => try Full(ISODateTimeFormat.dateTimeParser.parseDateTime(x)) catch { case e:Exception => Failure("Wrong variable value " + x + " for variable name " + spec.name + " : expecting a datetime") } case "integer" => try Full(x.toInt) catch { case e:Exception => Failure("Wrong variable value " + x + " for variable name " + spec.name + " : expecting an integer") } case "boolean" => try Full(x.toBoolean) catch { case e:Exception => Failure("Wrong variable value " + x + " for variable name " + spec.name + " : expecting a boolean") } case _ => logger.error("Wrong variable type %s for variable name %s".format(typeName, spec.name)) Failure("Wrong variable type " + typeName + " for variable name " + spec.name) } } } case class SystemVariable( override val spec: SystemVariableSpec, protected val defaultValues: Seq[String] = Seq()) extends Variable with HashcodeCaching { type T = SystemVariableSpec } case class TrackerVariable( override val spec: TrackerVariableSpec, protected val defaultValues: Seq[String] = Seq()) extends Variable with HashcodeCaching { type T = TrackerVariableSpec } trait SectionVariable extends Variable with SectionChild case class InputVariable( override val spec: InputVariableSpec, protected val defaultValues: Seq[String] = Seq()) extends SectionVariable with HashcodeCaching { type T = InputVariableSpec } case class SelectVariable( override val spec: SelectVariableSpec, protected val defaultValues: Seq[String] = Seq()) extends SectionVariable with HashcodeCaching { type T = SelectVariableSpec } case class SelectOneVariable( override val spec: SelectOneVariableSpec, protected val defaultValues: Seq[String] = Seq()) extends SectionVariable with HashcodeCaching { type T = SelectOneVariableSpec } object Variable { // define our own alternatives of matchCopy because we want v.values to be the default // values def matchCopy(v: Variable): Variable = matchCopy(v, false) def matchCopy(v: Variable, setMultivalued: Boolean): Variable = matchCopy(v, v.values, setMultivalued) def matchCopy(v: Variable, values: Seq[String], setMultivalued: Boolean = false): Variable = { val bVals = values.toBuffer v match { case iv: InputVariable => val newSpec = if (setMultivalued) iv.spec.cloneSetMultivalued else iv.spec iv.copy(defaultValues = bVals, spec = newSpec) case sv: SelectVariable => val newSpec = if (setMultivalued) sv.spec.cloneSetMultivalued else sv.spec sv.copy(defaultValues = bVals, spec = newSpec) case s1v: SelectOneVariable => val newSpec = if (setMultivalued) s1v.spec.cloneSetMultivalued else s1v.spec s1v.copy(defaultValues = bVals, spec = newSpec) case systemV: SystemVariable => val newSpec = if (setMultivalued) systemV.spec.cloneSetMultivalued else systemV.spec systemV.copy(defaultValues = bVals, spec = newSpec) case directive: TrackerVariable => val newSpec = if (setMultivalued) directive.spec.cloneSetMultivalued else directive.spec directive.copy(defaultValues = bVals, spec = newSpec) } } def variableParsing(variable: Variable, elt: Node): Unit = { variable.internalValues ++= valuesParsing((elt \ "internalValues")) } private def valuesParsing(elt: NodeSeq): Seq[String] = { val returnedValue = mutable.Buffer[String]() for (value <- elt \ "value") { returnedValue += value.text } returnedValue } /** * Set the first value */ def setUniqueValue(variable: Variable, value: String): Unit = { if (value != null) { if (!variable.spec.checked) { variable.internalValues(0) = value } else if (checkValue(variable, value)) { if (variable.internalValues.size > 0) variable.internalValues(0) = value else variable.internalValues += value } } } /** * Replace all values with the ones in argument */ def setValues(variable: Variable, values: Seq[String]): Unit = { if (values != null) { if (!variable.spec.checked) { variable.internalValues.clear variable.internalValues ++= values } else if (!variable.spec.multivalued && values.size > 1) { throw new VariableException("Wrong variable length for " + variable.spec.name) } else if (values.map(x => checkValue(variable, x)).contains(false)) { throw new VariableException("Wrong variable value for " + variable.spec.name) // this should really not be thrown } else { variable.internalValues.clear variable.internalValues ++= values } } } /** * Append values in argument to the value list */ def appendValues(variable: Variable, values: Seq[String]): Unit = { if (values != null) { if (!variable.spec.checked) { variable.internalValues ++= values } else if (!variable.spec.multivalued && (values.size + variable.internalValues.size) > 1) { throw new VariableException("Wrong variable length for " + variable.spec.name) } else if (values.map(x => checkValue(variable, x)).contains(false)) { throw new VariableException("Wrong variable value for " + variable.spec.name) // this should really not be thrown } else { variable.internalValues ++= values } } } /** * Check the value we intend to put in the variable */ def checkValue(variable: Variable, value: String): Boolean = { variable.castValue(value).isDefined } }
agpl-3.0
DerDu/SPHERE-Framework
Application/Document/Storage/Service/Setup.php
7692
<?php namespace SPHERE\Application\Document\Storage\Service; use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Table; use SPHERE\System\Database\Binding\AbstractSetup; /** * Class Setup * * @package SPHERE\Application\Document\Explorer\Storage\Service */ class Setup extends AbstractSetup { /** * @param bool $Simulate * @param bool $UTF8 * * @return string */ public function setupDatabaseSchema($Simulate = true, $UTF8 = false) { $Schema = clone $this->getConnection()->getSchema(); $tblPartition = $this->setTablePartition($Schema); $tblDirectory = $this->setTableDirectory($Schema, $tblPartition); $tblBinary = $this->setTableBinary($Schema); $tblFileCategory = $this->setTableFileCategory($Schema); $tblFileType = $this->setTableFileType($Schema, $tblFileCategory); $tblFile = $this->setTableFile($Schema, $tblDirectory, $tblBinary, $tblFileType); $tblReferenceType = $this->setTableReferenceType($Schema); $this->setTableReference($Schema, $tblFile, $tblReferenceType); /** * Migration & Protocol */ $this->getConnection()->addProtocol(__CLASS__); if(!$UTF8){ $this->getConnection()->setMigration($Schema, $Simulate); } else { $this->getConnection()->setUTF8(); } return $this->getConnection()->getProtocol($Simulate); } /** * @param Schema $Schema * * @return Table */ private function setTablePartition(Schema &$Schema) { $Table = $this->getConnection()->createTable($Schema, 'tblPartition'); if (!$this->getConnection()->hasColumn('tblPartition', 'Identifier')) { $Table->addColumn('Identifier', 'string'); } if (!$this->getConnection()->hasColumn('tblPartition', 'IsLocked')) { $Table->addColumn('IsLocked', 'boolean'); } if (!$this->getConnection()->hasColumn('tblPartition', 'Name')) { $Table->addColumn('Name', 'string'); } if (!$this->getConnection()->hasColumn('tblPartition', 'Description')) { $Table->addColumn('Description', 'string'); } return $Table; } /** * @param Schema $Schema * @param Table $tblPartition * * @return Table */ private function setTableDirectory(Schema &$Schema, Table $tblPartition) { $Table = $this->getConnection()->createTable($Schema, 'tblDirectory'); if (!$this->getConnection()->hasColumn('tblDirectory', 'Identifier')) { $Table->addColumn('Identifier', 'string'); } if (!$this->getConnection()->hasColumn('tblDirectory', 'IsLocked')) { $Table->addColumn('IsLocked', 'boolean'); } if (!$this->getConnection()->hasColumn('tblDirectory', 'Name')) { $Table->addColumn('Name', 'string'); } if (!$this->getConnection()->hasColumn('tblDirectory', 'Description')) { $Table->addColumn('Description', 'string'); } $this->getConnection()->addForeignKey($Table, $tblPartition, true); $this->getConnection()->addForeignKey($Table, $Table, true); return $Table; } /** * @param Schema $Schema * * @return Table */ private function setTableBinary(Schema &$Schema) { $Table = $this->getConnection()->createTable($Schema, 'tblBinary'); if (!$this->getConnection()->hasColumn('tblBinary', 'BinaryBlob')) { $Table->addColumn('BinaryBlob', 'blob'); } if (!$this->getConnection()->hasColumn('tblBinary', 'Hash')) { $Table->addColumn('Hash', 'string'); } return $Table; } /** * @param Schema $Schema * * @return Table */ private function setTableFileCategory(Schema &$Schema) { $Table = $this->getConnection()->createTable($Schema, 'tblFileCategory'); if (!$this->getConnection()->hasColumn('tblFileCategory', 'Identifier')) { $Table->addColumn('Identifier', 'string'); } if (!$this->getConnection()->hasColumn('tblFileCategory', 'Name')) { $Table->addColumn('Name', 'string'); } return $Table; } /** * @param Schema $Schema * @param Table $tblFileCategory * * @return Table */ private function setTableFileType(Schema &$Schema, Table $tblFileCategory) { $Table = $this->getConnection()->createTable($Schema, 'tblFileType'); if (!$this->getConnection()->hasColumn('tblFileType', 'Name')) { $Table->addColumn('Name', 'string'); } if (!$this->getConnection()->hasColumn('tblFileType', 'Extension')) { $Table->addColumn('Extension', 'string'); } if (!$this->getConnection()->hasColumn('tblFileType', 'MimeType')) { $Table->addColumn('MimeType', 'string'); } if (!$this->getConnection()->hasIndex($Table, array('Extension', 'MimeType'))) { $Table->addUniqueIndex(array('Extension', 'MimeType')); } $this->getConnection()->addForeignKey($Table, $tblFileCategory, true); return $Table; } /** * @param Schema $Schema * @param Table $tblDirectory * @param Table $tblBinary * @param Table $tblFileType * * @return Table */ private function setTableFile(Schema &$Schema, Table $tblDirectory, Table $tblBinary, Table $tblFileType) { $Table = $this->getConnection()->createTable($Schema, 'tblFile'); if (!$this->getConnection()->hasColumn('tblFile', 'IsLocked')) { $Table->addColumn('IsLocked', 'boolean'); } if (!$this->getConnection()->hasColumn('tblFile', 'Name')) { $Table->addColumn('Name', 'string'); } if (!$this->getConnection()->hasColumn('tblFile', 'Description')) { $Table->addColumn('Description', 'string'); } $this->getConnection()->addForeignKey($Table, $tblDirectory, true); $this->getConnection()->addForeignKey($Table, $tblFileType, true); $this->getConnection()->addForeignKey($Table, $tblBinary, true); return $Table; } /** * @param Schema $Schema * * @return Table */ private function setTableReferenceType(Schema &$Schema) { $Table = $this->getConnection()->createTable($Schema, 'tblReferenceType'); if (!$this->getConnection()->hasColumn('tblReferenceType', 'Identifier')) { $Table->addColumn('Identifier', 'string'); } if (!$this->getConnection()->hasColumn('tblReferenceType', 'Name')) { $Table->addColumn('Name', 'string'); } if (!$this->getConnection()->hasColumn('tblReferenceType', 'Description')) { $Table->addColumn('Description', 'string'); } return $Table; } /** * @param Schema $Schema * @param Table $tblFile * @param Table $tblReferenceType * * @return Table */ private function setTableReference(Schema &$Schema, Table $tblFile, Table $tblReferenceType) { $Table = $this->getConnection()->createTable($Schema, 'tblReference'); if (!$this->getConnection()->hasColumn('tblReference', 'foreignTblEntity')) { $Table->addColumn('foreignTblEntity', 'bigint', array('notnull' => false)); } $this->getConnection()->addForeignKey($Table, $tblFile, true); $this->getConnection()->addForeignKey($Table, $tblReferenceType, true); return $Table; } }
agpl-3.0
wheldom01/privacyidea
privacyidea/lib/tokens/registrationtoken.py
5493
# -*- coding: utf-8 -*- # # privacyIDEA # Aug 12, 2014 Cornelius Kölbel # License: AGPLv3 # contact: http://www.privacyidea.org # # 2015-01-29 Adapt during migration to flask # Cornelius Kölbel <cornelius@privacyidea.org> # # This code is free software; you can redistribute it and/or # modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE # License as published by the Free Software Foundation; either # version 3 of the License, or any later version. # # This code is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU 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/>. # """ This file contains the definition of the RegisterToken class. The code is tested in test_lib_tokens_registration.py. """ import logging from privacyidea.lib.tokens.passwordtoken import PasswordTokenClass from privacyidea.lib.log import log_with from privacyidea.lib.utils import generate_password from privacyidea.lib.decorators import check_token_locked from privacyidea.lib import _ optional = True required = False log = logging.getLogger(__name__) class RegistrationTokenClass(PasswordTokenClass): """ Token to implement a registration code. It can be used to create a registration code or a "TAN" which can be used once by a user to authenticate somewhere. After this registration code is used, the token is automatically deleted. The idea is to provide a workflow, where the user can get a registration code by e.g. postal mail and then use this code as the initial first factor to authenticate to the UI to enroll real tokens. A registration code can be created by an administrative task with the token/init api like this: **Example Authentication Request**: .. sourcecode:: http POST /token/init HTTP/1.1 Host: example.com Accept: application/json type=register user=cornelius realm=realm1 **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "detail": { "registrationcode": "12345808124095097608" }, "id": 1, "jsonrpc": "2.0", "result": { "status": true, "value": true }, "version": "privacyIDEA unknown" } """ def __init__(self, aToken): PasswordTokenClass.__init__(self, aToken) self.hKeyRequired = False self.set_type(u"registration") self.otp_len = 24 @staticmethod def get_class_type(): return "registration" @staticmethod def get_class_prefix(): return "REG" @staticmethod @log_with(log) def get_class_info(key=None, ret='all'): """ returns a subtree of the token definition :param key: subsection identifier :type key: string :param ret: default return value, if nothing is found :type ret: user defined :return: subsection if key exists or user defined :rtype: dict or scalar """ res = {'type': 'registration', 'title': 'Registration Code Token', 'description': _('Registration: A token that creates a ' 'registration code that ' 'can be used as a second factor once.'), 'init': {}, 'config': {}, 'user': [], # This tokentype is enrollable in the UI for... 'ui_enroll': ["admin"], 'policy': {}, } if key: ret = res.get(key) else: if ret == 'all': ret = res return ret def update(self, param): """ This method is called during the initialization process. :param param: parameters from the token init :type param: dict :return: None """ if "genkey" in param: # We do not need the genkey! We generate anyway. # Otherwise genkey and otpkey will raise an exception in # PasswordTokenClass del param["genkey"] param["otpkey"] = generate_password(size=self.otp_len) PasswordTokenClass.update(self, param) @log_with(log, log_entry=False) @check_token_locked def inc_count_auth_success(self): """ Increase the counter, that counts successful authentications In case of successful authentication the token does needs to be deleted. """ self.delete_token() return 1 @log_with(log) def get_init_detail(self, params=None, user=None): """ At the end of the initialization we return the registration code. """ response_detail = PasswordTokenClass.get_init_detail(self, params, user) params = params or {} secretHOtp = self.token.get_otpkey() registrationcode = secretHOtp.getKey() response_detail["registrationcode"] = registrationcode return response_detail
agpl-3.0
pdpfsug/wp_raga10
wp_raga10/wp-content/plugins/the-events-calendar/src/resources/js/tribe-events-ajax-calendar.js
14591
/** * @file This file contains all month view specific javascript. * This file should load after all vendors and core events javascript. * @version 3.0 */ (function( window, document, $, td, te, tf, ts, tt, config, dbug ) { /* * $ = jQuery * td = tribe_ev.data * te = tribe_ev.events * tf = tribe_ev.fn * ts = tribe_ev.state * tt = tribe_ev.tests * dbug = tribe_debug */ $( document ).ready( function() { var $body = $( 'body' ), $nav_link = $( '[class^="tribe-events-nav-"] a' ), initial_date = tf.get_url_param( 'tribe-bar-date' ), $wrapper = $( '#tribe-events' ), $tribedate = $( '#tribe-bar-date' ), date_mod = false; var base_url = '/'; if ( 'undefined' !== typeof config.events_base ) { base_url = $( '#tribe-events-header' ).data( 'baseurl' ); } else if ( $nav_link.length ) { base_url = $nav_link.first().attr( 'href' ).slice( 0, -8 ); } if ( td.default_permalinks ) { base_url = base_url.split("?")[0]; } if ( $( '.tribe-events-calendar' ).length && $( '#tribe-events-bar' ).length ) { if ( initial_date && initial_date.length > 7 ) { $( '#tribe-bar-date-day' ).val( initial_date.slice( -3 ) ); $tribedate.val( initial_date.substring( 0, 7 ) ); } } // begin display date formatting var date_format = 'yyyy-mm'; if ( ts.datepicker_format !== '0' ) { // we are not using the default query date format, lets grab it from the data array var arr_key = parseInt( ts.datepicker_format ), mask_key = 'm' + ts.datepicker_format.toString(); date_format = td.datepicker_formats.month[arr_key]; // if url date is set and datepicker format is different from query format // we need to fix the input value to emulate that before kicking in the datepicker if ( initial_date ) { if ( initial_date.length <= 7 ) { initial_date = initial_date + '-01'; } $tribedate.val( tribeDateFormat( initial_date, mask_key ) ); } } td.datepicker_opts = { format : date_format, minViewMode: 'months', autoclose : true }; $tribedate .bootstrapDatepicker( td.datepicker_opts ) .on( 'changeDate', function( e ) { ts.mdate = e.date; var year = e.date.getFullYear(), month = ('0' + (e.date.getMonth() + 1)).slice( -2 ); date_mod = true; ts.date = year + '-' + month; if ( tt.no_bar() || tt.live_ajax() && tt.pushstate ) { if ( ts.ajax_running || ts.updating_picker ) { return; } if ( ts.filter_cats ) { td.cur_url = $( '#tribe-events-header' ).data( 'baseurl' ) + ts.date + '/'; } else { if ( td.default_permalinks ) { td.cur_url = base_url; } else { td.cur_url = base_url + ts.date + '/'; } } ts.popping = false; tf.pre_ajax( function() { tribe_events_calendar_ajax_post(); } ); } } ); function tribe_mobile_load_events( date ) { var $target = $( '.tribe-mobile-day[data-day="' + date + '"]' ), $cell = $( '.tribe-events-calendar td[data-day="' + date + '"]' ), $more = $cell.find( '.tribe-events-viewmore' ), $events = $cell.find( '.type-tribe_events' ); if ( $events.length ) { $events .each( function() { var $this = $( this ); if ( $this.tribe_has_attr( 'data-tribejson' ) ) { var data = $this.data( 'tribejson' ); $target.append( tribe_tmpl( 'tribe_tmpl_month_mobile', data ) ); } } ); if ( $more.length ) { $target .append( $more.clone() ); } } } function tribe_mobile_setup_day( $date ) { var data = $date.data( 'tribejson' ); data.date = $date.attr( 'data-day' ); var $calendar = $date.parents( '.tribe-events-calendar' ), $container = $calendar.next( '#tribe-mobile-container' ), $days = $container.find( '.tribe-mobile-day' ), $triggers = $calendar.find( '.mobile-trigger' ), _active = '[data-day="' + data.date + '"]', $day = $days.filter( _active ); data.has_events = $date.hasClass( 'tribe-events-has-events' ); $triggers.removeClass( 'mobile-active' ) // If full_date_name is empty then default to highlighting the first day of the current month .filter( _active ).addClass( 'mobile-active' ); $days.hide(); if ( $day.length ) { $day.show(); } else { $container.append( tribe_tmpl( 'tribe_tmpl_month_mobile_day_header', data ) ); tribe_mobile_load_events( data.date ); } } function tribe_mobile_month_setup() { var $today = $wrapper.find( '.tribe-events-present' ), $mobile_trigger = $wrapper.find( '.mobile-trigger' ), $tribe_grid = $wrapper.find( document.getElementById( 'tribe-events-content' ) ).find( '.tribe-events-calendar' ); if ( !$( '#tribe-mobile-container' ).length ) { $( '<div id="tribe-mobile-container" />' ).insertAfter( $tribe_grid ); } if ( $today.length && $today.is( '.tribe-events-thismonth' ) ) { tribe_mobile_setup_day( $today ); } else { var $first_current_day = $mobile_trigger.filter( ".tribe-events-thismonth" ).first(); tribe_mobile_setup_day( $first_current_day ); } } function tribe_mobile_day_abbr() { $wrapper.find( '.tribe-events-calendar th' ).each( function() { var $this = $( this ), day_abbr = $this.attr( 'data-day-abbr' ), day_full = $this.attr( 'title' ); if ( $body.is( '.tribe-mobile' ) ) { $this.text( day_abbr ); } else { $this.text( day_full ); } } ); } function tribe_month_view_init( resize ) { if ( $body.is( '.tribe-mobile' ) ) { tribe_mobile_day_abbr(); tribe_mobile_month_setup(); } else { if ( resize ) { tribe_mobile_day_abbr(); } } } tribe_month_view_init( true ); $( te ).on( 'tribe_ev_resizeComplete', function() { tribe_month_view_init( true ); } ); if ( tt.pushstate && !tt.map_view() ) { var params = 'action=tribe_calendar&eventDate=' + $( '#tribe-events-header' ).data( 'date' ); if ( td.params.length ) { params = params + '&' + td.params; } if ( ts.category ) { params = params + '&tribe_event_category=' + ts.category; } history.replaceState( { "tribe_params": params }, ts.page_title, location.href ); $( window ).on( 'popstate', function( event ) { var state = event.originalEvent.state; if ( state ) { ts.do_string = false; ts.pushstate = false; ts.popping = true; ts.params = state.tribe_params; tf.pre_ajax( function() { tribe_events_calendar_ajax_post(); } ); tf.set_form( ts.params ); } } ); } $( '#tribe-events' ) .on( 'click', '.tribe-events-nav-previous, .tribe-events-nav-next', function( e ) { e.preventDefault(); if ( ts.ajax_running ) { return; } var $this = $( this ).find( 'a' ); ts.date = $this.data( "month" ); ts.mdate = ts.date + '-01'; if ( ts.datepicker_format !== '0' ) { tf.update_picker( tribeDateFormat( ts.mdate, mask_key ) ); } else { tf.update_picker( ts.date ); } if ( ts.filter_cats ) { td.cur_url = $( '#tribe-events-header' ).data( 'baseurl' ); } else { td.cur_url = $this.attr( "href" ); } if ( td.default_permalinks ) { td.cur_url = td.cur_url.split("?")[0]; } ts.popping = false; tf.pre_ajax( function() { tribe_events_calendar_ajax_post(); } ); } ) .on( 'click', 'td.tribe-events-thismonth a', function( e ) { e.stopPropagation(); } ) .on( 'click', '[id*="tribe-events-daynum-"] a', function( e ) { if ( $body.is( '.tribe-mobile' ) ) { e.preventDefault(); var $trigger = $( this ).closest( '.mobile-trigger' ); tribe_mobile_setup_day( $trigger ); } } ) .on( 'click', '.mobile-trigger', function( e ) { if ( $body.is( '.tribe-mobile' ) ) { e.preventDefault(); e.stopPropagation(); tribe_mobile_setup_day( $( this ) ); } } ); tf.snap( '#tribe-bar-form', 'body', '#tribe-events-footer .tribe-events-nav-previous, #tribe-events-footer .tribe-events-nav-next' ); /** * @function tribe_events_bar_calendar_ajax_actions * @desc On events bar submit, this function collects the current state of the bar and sends it to the month view ajax handler. * @param {event} e The event object. */ function tribe_events_bar_calendar_ajax_actions( e ) { if ( tribe_events_bar_action != 'change_view' ) { e.preventDefault(); if ( ts.ajax_running ) { return; } if ( $tribedate.val().length ) { if ( ts.datepicker_format !== '0' ) { ts.date = tribeDateFormat( $tribedate.bootstrapDatepicker( 'getDate' ), 'tribeMonthQuery' ); } else { ts.date = $tribedate.val(); } } else { if ( !date_mod ) { ts.date = td.cur_date.slice( 0, -3 ); } } if ( ts.filter_cats ) { td.cur_url = $( '#tribe-events-header' ).data( 'baseurl' ) + ts.date + '/'; } else { if ( td.default_permalinks ) { td.cur_url = base_url; } else { td.cur_url = base_url + ts.date + '/'; } } ts.popping = false; tf.pre_ajax( function() { tribe_events_calendar_ajax_post(); } ); } } $( 'form#tribe-bar-form' ).on( 'submit', function( e ) { tribe_events_bar_calendar_ajax_actions( e ); } ); $( te ).on( 'tribe_ev_runAjax', function() { tribe_events_calendar_ajax_post(); } ); $( te ).on( 'tribe_ev_updatingRecurrence', function() { ts.date = $( '#tribe-events-header' ).data( "date" ); if ( ts.filter_cats ) { td.cur_url = $( '#tribe-events-header' ).data( 'baseurl' ) + ts.date + '/'; } else { if ( td.default_permalinks ) { td.cur_url = base_url; } else { td.cur_url = base_url + ts.date + '/'; } } ts.popping = false; } ); /** * @function tribe_events_calendar_ajax_post * @desc The ajax handler for month view. * Fires the custom event 'tribe_ev_serializeBar' at start, then 'tribe_ev_collectParams' to gather any additional paramters before actually launching the ajax post request. * As post begins 'tribe_ev_ajaxStart' and 'tribe_ev_monthView_AjaxStart' are fired, and then 'tribe_ev_ajaxSuccess' and 'tribe_ev_monthView_ajaxSuccess' are fired on success. * Various functions in the events plugins hook into these events. They are triggered on the tribe_ev.events object. */ function tribe_events_calendar_ajax_post() { if ( tf.invalid_date( ts.date ) ) { return; } $( '.tribe-events-calendar' ).tribe_spin(); ts.pushcount = 0; ts.ajax_running = true; if ( !ts.popping ) { ts.params = { action : 'tribe_calendar', eventDate: ts.date }; ts.url_params = {}; if ( ts.category ) { ts.params.tribe_event_category = ts.category; ts.url_params.tribe_events_cat = ts.category; } if ( td.default_permalinks ) { if( !ts.url_params.hasOwnProperty( 'post_type' ) ){ ts.url_params['post_type'] = config.events_post_type; } if( !ts.url_params.hasOwnProperty( 'eventDisplay' ) ){ ts.url_params['eventDisplay'] = ts.view; } } $( te ).trigger( 'tribe_ev_serializeBar' ); ts.params = $.param( ts.params ); ts.url_params = $.param( ts.url_params ); $( te ).trigger( 'tribe_ev_collectParams' ); if ( ts.pushcount > 0 || ts.filters || td.default_permalinks || ts.category ) { ts.do_string = true; ts.pushstate = false; } else { ts.do_string = false; ts.pushstate = true; } } if ( tt.pushstate && !ts.filter_cats ) { // @ifdef DEBUG dbug && debug.time( 'Month View Ajax Timer' ); // @endif $( te ).trigger( 'tribe_ev_ajaxStart' ).trigger( 'tribe_ev_monthView_AjaxStart' ); $.post( TribeCalendar.ajaxurl, ts.params, function( response ) { ts.initial_load = false; tf.enable_inputs( '#tribe_events_filters_form', 'input, select' ); if ( response.success ) { ts.ajax_running = false; td.ajax_response = { 'total_count': '', 'view' : response.view, 'max_pages' : '', 'tribe_paged': '', 'timestamp' : new Date().getTime() }; // @ifdef DEBUG if ( dbug && response.html === 0 ) { debug.warn( 'Month view ajax had an error in the query and returned 0.' ); } // @endif var $the_content = ''; if ( $.isFunction( $.fn.parseHTML ) ) { $the_content = $.parseHTML( response.html ); } else { $the_content = response.html; } $( '#tribe-events-content' ).replaceWith( $the_content ); tribe_month_view_init( true ); ts.page_title = $( '#tribe-events-header' ).data( 'title' ); document.title = ts.page_title; // @TODO: We need to D.R.Y. this assignment and the following if statement about shortcodes/do_string // Ensure that the base URL is, in fact, the URL we want td.cur_url = tf.get_base_url(); // we only want to add query args for Shortcodes and ugly URL sites if ( $( '#tribe-events.tribe-events-shortcode' ).length || ts.do_string ) { if ( -1 !== td.cur_url.indexOf( '?' ) ) { td.cur_url = td.cur_url.split( '?' )[0]; } td.cur_url = td.cur_url + '?' + ts.url_params; } if ( ts.do_string ) { history.pushState( { "tribe_date" : ts.date, "tribe_params": ts.params }, ts.page_title, td.cur_url ); } if ( ts.pushstate ) { history.pushState( { "tribe_date" : ts.date, "tribe_params": ts.params }, ts.page_title, td.cur_url ); } $( te ).trigger( 'tribe_ev_ajaxSuccess' ).trigger( 'tribe_ev_monthView_ajaxSuccess' ); $( te ).trigger( 'ajax-success.tribe' ).trigger( 'tribe_ev_monthView_ajaxSuccess' ); // @ifdef DEBUG dbug && debug.timeEnd( 'Month View Ajax Timer' ); // @endif } } ); } else { if ( ts.url_params.length ) { window.location = td.cur_url + '?' + ts.url_params; } else { window.location = td.cur_url; } } } // @ifdef DEBUG dbug && debug.info( 'TEC Debug: tribe-events-ajax-calendar.js successfully loaded, Tribe Events Init finished' ); dbug && debug.timeEnd( 'Tribe JS Init Timer' ); // @endif } ); })( window, document, jQuery, tribe_ev.data, tribe_ev.events, tribe_ev.fn, tribe_ev.state, tribe_ev.tests, tribe_js_config, tribe_debug );
agpl-3.0
235/gwt-odb-ui
src/net/pleso/odbui/public/js/dojo-release-1.0.2/dijit/tests/module.js
644
if(!dojo._hasResource["dijit.tests.module"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dijit.tests.module"] = true; dojo.provide("dijit.tests.module"); try{ dojo.require("dijit.tests._base.manager"); dojo.require("dijit.tests._base.viewport"); dojo.require("dijit.tests._base.wai"); dojo.require("dijit.tests._Templated"); dojo.require("dijit.tests.widgetsInTemplate"); dojo.require("dijit.tests.Container"); dojo.require("dijit.tests.layout.ContentPane"); dojo.require("dijit.tests.ondijitclick"); dojo.require("dijit.tests.form.Form"); }catch(e){ doh.debug(e); } }
agpl-3.0
mtlchun/edx
lms/djangoapps/lms_migration/migrate.py
8933
# # migration tools for content team to go from stable-edx4edx to LMS+CMS # import json import logging import os import xmodule.modulestore.django as xmodule_django from xmodule.modulestore.django import modulestore from django.http import HttpResponse from django.conf import settings import track.views try: from django.views.decorators.csrf import csrf_exempt except ImportError: from django.contrib.csrf.middleware import csrf_exempt log = logging.getLogger("edx.lms_migrate") LOCAL_DEBUG = True ALLOWED_IPS = settings.LMS_MIGRATION_ALLOWED_IPS def escape(s): """escape HTML special characters in string""" return str(s).replace('<', '&lt;').replace('>', '&gt;') def getip(request): ''' Extract IP address of requester from header, even if behind proxy ''' ip = request.META.get('HTTP_X_REAL_IP', '') # nginx reverse proxy if not ip: ip = request.META.get('REMOTE_ADDR', 'None') return ip def get_commit_id(course): #return course.metadata.get('GIT_COMMIT_ID', 'No commit id') return getattr(course, 'GIT_COMMIT_ID', 'No commit id') # getattr(def_ms.courses[reload_dir], 'GIT_COMMIT_ID','No commit id') def set_commit_id(course, commit_id): #course.metadata['GIT_COMMIT_ID'] = commit_id course.GIT_COMMIT_ID = commit_id # def_ms.courses[reload_dir].GIT_COMMIT_ID = new_commit_id def manage_modulestores(request, reload_dir=None, commit_id=None): ''' Manage the static in-memory modulestores. If reload_dir is not None, then instruct the xml loader to reload that course directory. ''' html = "<html><body>" def_ms = modulestore() courses = def_ms.get_courses() #---------------------------------------- # check on IP address of requester ip = getip(request) if LOCAL_DEBUG: html += '<h3>IP address: %s <h3>' % ip html += '<h3>User: %s </h3>' % request.user html += '<h3>My pid: %s</h3>' % os.getpid() log.debug(u'request from ip=%s, user=%s', ip, request.user) if not (ip in ALLOWED_IPS or 'any' in ALLOWED_IPS): if request.user and request.user.is_staff: log.debug(u'request allowed because user=%s is staff', request.user) else: html += 'Permission denied' html += "</body></html>" log.debug('request denied, ALLOWED_IPS=%s' % ALLOWED_IPS) return HttpResponse(html, status=403) #---------------------------------------- # reload course if specified; handle optional commit_id if reload_dir is not None: if reload_dir not in def_ms.courses: html += '<h2 class="inline-error">Error: "%s" is not a valid course directory</h2>' % reload_dir else: # reloading based on commit_id is needed when running mutiple worker threads, # so that a given thread doesn't reload the same commit multiple times current_commit_id = get_commit_id(def_ms.courses[reload_dir]) log.debug('commit_id="%s"' % commit_id) log.debug('current_commit_id="%s"' % current_commit_id) if (commit_id is not None) and (commit_id == current_commit_id): html += "<h2>Already at commit id %s for %s</h2>" % (commit_id, reload_dir) track.views.server_track(request, 'reload %s skipped already at %s (pid=%s)' % (reload_dir, commit_id, os.getpid(), ), {}, page='migrate') else: html += '<h2>Reloaded course directory "%s"</h2>' % reload_dir def_ms.try_load_course(reload_dir) gdir = settings.DATA_DIR / reload_dir new_commit_id = os.popen('cd %s; git log -n 1 | head -1' % gdir).read().strip().split(' ')[1] set_commit_id(def_ms.courses[reload_dir], new_commit_id) html += '<p>commit_id=%s</p>' % new_commit_id track.views.server_track(request, 'reloaded %s now at %s (pid=%s)' % (reload_dir, new_commit_id, os.getpid()), {}, page='migrate') #---------------------------------------- html += '<h2>Courses loaded in the modulestore</h2>' html += '<ol>' for cdir, course in def_ms.courses.items(): html += '<li><a href="%s/migrate/reload/%s">%s</a> (%s)</li>' % ( settings.EDX_ROOT_URL, escape(cdir), escape(cdir), course.location.to_deprecated_string() ) html += '</ol>' #---------------------------------------- #dumpfields = ['definition', 'location', 'metadata'] dumpfields = ['location', 'metadata'] for cdir, course in def_ms.courses.items(): html += '<hr width="100%"/>' html += '<h2>Course: %s (%s)</h2>' % (course.display_name_with_default, cdir) html += '<p>commit_id=%s</p>' % get_commit_id(course) for field in dumpfields: data = getattr(course, field, None) html += '<h3>%s</h3>' % field if type(data) == dict: html += '<ul>' for k, v in data.items(): html += '<li>%s:%s</li>' % (escape(k), escape(v)) html += '</ul>' else: html += '<ul><li>%s</li></ul>' % escape(data) #---------------------------------------- html += '<hr width="100%"/>' html += "courses: <pre>%s</pre>" % escape(courses) ms = xmodule_django._MODULESTORES html += "modules: <pre>%s</pre>" % escape(ms) html += "default modulestore: <pre>%s</pre>" % escape(unicode(def_ms)) #---------------------------------------- log.debug('_MODULESTORES=%s' % ms) log.debug('courses=%s' % courses) log.debug('def_ms=%s' % unicode(def_ms)) html += "</body></html>" return HttpResponse(html) @csrf_exempt def gitreload(request, reload_dir=None): ''' This can be used as a github WebHook Service Hook, for reloading of the content repo used by the LMS. If reload_dir is not None, then instruct the xml loader to reload that course directory. ''' html = "<html><body>" ip = getip(request) html += '<h3>IP address: %s ' % ip html += '<h3>User: %s ' % request.user ALLOWED_IPS = [] # allow none by default if hasattr(settings, 'ALLOWED_GITRELOAD_IPS'): # allow override in settings ALLOWED_IPS = settings.ALLOWED_GITRELOAD_IPS if not (ip in ALLOWED_IPS or 'any' in ALLOWED_IPS): if request.user and request.user.is_staff: log.debug(u'request allowed because user=%s is staff', request.user) else: html += 'Permission denied' html += "</body></html>" log.debug('request denied from %s, ALLOWED_IPS=%s' % (ip, ALLOWED_IPS)) return HttpResponse(html) #---------------------------------------- # see if request is from github (POST with JSON) if reload_dir is None and 'payload' in request.POST: payload = request.POST['payload'] log.debug("payload=%s" % payload) gitargs = json.loads(payload) log.debug("gitargs=%s" % gitargs) reload_dir = gitargs['repository']['name'] log.debug("github reload_dir=%s" % reload_dir) gdir = settings.DATA_DIR / reload_dir if not os.path.exists(gdir): log.debug("====> ERROR in gitreload - no such directory %s" % reload_dir) return HttpResponse('Error') cmd = "cd %s; git reset --hard HEAD; git clean -f -d; git pull origin; chmod g+w course.xml" % gdir log.debug(os.popen(cmd).read()) if hasattr(settings, 'GITRELOAD_HOOK'): # hit this hook after reload, if set gh = settings.GITRELOAD_HOOK if gh: ghurl = '%s/%s' % (gh, reload_dir) r = requests.get(ghurl) log.debug("GITRELOAD_HOOK to %s: %s" % (ghurl, r.text)) #---------------------------------------- # reload course if specified if reload_dir is not None: def_ms = modulestore() if reload_dir not in def_ms.courses: html += '<h2 class="inline-error">Error: "%s" is not a valid course directory</font></h2>' % reload_dir else: html += "<h2>Reloaded course directory '%s'</h2>" % reload_dir def_ms.try_load_course(reload_dir) track.views.server_track(request, 'reloaded %s' % reload_dir, {}, page='migrate') return HttpResponse(html)
agpl-3.0
GPCsolutions/ekylibre
app/controllers/backend/document_templates_controller.rb
1288
# == License # Ekylibre - Simple agricultural ERP # Copyright (C) 2008-2011 Brice Texier, Thibaud Merigon # # 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 # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class Backend::DocumentTemplatesController < Backend::BaseController manage_restfully language: "Preference[:language]".c unroll list(order: :name) do |t| t.action :edit t.action :destroy, if: :destroyable? t.column :active t.column :name t.column :nature t.column :by_default t.column :archiving t.column :language end # Loads ou reloads.all managed document templates def load DocumentTemplate.load_defaults notify_success(:update_is_done) redirect_to action: :index end end
agpl-3.0
Meisterschueler/ogn-python
migrations/versions/c53fdb39f5a5_added_frequencyscanfiles.py
1588
"""Added UploadedFile Revision ID: c53fdb39f5a5 Revises: 002656878233 Create Date: 2020-12-01 18:18:43.404091 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'c53fdb39f5a5' down_revision = '002656878233' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('frequency_scan_files', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('gain', sa.Float(precision=2), nullable=False), sa.Column('upload_ip_address', sa.String(), nullable=False), sa.Column('upload_timestamp', sa.DateTime(), nullable=False), sa.Column('receiver_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['receiver_id'], ['receivers.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_frequency_scan_files_receiver_id'), 'frequency_scan_files', ['receiver_id'], unique=False) op.create_index(op.f('ix_frequency_scan_files_upload_timestamp'), 'frequency_scan_files', ['upload_timestamp'], unique=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_frequency_scan_files_upload_timestamp'), table_name='frequency_scan_files') op.drop_index(op.f('ix_frequency_scan_files_receiver_id'), table_name='frequency_scan_files') op.drop_table('frequency_scan_files') # ### end Alembic commands ###
agpl-3.0
aayushmudgal/CloudCoder
CloudCoderTools/src/org/cloudcoder/importer/DateTimeToMillis.java
780
package org.cloudcoder.importer; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class DateTimeToMillis { public static final String FORMAT = "dd MM yyyy HH:mm:ss Z"; public static void main(String[] args) throws ParseException { Scanner keyboard = new Scanner(System.in); System.out.println("Enter date/time in format " + FORMAT); String dateTime = keyboard.nextLine(); long time = convert(dateTime); System.out.println(time); } public static long convert(String dateTime) throws ParseException { DateFormat formatter = new SimpleDateFormat(FORMAT); Date date = (Date) formatter.parse(dateTime); long time = date.getTime(); return time; } }
agpl-3.0
dhootha/phpform
reports/test/libraries/PMA_tbl_columns_definition_form_test.php
25647
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Tests for libraries/tbl_columns_definition_form.lib.php * * @package PhpMyAdmin-test */ /* * Include to test. */ require_once 'libraries/Util.class.php'; require_once 'libraries/tbl_columns_definition_form.lib.php'; require_once 'libraries/DatabaseInterface.class.php'; require_once 'libraries/Partition.class.php'; require_once 'libraries/Types.class.php'; require_once 'libraries/Theme.class.php'; require_once 'libraries/php-gettext/gettext.inc'; require_once 'libraries/transformations.lib.php'; require_once 'libraries/mysql_charsets.inc.php'; require_once 'libraries/StorageEngine.class.php'; /** * Tests for libraries/tbl_columns_definition_form.lib.php * * @package PhpMyAdmin-test */ class PMA_TblColumnsDefinitionFormTest extends PHPUnit_Framework_TestCase { /** * SetUp function for test cases * * @return void */ public function setUp() { $GLOBALS['cfg']['ServerDefault'] = 1; $GLOBALS['cfg']['DBG'] = null; $GLOBALS['cfg']['TextareaCols'] = 10; $GLOBALS['cfg']['TextareaRows'] = 15; $GLOBALS['pmaThemeImage'] = 'image'; $_SESSION['PMA_Theme'] = PMA_Theme::load('./themes/pmahomme'); $_SESSION['PMA_Theme'] = new PMA_Theme(); } /** * Test for PMA_getFormsParameters * * @return void */ public function testGetFormsParameters() { // case 1 $_REQUEST['after_field'] = "affield"; $_REQUEST['field_where'] = "fwhere"; $result = PMA_getFormsParameters( "dbname", "tablename", "tbl_create.php", 22, array(12, 13) ); $this->assertEquals( array( 'db' => 'dbname', 'reload' => 1, 'orig_num_fields' => 22, 'orig_field_where' => 'fwhere', 'orig_after_field' => 'affield', 'selected[0]' => 12, 'selected[1]' => 13 ), $result ); // case 2 $result = PMA_getFormsParameters( "dbname", "tablename", "tbl_addfield.php", null, 1 ); $this->assertEquals( array( 'db' => 'dbname', 'table' => 'tablename', 'orig_field_where' => 'fwhere', 'orig_after_field' => 'affield', 'field_where' => 'fwhere', 'after_field' => 'affield' ), $result ); // case 3 $_REQUEST['after_field'] = null; $_REQUEST['field_where'] = null; $result = PMA_getFormsParameters( "dbname", "tablename", null, 0, null ); $this->assertEquals( array( 'db' => 'dbname', 'table' => 'tablename', 'orig_num_fields' => 0 ), $result ); } /** * Test for PMA_getHtmlForTableConfigurations * * @return void */ public function testGetHtmlForTableConfigurations() { $_REQUEST['comment'] = 'c&d'; $_REQUEST['tbl_storage_engine'] = 'engine'; $_REQUEST['tbl_collation'] = 'latin1_swedish_ci'; $_REQUEST['partition_definition'] = "partition>"; $dbi = $this->getMockBuilder('PMA_DatabaseInterface') ->disableOriginalConstructor() ->getMock(); $dbi->expects($this->any()) ->method('fetchResult') ->will( $this->returnValue( array( array( 'Name' => 'partition', 'Support' => 'NO' ) ) ) ); $GLOBALS['dbi'] = $dbi; $result = PMA_getHtmlForTableConfigurations(); $this->assertContains( '<input type="text" name="comment" size="40" maxlength="2048" ' . 'value="c&amp;d" class="textfield"', $result ); $this->assertContains( '<select name="tbl_storage_engine">', $result ); $this->assertContains( '<select lang="en" dir="ltr" name="tbl_collation">', $result ); $this->assertContains( '<option value="utf8_bin" title="Unicode (multilingual), Binary">' . 'utf8_bin</option>', $result ); $this->assertContains( '<textarea name="partition_definition" id="partitiondefinition" ' . 'cols="10" rows="15" dir="text_dir">partition&gt;</textarea>', $result ); } /** * Test for PMA_getHtmlForFooter * * @return void */ public function testGetHtmlForFooter() { $result = PMA_getHtmlForFooter(); $this->assertContains( '<input type="submit" name="do_save_data" value="Save" />', $result ); $this->assertContains( '<div id="properties_message">', $result ); $this->assertContains( '<div id="popup_background">', $result ); } /** * Test for PMA_getHtmlForTableNameAndNoOfColumns * * @return void */ public function testGetHtmlForTableNameAndNoOfColumns() { $_REQUEST['table'] = "tablename"; $result = PMA_getHtmlForTableNameAndNoOfColumns(); $this->assertContains( '<input type="text" name="table" size="40" maxlength="80" ' . 'value="tablename" class="textfield" ', $result ); $this->assertContains( '<input type="text" id="added_fields" name="added_fields" ' . 'size="2" value="1" onfocus="this.select()"', $result ); $this->assertContains( '<input type="button" name="submit_num_fields"value="Go"', $result ); } /** * Test for PMA_getHtmlForTableFieldDefinitions * * @return void */ public function testGetHtmlForTableFieldDefinitions() { $header_cells = array('h1', 'h2'); $content_cells = array( array('a', 'b'), array('c'), 2 ); $result = PMA_getHtmlForTableFieldDefinitions($header_cells, $content_cells); $this->assertContains( '<th>h1</th>', $result ); $this->assertContains( '<th>h2</th>', $result ); $this->assertContains( '<td class="center">a</td>', $result ); $this->assertContains( '<td class="center">b</td>', $result ); $this->assertContains( '<td class="center">c</td>', $result ); } /** * Test for PMA_getHtmlForTableCreateOrAddField * * @return void */ public function testGetHtmlForTableCreateOrAddField() { $dbi = $this->getMockBuilder('PMA_DatabaseInterface') ->disableOriginalConstructor() ->getMock(); $dbi->expects($this->any()) ->method('fetchResult') ->will( $this->returnValue( array() ) ); $GLOBALS['dbi'] = $dbi; $result = PMA_getHtmlForTableCreateOrAddField( "tbl_create.php", array('a' => 'b'), array(array('c1')), array('h1') ); $this->assertContains( '<form method="post" action="tbl_create.php" ' . 'class="create_table_form ajax lock-page">', $result ); $this->assertContains( '<input type="hidden" name="a" value="b"', $result ); $this->assertContains( '<select lang="en" dir="ltr" name="tbl_collation">', $result ); $this->assertContains( '<input type="submit" name="do_save_data" value="Save"', $result ); $this->assertContains( '<input type="text" name="table"', $result ); } /** * Test for PMA_getHeaderCells * * @return void */ public function testGetHeaderCells() { $GLOBALS['cfg']['BrowseMIME'] = true; $GLOBALS['cfg']['ShowHint'] = false; $result = PMA_getHeaderCells(false, array(), true, 'db', 'table'); $this->assertContains( 'Index', $result ); $this->assertContains( 'Move column', $result ); $this->assertContains( 'MIME type', $result ); } /** * Test for PMA_getMoveColumns * * @return void */ public function testGetMoveColumns() { $dbi = $this->getMockBuilder('PMA_DatabaseInterface') ->disableOriginalConstructor() ->getMock(); $dbi->expects($this->once()) ->method('tryQuery') ->with("SELECT * FROM `db`.`table` LIMIT 1") ->will($this->returnValue('v1')); $dbi->expects($this->once()) ->method('getFieldsMeta') ->with("v1") ->will($this->returnValue('movecols')); $GLOBALS['dbi'] = $dbi; $this->assertEquals( PMA_getMoveColumns('db', 'table'), 'movecols' ); } /** * Test for PMA_getRowDataForRegeneration * * @return void */ public function testGetRowDataForRegeneration() { $_REQUEST = array( 'field_name' => array(1 => 'name'), 'field_type' => array(1 => 'type'), 'field_collation' => array(1 => 'colltn'), 'field_null' => array(1 => true), 'field_key' => array(1 => "fulltext_1"), 'field_default_type' => array(1 => 'USER_DEFINED'), 'field_default_value' => array(1 => 'DEF'), 'field_extra' => array(1 => 'extra') ); $submit_fulltext = array(1 => 1); $result = PMA_getRowDataForRegeneration(1, $submit_fulltext); $this->assertEquals( array( 'Field' => 'name', 'Type' => 'type', 'Collation' => 'colltn', 'Null' => true, 'Key' => 'FULLTEXT', 'DefaultType' => 'USER_DEFINED', 'DefaultValue' => 'DEF', 'Default' => 'DEF', 'Extra' => 'extra', 'Comment' => 'FULLTEXT' ), $result ); } /** * Test for PMA_getSubmitPropertiesForRegeneration * * @return void */ public function testGetSubmitPropertiesForRegeneration() { $_REQUEST = array( 'field_length' => array(1 => 22), 'field_attribute' => array(1 => 'attr'), 'field_default_current_timestamp' => array() ); $result = PMA_getSubmitPropertiesForRegeneration(1); $this->assertEquals( array(22, 'attr', false), $result ); } /** * Test for PMA_getColumnMetaForDefault * * @return void */ public function testHandleRegeneration() { $_REQUEST = array( 'field_comments' => array(1 => 'comm'), 'field_mimetype' => array(1 => 'mime'), 'field_transformation' => array(1 => 'trans'), 'field_transformation_options' => array(1 => 'transops') ); $result = PMA_handleRegeneration(1, 'FULLTEXT', array(), array()); $this->assertEquals( array('comm'), $result[4] ); $this->assertEquals( array( array( 'mimetype' => 'mime', 'transformation' => 'trans', 'transformation_options' => 'transops' ) ), $result[5] ); } /** * Test for PMA_getColumnMetaForDefault * * @return void */ public function testGetColumnMetaForDefault() { $cmeta = array( 'Default' => null, 'Null' => 'YES', 'DefaultType' => 'a', 'DefaultValue' => 'b', ); $result = PMA_getColumnMetaForDefault($cmeta, null); $this->assertEquals( 'NULL', $result['DefaultType'] ); $this->assertEquals( '', $result['DefaultValue'] ); // case 2 $cmeta = array( 'Default' => null, 'Null' => 'NO', 'DefaultType' => 'a', 'DefaultValue' => 'b', ); $result = PMA_getColumnMetaForDefault($cmeta, true); $this->assertEquals( 'USER_DEFINED', $result['DefaultType'] ); $this->assertEquals( null, $result['DefaultValue'] ); // case 3 $cmeta = array( 'Default' => null, 'Null' => 'NO', 'DefaultType' => 'a', 'DefaultValue' => 'b', ); $result = PMA_getColumnMetaForDefault($cmeta, false); $this->assertEquals( 'NONE', $result['DefaultType'] ); $this->assertEquals( null, $result['DefaultValue'] ); // case 4 $cmeta = array( 'Default' => 'CURRENT_TIMESTAMP', 'Null' => 'NO', 'DefaultType' => 'a', 'DefaultValue' => 'b', ); $result = PMA_getColumnMetaForDefault($cmeta, false); $this->assertEquals( 'CURRENT_TIMESTAMP', $result['DefaultType'] ); $this->assertEquals( null, $result['DefaultValue'] ); // case 5 $cmeta = array( 'Default' => 'SOMETHING_ELSE', 'Null' => 'NO', 'DefaultType' => 'a', 'DefaultValue' => 'b', ); $result = PMA_getColumnMetaForDefault($cmeta, false); $this->assertEquals( 'USER_DEFINED', $result['DefaultType'] ); $this->assertEquals( 'SOMETHING_ELSE', $result['DefaultValue'] ); } /** * Test for PMA_getHtmlForColumnName * * @return void */ public function testGetHtmlForColumnName() { $cfgRelation = array('central_columnswork' => true); $result = PMA_getHtmlForColumnName( 2, 4, 4, array('Field' => "fieldname", 'column_status' => array('isReferenced' => false, 'isForeignKey' => false, 'isEditable' => true)), $cfgRelation ); $this->assertContains( '<input id="field_2_0" type="text" name="field_name[2]" ' . 'maxlength="64" class="textfield" title="Column" size="10" ' . 'value="fieldname" />', $result ); } /** * Test for PMA_getHtmlForColumnType * * @return void */ public function testGetHtmlForColumnType() { $GLOBALS['PMA_Types'] = new PMA_Types; $result = PMA_getHtmlForColumnType( 1, 4, 3, false, array('column_status' => array('isReferenced' => false, 'isForeignKey' => false, 'isEditable' => true)) ); $this->assertContains( '<select class="column_type" name="field_type[1]" id="field_1_1">', $result ); $this->assertContains( '<option title="">INT</option>', $result ); } /** * Test for PMA_getHtmlForTransformationOption * * @return void */ public function testGetHtmlForTransformationOption() { $cmeta = array( 'Field' => 'fieldname' ); $mime = array( 'fieldname' => array( 'transformation_options' => 'transops' ) ); $result = PMA_getHtmlForTransformationOption( 2, 4, 4, $cmeta, $mime, '' ); $this->assertContains( '<input id="field_2_0" type="text" name="field_transformation_' . 'options[2]" size="16" class="textfield" value="transops" />', $result ); } /** * Test for PMA_getHtmlForTransformation * * @return void */ public function testGetHtmlForTransformation() { $cmeta = array( 'Field' => 'fieldname' ); $mime = array( 'fieldname' => array( 'transformation' => 'Text_Plain_Preappend.class.php', 'transformation_options' => 'transops' ) ); $avail_mime = array( 'transformation' => array( 'foo' => 'bar' ), 'transformation_file' => array( 'foo' => 'Text_Plain_Preappend.class.php' ) ); $result = PMA_getHtmlForTransformation( 2, 0, 0, $avail_mime, $cmeta, $mime, '' ); $this->assertContains( '<select id="field_2_0" size="1" name="field_transformation[2]">', $result ); $this->assertContains( 'selected ', $result ); } /** * Test for PMA_getHtmlForMoveColumn * * @return void */ public function testGetHtmlForMoveColumn() { $cmeta = array( 'Field' => 'fieldname' ); $moveColumns = array(); $temp = new stdClass; $temp->name = 'a'; $moveColumns[] = $temp; $temp = new stdClass; $temp->name = 'fieldname'; $moveColumns[] = $temp; $result = PMA_getHtmlForMoveColumn( 2, 0, 0, $moveColumns, $cmeta ); $this->assertContains( '<select id="field_2_0" name="field_move_to[2]" size="1" ' . 'width="5em">', $result ); $this->assertContains( '<option value="" selected="selected">&nbsp;</option>', $result ); $this->assertContains( '<option value="a" disabled="disabled">after `a`</option>', $result ); $this->assertContains( '<option value="fieldname" disabled="disabled">after `fieldname`</option>', $result ); } /** * Test for PMA_getHtmlForColumnComment * * @return void */ public function testGetHtmlForColumnComment() { $cmeta = array( 'Field' => 'fieldname' ); $commentMeta = array( 'fieldname' => 'fieldnamecomment<' ); $result = PMA_getHtmlForColumnComment( 2, 1, 0, $cmeta, $commentMeta ); $this->assertContains( '<input id="field_2_1" type="text" name="field_comments[2]" ' . 'size="12" value="fieldnamecomment&lt;" class="textfield" />', $result ); } /** * Test for PMA_getHtmlForColumnAutoIncrement * * @return void */ public function testGetHtmlForColumnAutoIncrement() { $cmeta = array( 'Extra' => 'auto_increment' ); $result = PMA_getHtmlForColumnAutoIncrement( 2, 1, 0, $cmeta ); $this->assertContains( '<input name="field_extra[2]" id="field_2_1" checked="checked" ' . 'type="checkbox" value="AUTO_INCREMENT" />', $result ); } /** * Test for PMA_getHtmlForColumnIndexes * * @return void */ public function testGetHtmlForColumnIndexes() { $cmeta = array( 'Extra' => 'auto_increment', 'Field' => 'fieldname' ); $result = PMA_getHtmlForColumnIndexes( 2, 1, 0, $cmeta ); $this->assertContains( '<select name="field_key[2]" id="field_2_1"', $result ); $this->assertContains( '<option value="none_2">---</option>', $result ); $this->assertContains( '<option value="primary_2" title="Primary">PRIMARY</option>', $result ); $this->assertContains( '<option value="unique_2" title="Unique">UNIQUE</option>', $result ); $this->assertContains( '<option value="index_2" title="Index">INDEX</option>', $result ); } /** * Test for PMA_getHtmlForIndexTypeOption * * @return void */ public function testGetHtmlForIndexTypeOption() { $cmeta = array( 'Key' => 'PRI' ); $result = PMA_getHtmlForIndexTypeOption( 2, $cmeta, 'INT', 'PRI' ); $this->assertContains( '<option value="int_2" title="INT" selected="selected">INT</option>', $result ); } /** * Test for PMA_getHtmlForColumnNull * * @return void */ public function testGetHtmlForColumnNull() { $cmeta = array( 'Null' => 'YES' ); $result = PMA_getHtmlForColumnNull( 2, 3, 1, $cmeta ); $this->assertContains( '<input name="field_null[2]" id="field_2_2" checked="checked" ' . 'type="checkbox" value="NULL" class="allow_null"/>', $result ); } /** * Test for PMA_getHtmlForColumnAttribute * * @return void */ public function testGetHtmlForColumnAttribute() { $cmeta = array( 'Null' => 'YES', 'Extra' => 'on update CURRENT_TIMESTAMP', 'Field' => 'f' ); $colspec = array('attribute' => 'attr'); $analyzed_sql = array( array( 'create_table_fields' => array( 'f' => array( 'default_current_timestamp' => true, ) ) ) ); $types = $this->getMockBuilder('PMA_Types') ->disableOriginalConstructor() ->setMethods(array('getAttributes')) ->getMock(); $types->expects($this->once()) ->method('getAttributes') ->will( $this->returnValue( array('on update CURRENT_TIMESTAMP') ) ); $GLOBALS['PMA_Types'] = $types; $result = PMA_getHtmlForColumnAttribute( 2, 3, 1, $colspec, $cmeta, true, $analyzed_sql ); $this->assertContains( '<select style="width: 7em;" name="field_attribute[2]" ' . 'id="field_2_2">', $result ); $this->assertContains( '<option value="on update CURRENT_TIMESTAMP">', $result ); } /** * Test for PMA_getHtmlForColumnCollation * * @return void */ public function testGetHtmlForColumnCollation() { $cmeta = array( 'Collation' => 'utf8_general_ci' ); $result = PMA_getHtmlForColumnCollation( 2, 3, 1, $cmeta ); $this->assertContains( '<select lang="en" dir="ltr" name="field_collation[2]" id="field_2_2">', $result ); $this->assertContains( '<option value="utf8_bin" title="Unicode (multilingual), Binary">', $result ); } /** * Test for PMA_getHtmlForColumnLength * * @return void */ public function testGetHtmlForColumnLength() { $result = PMA_getHtmlForColumnLength( 2, 3, 1, 10, 8 ); $this->assertContains( '<input id="field_2_2" type="text" name="field_length[2]" size="10" ' . 'value="8" class="textfield" />', $result ); $this->assertContains( '<p class="enum_notice" id="enum_notice_2_2">', $result ); } /** * Test for PMA_getHtmlForColumnDefault * * @return void */ public function testGetHtmlForColumnDefault() { $cmeta = array( 'Default' => 'YES', 'DefaultType' => 'NONE', 'DefaultValue' => '2222' ); $result = PMA_getHtmlForColumnDefault( 2, 3, 1, 'TIMESTAMP', true, $cmeta ); $this->assertContains( '<select name="field_default_type[2]" id="field_2_2" ' . 'class="default_type">', $result ); $this->assertContains( '<option value="NONE" selected="selected" >', $result ); $this->assertContains( '<input type="text" name="field_default_value[2]" size="12" ' . 'value="2222" class="textfield default_value" />', $result ); } /** * Test for PMA_getFormParamsForOldColumn * * @return void */ public function testGetFormParamsForOldColumn() { // Function needs correction $this->markTestIncomplete('Not yet implemented!'); } } ?>
lgpl-2.1
aglne/lenskit
lenskit-knn/src/main/java/org/grouplens/lenskit/knn/item/package-info.java
3610
/* * LensKit, an open source recommender systems toolkit. * Copyright 2010-2014 LensKit Contributors. See CONTRIBUTORS.md. * Work on LensKit has been funded by the National Science Foundation under * grants IIS 05-34939, 08-08692, 08-12148, and 10-17697. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * 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. */ /** * Implementation of item-item collaborative filtering. * <p> * The item-item CF implementation is built up of several pieces. The * {@linkplain org.grouplens.lenskit.knn.item.model.ItemItemModelBuilder model builder} takes the rating data * and several parameters and components, such as the * {@linkplain org.grouplens.lenskit.vectors.similarity.VectorSimilarity similarity function} and {@linkplain ModelSize model size}, * and computes the {@linkplain org.grouplens.lenskit.knn.item.model.SimilarityMatrixModel similarity matrix}. The * {@linkplain ItemItemScorer scorer} * uses this model to score items. * <p> * The basic idea of item-item CF is to compute similarities between items, typically * based on the users that have rated them, and the recommend items similar to the items * that a user likes. The model is then truncated — only the {@link ModelSize} most similar * items are retained for each item – to save space. Neighborhoods are further truncated * when doing recommendation; only the {@link org.grouplens.lenskit.knn.NeighborhoodSize} most similar items that * a user has rated are used to score any given item. {@link ModelSize} is typically * larger than {@link org.grouplens.lenskit.knn.NeighborhoodSize} to improve the ability of the recommender to find * neighbors. * <p> * When the similarity function is asymmetric (\(s(i,j)=s(j,i)\) does not hold), some care * is needed to make sure that the function is used in the correct direction. Following * Deshpande and Karypis, we use the similarity function as \(s(j,i)\), where \(j\) is the * item the user has purchased or rated and \(i\) is the item that is going to be scored. This * function is then stored in row \(i\) and column \(j\) of the matrix. Rows are then truncated * (so we retain the {@link ModelSize} most similar items for each \(i\)); this direction differs * from Deshpande &amp; Karypis, as row truncation is more efficient &amp; simpler to write within * LensKit's item-item algorithm structure, and performs better in offline tests against the * MovieLens 1M data set * (see <a href="http://dev.grouplens.org/trac/lenskit/wiki/ItemItemTruncateDirection">writeup</a>). * Computation against a particular item the user has rated is done down that item's column. * <p> * The scorers and recommenders actually operate on a generic {@link org.grouplens.lenskit.knn.item.model.ItemItemModel}, so the * item-based scoring algorithm can be used against other sources of similarity, such as * similarities stored in a database or text index. */ package org.grouplens.lenskit.knn.item;
lgpl-2.1
jbechtel/CASMcode
src/casm/hull/GeometryPieces.cc
5859
#include "casm/hull/GeometryPieces.hh" #include "casm/BP_C++/BP_Geo.hh" #include "casm/BP_C++/BP_Vec.hh" #include "casm/container/Array.hh" #include "casm/casm_io/jsonParser.hh" namespace CASM { /** * The following is a horrendous piece of code I'm using to avoid #include nightmares * that show up trying to define the appropriate to_json/from_json for BP::BP_Vec. * The plan right now is to eventually move away from BP::Geo to qHull, so this * will disappear on the long run. */ Array<int> BP_to_CASM(const BP::BP_Vec<int> &value) { Array<int> casmfied; for(Index i = 0; i < value.size(); i++) { casmfied.push_back(value[i]); } return casmfied; } /** * Given a Geo object (presumably a hull for your groundstates) this * will return a jsonParser object that has the relevant information * to plot 0K phase diagrams in composition and chemical potential space. * Includes * rank: equivalent to number of components in your system * facet x: normal: normal vector to your facet with dimensionality of rank * vertex a: index of one of the corners of facet x * vertex b: ... * ... * intercept 1: intercept of facet x on energy axis at a composition of pure component 1 * intercept 2: ... * ... * neighbors: list of neighboring facets to facet x * facet y: ... * ... * * vertex x: index * position * neighboring vertices * facets it's on * * * The intercepts are related to the chemical potential. Since everything * is done relative to one of the components this routine can be changed * to account for this. For now, what this routine returns is * purely geometrical information. */ jsonParser hull_data(BP::Geo &hull) { //accessors in Geo aren't const //BP::Geo hull = ghull; //There's probably some sort of check that should go here that //makes sure your hull object isn't messed up. jsonParser hull_info; //First figure out the normal and rank hull_info["rank"] = hull.get_dim(); //State tolerance hull_info["tolerance"] = hull.get_Geo_tol(); //How many facets and points? hull_info["num_facets"] = hull.CH_facets_size(); hull_info["num_vertices"] = hull.CH_verts_size(); //Place to store all facets Array<jsonParser> facet_info_list; //loop over facets for(int f = 0; f < hull.CH_facets_size(); f++) { //make sublist of properties jsonParser facet_info = facet_data(hull, f); facet_info_list.push_back(facet_info); //store all the info you just found //hull_info[facetname]=facet_info; } //Place to store all vertices Array<jsonParser> vertex_info_list; //BP::BP_Vec<int> vertex_indices=hull.CH_verts_indices(); //loop over vertices for(int v = 0; v < hull.CH_verts_size(); v++) { //jsonParser vertex_info=vertex_data(hull,vertex_indices[v]); jsonParser vertex_info = vertex_data(hull, v); vertex_info_list.push_back(vertex_info); } hull_info["facets"] = facet_info_list; hull_info["vertices"] = vertex_info_list; return hull_info; } /** * Returns info of just one facet of the hull Geo object specified by index. * (See hull data for how the layout is) */ jsonParser facet_data(BP::Geo &hull, int findex) { jsonParser facet_info; //Store index facet_info["findex"] = findex; //Get the normal vector Eigen::VectorXd normal = hull.CH_facets_norm(findex); normal.normalize(); //Not done by default for some reason facet_info["normal"] = normal; //Get the area facet_info["area"] = hull.CH_facets_area(findex); //Include vertex info facet_info["vertices"] = BP_to_CASM(hull.CH_facets_nborverts(findex)); //Get indices for neighboring facets FIX THIS facet_info["neighboring_facets"] = BP_to_CASM(hull.CH_facets_nborfacets(findex)); //Figure out intercepts //for any point v on a facet with normal n we have n.v=const BP::BP_Vec<int> vertex_indices = hull.CH_facets_nborverts(findex); Eigen::VectorXd v = hull.CH_verts_pos(vertex_indices[0]); //I can't imagine not having a vertex, but maybe add a check? double k = v.dot(normal); int rank = hull.get_dim(); //If the intercept occurs at a point on the facet x, we have x=0,0,1,0,x_E (example) and we want x_E double normE = normal(0); Array<double> intercepts; //first member of vector is the energy, so stop one before that. This loop finds intercepts for all //the specified (independent) components for(int i = 1; i < rank; i++) { double intercept = (k - normal(i)) / normE; intercepts.push_back(intercept); } //lastly get the dependent component intercept intercepts.push_back(k / normE); facet_info["intercepts"] = intercepts; return facet_info; } /** * Returns info of just one vertex of the hull Geo object specified by index. * (See hull data for how the layout is) */ jsonParser vertex_data(BP::Geo &hull, int vindex) { jsonParser vertex_info; //Store index vertex_info["vindex"] = vindex; //Get position of vertex vertex_info["position"] = hull.CH_verts_pos(vindex); //Get indices for neighboring vertices vertex_info["neighboring_vertices"] = BP_to_CASM(hull.CH_verts_nborverts(vindex)); //Get indices for neighboring facets vertex_info["neighboring_facets"] = BP_to_CASM(hull.CH_verts_nborfacets(vindex)); //Check to see what facets this vertex is on //vertex_info["facets"]=BP_to_CASM(hull.CH_verts_nborfacets(index)); return vertex_info; } }
lgpl-2.1
bitsauce/ASIDE
build/release/moc_qtlocalpeer.cpp
4209
/**************************************************************************** ** Meta object code from reading C++ file 'qtlocalpeer.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../qtsingleapplication/src/qtlocalpeer.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qtlocalpeer.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_QtLocalPeer_t { QByteArrayData data[5]; char stringdata[55]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_QtLocalPeer_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_QtLocalPeer_t qt_meta_stringdata_QtLocalPeer = { { QT_MOC_LITERAL(0, 0, 11), QT_MOC_LITERAL(1, 12, 15), QT_MOC_LITERAL(2, 28, 0), QT_MOC_LITERAL(3, 29, 7), QT_MOC_LITERAL(4, 37, 17) }, "QtLocalPeer\0messageReceived\0\0message\0" "receiveConnection" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_QtLocalPeer[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 4, 0, 27, 2, 0x09 /* Protected */, // signals: parameters QMetaType::Void, QMetaType::QString, 3, // slots: parameters QMetaType::Void, 0 // eod }; void QtLocalPeer::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { QtLocalPeer *_t = static_cast<QtLocalPeer *>(_o); switch (_id) { case 0: _t->messageReceived((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 1: _t->receiveConnection(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (QtLocalPeer::*_t)(const QString & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QtLocalPeer::messageReceived)) { *result = 0; } } } } const QMetaObject QtLocalPeer::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_QtLocalPeer.data, qt_meta_data_QtLocalPeer, qt_static_metacall, 0, 0} }; const QMetaObject *QtLocalPeer::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *QtLocalPeer::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_QtLocalPeer.stringdata)) return static_cast<void*>(const_cast< QtLocalPeer*>(this)); return QObject::qt_metacast(_clname); } int QtLocalPeer::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } // SIGNAL 0 void QtLocalPeer::messageReceived(const QString & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } QT_END_MOC_NAMESPACE
lgpl-2.1
codeaudit/beast-mcmc
src/dr/math/distributions/UniformDistribution.java
5143
/* * UniformDistribution.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST 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 BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.math.distributions; import dr.math.UnivariateFunction; import dr.util.DataTable; /** * uniform distribution. * * @author Andrew Rambaut * @author Alexei Drummond * @version $Id: UniformDistribution.java,v 1.3 2005/07/11 14:06:25 rambaut Exp $ */ public class UniformDistribution implements Distribution { // // Public stuff // /* * Constructor */ public UniformDistribution(double lower, double upper) { this.lower = lower; this.upper = upper; } public double pdf(double x) { return pdf(x, lower, upper); } public double logPdf(double x) { return logPdf(x, lower, upper); } public double cdf(double x) { return cdf(x, lower, upper); } public double quantile(double y) { return quantile(y, lower, upper); } public double mean() { return mean(lower, upper); } public double variance() { return variance(lower, upper); } public final UnivariateFunction getProbabilityDensityFunction() { return pdfFunction; } private final UnivariateFunction pdfFunction = new UnivariateFunction() { public final double evaluate(double x) { return pdf(x); } public final double getLowerBound() { return lower; } public final double getUpperBound() { return upper; } }; /** * probability density function of the uniform distribution * * @param x argument * @param lower the lower bound of the uniform distribution * @param upper the upper bound of the uniform distribution * @return pdf value */ public static double pdf(double x, double lower, double upper) { return (x >= lower && x <= upper ? 1.0 / (upper - lower) : 0.0); } /** * the natural log of the probability density function of the uniform distribution * * @param x argument * @param lower the lower bound of the uniform distribution * @param upper the upper bound of the uniform distribution * @return log pdf value */ public static double logPdf(double x, double lower, double upper) { if (x < lower || x > upper) return Double.NEGATIVE_INFINITY; // improve numerical stability: return - Math.log(upper - lower); // return Math.log(pdf(x, lower, upper)); } /** * cumulative density function of the uniform distribution * * @param x argument * @param lower the lower bound of the uniform distribution * @param upper the upper bound of the uniform distribution * @return cdf value */ public static double cdf(double x, double lower, double upper) { if (x < lower) return 0.0; if (x > upper) return 1.0; return (x - lower) / (upper - lower); } /** * quantile (inverse cumulative density function) of the uniform distribution * * @param y argument * @param lower the lower bound of the uniform distribution * @param upper the upper bound of the uniform distribution * @return icdf value */ public static double quantile(double y, double lower, double upper) { if (!(y >= 0.0 && y <= 1.0)) throw new IllegalArgumentException("y must in range [0,1]"); return (y * (upper - lower)) + lower; } /** * mean of the uniform distribution * * @param lower the lower bound of the uniform distribution * @param upper the upper bound of the uniform distribution * @return mean */ public static double mean(double lower, double upper) { return (upper + lower) / 2; } /** * variance of the uniform distribution * * @param lower the lower bound of the uniform distribution * @param upper the upper bound of the uniform distribution * @return variance */ public static double variance(double lower, double upper) { return (upper - lower) * (upper - lower) / 12; } // Private private final double upper; private final double lower; }
lgpl-2.1
livioc/nhibernate-core
src/NHibernate.Test/MappingByCode/MappersTests/DynamicComponentMapperTests/ManyToOnePropertyOnDynamicCompoTests.cs
1895
using System.Collections; using System.Linq; using NHibernate.Cfg.MappingSchema; using NHibernate.Mapping.ByCode; using NHibernate.Mapping.ByCode.Impl; using NUnit.Framework; namespace NHibernate.Test.MappingByCode.MappersTests.DynamicComponentMapperTests { public class ManyToOnePropertyOnDynamicCompoTests { private class Person { public int Id { get; set; } private IDictionary info; public IDictionary Info { get { return info; } } } private class MyClass { public int Id { get; set; } } [Test] public void WhenAddThenHas() { var mapdoc = new HbmMapping(); var component = new HbmDynamicComponent(); var mapper = new DynamicComponentMapper(component, For<Person>.Property(p => p.Info), mapdoc); var propertyInfo = (new { A = (MyClass)null }).GetType().GetProperty("A"); mapper.ManyToOne(propertyInfo, x => { }); Assert.That(component.Properties.Select(x => x.Name), Is.EquivalentTo(new[] { "A" })); } [Test] public void WhenCustomizeThenCallCustomizer() { var mapdoc = new HbmMapping(); var component = new HbmDynamicComponent(); var mapper = new DynamicComponentMapper(component, For<Person>.Property(p => p.Info), mapdoc); var propertyInfo = (new { A = (MyClass)null }).GetType().GetProperty("A"); var called = false; mapper.ManyToOne(propertyInfo, x => called = true); Assert.That(called, Is.True); } [Test] public void WhenCustomizeAccessorThenIgnore() { var mapdoc = new HbmMapping(); var component = new HbmDynamicComponent(); var mapper = new DynamicComponentMapper(component, For<Person>.Property(p => p.Info), mapdoc); var propertyInfo = (new { A = (MyClass)null }).GetType().GetProperty("A"); mapper.ManyToOne(propertyInfo, x => x.Access(Accessor.Field)); Assert.That(component.Properties.OfType<HbmManyToOne>().Single().Access, Is.Null.Or.Empty); } } }
lgpl-2.1
flow123d/dealii
tests/hp/hp_quad_dof_identities_dgp.cc
2166
// --------------------------------------------------------------------- // // Copyright (C) 2005 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // check FE_DGP::hp_quad_dof_identities #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/hp/fe_collection.h> #include <deal.II/fe/fe_dgp.h> #include <fstream> template <int dim> void test () { hp::FECollection<dim> fe_collection; for (unsigned int i=1; i<8-dim; ++i) fe_collection.push_back (FE_DGP<dim>(i)); for (unsigned int i=0; i<fe_collection.size(); ++i) for (unsigned int j=0; j<fe_collection.size(); ++j) { const std::vector<std::pair<unsigned int, unsigned int> > identities = fe_collection[i].hp_quad_dof_identities (fe_collection[j]); deallog << "Identities for " << fe_collection[i].get_name() << " and " << fe_collection[j].get_name() << ": " << identities.size() << std::endl; for (unsigned int k=0; k<identities.size(); ++k) { Assert (identities[k].first < fe_collection[i].dofs_per_quad, ExcInternalError()); Assert (identities[k].second < fe_collection[j].dofs_per_quad, ExcInternalError()); deallog << identities[k].first << ' ' << identities[k].second << std::endl; } } } int main () { std::ofstream logfile("output"); logfile.precision(2); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); test<2> (); test<3> (); deallog << "OK" << std::endl; }
lgpl-2.1
anders9ustafsson/framework
Sources/Accord.Statistics/Testing/Power/Base/IPowerAnalysis.cs
4211
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2017 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Statistics.Testing.Power { using System; /// <summary> /// Common interface for power analysis objects. /// </summary> /// /// <remarks> /// <para> /// The power of a statistical test is the probability that it correctly rejects /// the null hypothesis when the null hypothesis is false. That is, </para> /// /// <para> /// <c>power = P(reject null hypothesis | null hypothesis is false)</c> /// </para> /// /// <para> /// It can be equivalently thought of as the probability of correctly accepting the /// alternative hypothesis when the alternative hypothesis is true - that is, the ability /// of a test to detect an effect, if the effect actually exists. The power is in general /// a function of the possible distributions, often determined by a parameter, under the /// alternative hypothesis. As the power increases, the chances of a Type II error occurring /// decrease. The probability of a Type II error occurring is referred to as the false /// negative rate (β) and the power is equal to 1−β. The power is also known as the sensitivity. /// </para> /// /// <para> /// Power analysis can be used to calculate the minimum sample size required so that /// one can be reasonably likely to detect an effect of a given size. Power analysis /// can also be used to calculate the minimum effect size that is likely to be detected /// in a study using a given sample size. In addition, the concept of power is used to /// make comparisons between different statistical testing procedures: for example, /// between a parametric and a nonparametric test of the same hypothesis. There is also /// the concept of a power function of a test, which is the probability of rejecting the /// null when the null is true.</para> /// /// <para> /// References: /// <list type="bullet"> /// <item><description> /// Wikipedia, The Free Encyclopedia. Statistical power. Available on: /// http://en.wikipedia.org/wiki/Statistical_power </description></item> /// </list></para> /// </remarks> /// /// <seealso cref="TTestPowerAnalysis"/> /// <seealso cref="ZTestPowerAnalysis"/> /// public interface IPowerAnalysis : ICloneable, IFormattable { /// <summary> /// Gets the test type. /// </summary> /// DistributionTail Tail { get; } /// <summary> /// Gets the power of the test, also known as the /// (1-Beta error rate) or the test's sensitivity. /// </summary> /// double Power { get; } /// <summary> /// Gets the significance level /// for the test. Also known as alpha. /// </summary> /// double Size { get; } /// <summary> /// Gets the number of samples /// considered in the test. /// </summary> /// double Samples { get; } /// <summary> /// Gets the effect size of the test. /// </summary> /// double Effect { get; } } }
lgpl-2.1
KDE/qt
src/gui/kernel/qpalette.cpp
40638
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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 Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qpalette.h" #include "qapplication.h" #include "qdatastream.h" #include "qvariant.h" QT_BEGIN_NAMESPACE static int qt_palette_count = 1; class QPalettePrivate { public: QPalettePrivate() : ref(1), ser_no(qt_palette_count++), detach_no(0) { } QAtomicInt ref; QBrush br[QPalette::NColorGroups][QPalette::NColorRoles]; int ser_no; int detach_no; }; static QColor qt_mix_colors(QColor a, QColor b) { return QColor((a.red() + b.red()) / 2, (a.green() + b.green()) / 2, (a.blue() + b.blue()) / 2, (a.alpha() + b.alpha()) / 2); } #ifdef QT3_SUPPORT #ifndef QT_NO_DATASTREAM QDataStream &qt_stream_out_qcolorgroup(QDataStream &s, const QColorGroup &g) { if(s.version() == 1) { // Qt 1.x s << g.color(QPalette::Foreground) << g.color(QPalette::Background) << g.color(QPalette::Light) << g.color(QPalette::Dark) << g.color(QPalette::Mid) << g.color(QPalette::Text) << g.color(QPalette::Base); } else { int max = QPalette::NColorRoles; if (s.version() <= QDataStream::Qt_2_1) max = QPalette::HighlightedText + 1; else if (s.version() <= QDataStream::Qt_4_3) max = QPalette::AlternateBase + 1; for(int r = 0 ; r < max ; r++) s << g.brush((QPalette::ColorRole)r); } return s; } QDataStream &qt_stream_in_qcolorgroup(QDataStream &s, QColorGroup &g) { if(s.version() == 1) { // Qt 1.x QColor fg, bg, light, dark, mid, text, base; s >> fg >> bg >> light >> dark >> mid >> text >> base; QPalette p(bg); p.setColor(QPalette::Active, QPalette::Foreground, fg); p.setColor(QPalette::Active, QPalette::Light, light); p.setColor(QPalette::Active, QPalette::Dark, dark); p.setColor(QPalette::Active, QPalette::Mid, mid); p.setColor(QPalette::Active, QPalette::Text, text); p.setColor(QPalette::Active, QPalette::Base, base); g = p; g.setCurrentColorGroup(QPalette::Active); } else { int max = QPalette::NColorRoles; if (s.version() <= QDataStream::Qt_2_1) max = QPalette::HighlightedText + 1; else if (s.version() <= QDataStream::Qt_3_0) max = QPalette::LinkVisited + 1; else if (s.version() <= QDataStream::Qt_4_3) max = QPalette::AlternateBase + 1; QBrush tmp; for(int r = 0 ; r < max; r++) { s >> tmp; g.setBrush((QPalette::ColorRole)r, tmp); } } return s; } QDataStream &operator<<(QDataStream &s, const QColorGroup &g) { return qt_stream_out_qcolorgroup(s, g); } QDataStream &operator>>(QDataStream &s, QColorGroup &g) { return qt_stream_in_qcolorgroup(s, g); } #endif /*! Constructs a palette with the specified \a active, \a disabled and \a inactive color groups. */ QPalette::QPalette(const QColorGroup &active, const QColorGroup &disabled, const QColorGroup &inactive) { Q_ASSERT(QPalette::NColorRoles == QPalette::ToolTipText + 1); init(); setColorGroup(Active, active); setColorGroup(Disabled, disabled); setColorGroup(Inactive, inactive); } QColorGroup QPalette::createColorGroup(ColorGroup cr) const { QColorGroup ret(*this); ret.setCurrentColorGroup(cr); return ret; } void QPalette::setColorGroup(ColorGroup cg, const QColorGroup &g) { setColorGroup(cg, g.brush(WindowText), g.brush(Button), g.brush(Light), g.brush(Dark), g.brush(Mid), g.brush(Text), g.brush(BrightText), g.brush(Base), g.brush(AlternateBase), g.brush(Window), g.brush(Midlight), g.brush(ButtonText), g.brush(Shadow), g.brush(Highlight), g.brush(HighlightedText), g.brush(Link), g.brush(LinkVisited), g.brush(ToolTipBase), g.brush(ToolTipText)); } #endif /*! \fn const QColor &QPalette::color(ColorRole role) const \overload Returns the color that has been set for the given color \a role in the current ColorGroup. \sa brush() ColorRole */ /*! \fn const QBrush &QPalette::brush(ColorRole role) const \overload Returns the brush that has been set for the given color \a role in the current ColorGroup. \sa color() setBrush() ColorRole */ /*! \fn void QPalette::setColor(ColorRole role, const QColor &color) \overload Sets the color used for the given color \a role, in all color groups, to the specified solid \a color. \sa brush() setColor() ColorRole */ /*! \fn void QPalette::setBrush(ColorRole role, const QBrush &brush) Sets the brush for the given color \a role to the specified \a brush for all groups in the palette. \sa brush() setColor() ColorRole */ /*! \fn const QBrush & QPalette::foreground() const \obsolete Use windowText() instead. */ /*! \fn const QBrush & QPalette::windowText() const Returns the window text (general foreground) brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::button() const Returns the button brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::light() const Returns the light brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush& QPalette::midlight() const Returns the midlight brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::dark() const Returns the dark brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::mid() const Returns the mid brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::text() const Returns the text foreground brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::brightText() const Returns the bright text foreground brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::buttonText() const Returns the button text foreground brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::base() const Returns the base brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::alternateBase() const Returns the alternate base brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::toolTipBase() const \since 4.4 Returns the tool tip base brush of the current color group. This brush is used by QToolTip and QWhatsThis. \note Tool tips use the Inactive color group of QPalette, because tool tips are not active windows. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::toolTipText() const \since 4.4 Returns the tool tip text brush of the current color group. This brush is used by QToolTip and QWhatsThis. \note Tool tips use the Inactive color group of QPalette, because tool tips are not active windows. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::background() const \obsolete Use window() instead. */ /*! \fn const QBrush & QPalette::window() const Returns the window (general background) brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::shadow() const Returns the shadow brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::highlight() const Returns the highlight brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::highlightedText() const Returns the highlighted text brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::link() const Returns the unvisited link text brush of the current color group. \sa ColorRole brush() */ /*! \fn const QBrush & QPalette::linkVisited() const Returns the visited link text brush of the current color group. \sa ColorRole brush() */ /*! \fn ColorGroup QPalette::currentColorGroup() const Returns the palette's current color group. */ /*! \fn void QPalette::setCurrentColorGroup(ColorGroup cg) Set the palette's current color group to \a cg. */ /*! \class QPalette \brief The QPalette class contains color groups for each widget state. \ingroup appearance \ingroup shared \ingroup multimedia \mainclass A palette consists of three color groups: \e Active, \e Disabled, and \e Inactive. All widgets in Qt contain a palette and use their palette to draw themselves. This makes the user interface easily configurable and easier to keep consistent. If you create a new widget we strongly recommend that you use the colors in the palette rather than hard-coding specific colors. The color groups: \list \i The Active group is used for the window that has keyboard focus. \i The Inactive group is used for other windows. \i The Disabled group is used for widgets (not windows) that are disabled for some reason. \endlist Both active and inactive windows can contain disabled widgets. (Disabled widgets are often called \e inaccessible or \e{grayed out}.) In most styles, Active and Inactive look the same. Colors and brushes can be set for particular roles in any of a palette's color groups with setColor() and setBrush(). A color group contains a group of colors used by widgets for drawing themselves. We recommend that widgets use color group roles from the palette such as "foreground" and "base" rather than literal colors like "red" or "turquoise". The color roles are enumerated and defined in the \l ColorRole documentation. We strongly recommend that you use the default palette of the current style (returned by QApplication::palette()) and modify that as necessary. This is done by Qt's widgets when they are drawn. To modify a color group you call the functions setColor() and setBrush(), depending on whether you want a pure color or a pixmap pattern. There are also corresponding color() and brush() getters, and a commonly used convenience function to get the ColorRole for the current ColorGroup: window(), windowText(), base(), etc. You can copy a palette using the copy constructor and test to see if two palettes are \e identical using isCopyOf(). QPalette is optimized by the use of \l{implicit sharing}, so it is very efficient to pass QPalette objects as arguments. \warning Some styles do not use the palette for all drawing, for instance, if they make use of native theme engines. This is the case for both the Windows XP, Windows Vista, and the Mac OS X styles. \sa QApplication::setPalette(), QWidget::setPalette(), QColor */ /*! \enum QPalette::ColorGroup \value Disabled \value Active \value Inactive \value Normal synonym for Active \omitvalue All \omitvalue NColorGroups \omitvalue Current */ /*! \enum QPalette::ColorRole \img palette.png Color Roles The ColorRole enum defines the different symbolic color roles used in current GUIs. The central roles are: \value Window A general background color. \value Background This value is obsolete. Use Window instead. \value WindowText A general foreground color. \value Foreground This value is obsolete. Use WindowText instead. \value Base Used mostly as the background color for text entry widgets, but can also be used for other painting - such as the background of combobox drop down lists and toolbar handles. It is usually white or another light color. \value AlternateBase Used as the alternate background color in views with alternating row colors (see QAbstractItemView::setAlternatingRowColors()). \value ToolTipBase Used as the background color for QToolTip and QWhatsThis. Tool tips use the Inactive color group of QPalette, because tool tips are not active windows. \value ToolTipText Used as the foreground color for QToolTip and QWhatsThis. Tool tips use the Inactive color group of QPalette, because tool tips are not active windows. \value Text The foreground color used with \c Base. This is usually the same as the \c WindowText, in which case it must provide good contrast with \c Window and \c Base. \value Button The general button background color. This background can be different from \c Window as some styles require a different background color for buttons. \value ButtonText A foreground color used with the \c Button color. \value BrightText A text color that is very different from \c WindowText, and contrasts well with e.g. \c Dark. Typically used for text that needs to be drawn where \c Text or \c WindowText would give poor contrast, such as on pressed push buttons. Note that text colors can be used for things other than just words; text colors are \e usually used for text, but it's quite common to use the text color roles for lines, icons, etc. There are some color roles used mostly for 3D bevel and shadow effects. All of these are normally derived from \c Window, and used in ways that depend on that relationship. For example, buttons depend on it to make the bevels look attractive, and Motif scroll bars depend on \c Mid to be slightly different from \c Window. \value Light Lighter than \c Button color. \value Midlight Between \c Button and \c Light. \value Dark Darker than \c Button. \value Mid Between \c Button and \c Dark. \value Shadow A very dark color. By default, the shadow color is Qt::black. Selected (marked) items have two roles: \value Highlight A color to indicate a selected item or the current item. By default, the highlight color is Qt::darkBlue. \value HighlightedText A text color that contrasts with \c Highlight. By default, the highlighted text color is Qt::white. There are two color roles related to hyperlinks: \value Link A text color used for unvisited hyperlinks. By default, the link color is Qt::blue. \value LinkVisited A text color used for already visited hyperlinks. By default, the linkvisited color is Qt::magenta. Note that we do not use the \c Link and \c LinkVisited roles when rendering rich text in Qt, and that we recommend that you use CSS and the QTextDocument::setDefaultStyleSheet() function to alter the appearance of links. For example: \snippet doc/src/snippets/textdocument-css/main.cpp 0 \value NoRole No role; this special role is often used to indicate that a role has not been assigned. \omitvalue NColorRoles */ /*! Constructs a palette object that uses the application's default palette. \sa QApplication::setPalette(), QApplication::palette() */ QPalette::QPalette() : d(QApplication::palette().d), current_group(Active), resolve_mask(0) { d->ref.ref(); } static void qt_palette_from_color(QPalette &pal, const QColor & button) { QColor bg = button, btn = button, fg, base; int h, s, v; bg.getHsv(&h, &s, &v); if(v > 128) { fg = Qt::black; base = Qt::white; } else { fg = Qt::white; base = Qt::black; } //inactive and active are the same.. pal.setColorGroup(QPalette::Active, QBrush(fg), QBrush(btn), QBrush(btn.lighter(150)), QBrush(btn.darker()), QBrush(btn.darker(150)), QBrush(fg), QBrush(Qt::white), QBrush(base), QBrush(bg)); pal.setColorGroup(QPalette::Inactive, QBrush(fg), QBrush(btn), QBrush(btn.lighter(150)), QBrush(btn.darker()), QBrush(btn.darker(150)), QBrush(fg), QBrush(Qt::white), QBrush(base), QBrush(bg)); pal.setColorGroup(QPalette::Disabled, QBrush(btn.darker()), QBrush(btn), QBrush(btn.lighter(150)), QBrush(btn.darker()), QBrush(btn.darker(150)), QBrush(btn.darker()), QBrush(Qt::white), QBrush(bg), QBrush(bg)); } /*! Constructs a palette from the \a button color. The other colors are automatically calculated, based on this color. \c Window will be the button color as well. */ QPalette::QPalette(const QColor &button) { init(); qt_palette_from_color(*this, button); } /*! Constructs a palette from the \a button color. The other colors are automatically calculated, based on this color. \c Window will be the button color as well. */ QPalette::QPalette(Qt::GlobalColor button) { init(); qt_palette_from_color(*this, button); } /*! Constructs a palette. You can pass either brushes, pixmaps or plain colors for \a windowText, \a button, \a light, \a dark, \a mid, \a text, \a bright_text, \a base and \a window. \sa QBrush */ QPalette::QPalette(const QBrush &windowText, const QBrush &button, const QBrush &light, const QBrush &dark, const QBrush &mid, const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &window) { init(); setColorGroup(All, windowText, button, light, dark, mid, text, bright_text, base, window); } /*!\obsolete Constructs a palette with the specified \a windowText, \a window, \a light, \a dark, \a mid, \a text, and \a base colors. The button color will be set to the window color. */ QPalette::QPalette(const QColor &windowText, const QColor &window, const QColor &light, const QColor &dark, const QColor &mid, const QColor &text, const QColor &base) { init(); setColorGroup(All, QBrush(windowText), QBrush(window), QBrush(light), QBrush(dark), QBrush(mid), QBrush(text), QBrush(light), QBrush(base), QBrush(window)); } /*! Constructs a palette from a \a button color and a \a window. The other colors are automatically calculated, based on these colors. */ QPalette::QPalette(const QColor &button, const QColor &window) { init(); QColor bg = window, btn = button, fg, base, disfg; int h, s, v; bg.getHsv(&h, &s, &v); if(v > 128) { fg = Qt::black; base = Qt::white; disfg = Qt::darkGray; } else { fg = Qt::white; base = Qt::black; disfg = Qt::darkGray; } //inactive and active are identical setColorGroup(Inactive, QBrush(fg), QBrush(btn), QBrush(btn.lighter(150)), QBrush(btn.darker()), QBrush(btn.darker(150)), QBrush(fg), QBrush(Qt::white), QBrush(base), QBrush(bg)); setColorGroup(Active, QBrush(fg), QBrush(btn), QBrush(btn.lighter(150)), QBrush(btn.darker()), QBrush(btn.darker(150)), QBrush(fg), QBrush(Qt::white), QBrush(base), QBrush(bg)); setColorGroup(Disabled, QBrush(disfg), QBrush(btn), QBrush(btn.lighter(150)), QBrush(btn.darker()), QBrush(btn.darker(150)), QBrush(disfg), QBrush(Qt::white), QBrush(base), QBrush(bg)); } /*! Constructs a copy of \a p. This constructor is fast thanks to \l{implicit sharing}. */ QPalette::QPalette(const QPalette &p) { d = p.d; d->ref.ref(); resolve_mask = p.resolve_mask; current_group = p.current_group; } /*! Destroys the palette. */ QPalette::~QPalette() { if(!d->ref.deref()) delete d; } /*!\internal*/ void QPalette::init() { d = new QPalettePrivate; resolve_mask = 0; current_group = Active; //as a default.. } /*! Assigns \a p to this palette and returns a reference to this palette. This operation is fast thanks to \l{implicit sharing}. */ QPalette &QPalette::operator=(const QPalette &p) { p.d->ref.ref(); resolve_mask = p.resolve_mask; current_group = p.current_group; if(!d->ref.deref()) delete d; d = p.d; return *this; } /*! Returns the palette as a QVariant */ QPalette::operator QVariant() const { return QVariant(QVariant::Palette, this); } /*! \fn const QColor &QPalette::color(ColorGroup group, ColorRole role) const Returns the color in the specified color \a group, used for the given color \a role. \sa brush() setColor() ColorRole */ /*! \fn const QBrush &QPalette::brush(ColorGroup group, ColorRole role) const Returns the brush in the specified color \a group, used for the given color \a role. \sa color() setBrush() ColorRole */ const QBrush &QPalette::brush(ColorGroup gr, ColorRole cr) const { Q_ASSERT(cr < NColorRoles); if(gr >= (int)NColorGroups) { if(gr == Current) { gr = (ColorGroup)current_group; } else { qWarning("QPalette::brush: Unknown ColorGroup: %d", (int)gr); gr = Active; } } return d->br[gr][cr]; } /*! \fn void QPalette::setColor(ColorGroup group, ColorRole role, const QColor &color) Sets the brush in the specified color \a group, used for the given color \a role, to the specified solid \a color. \sa setBrush() color() ColorRole */ /*! \fn void QPalette::setBrush(ColorGroup group, ColorRole role, const QBrush &brush) \overload Sets the brush in the specified color \a group, used for the given color \a role, to \a brush. \sa brush() setColor() ColorRole */ void QPalette::setBrush(ColorGroup cg, ColorRole cr, const QBrush &b) { Q_ASSERT(cr < NColorRoles); detach(); if(cg >= (int)NColorGroups) { if(cg == All) { for(int i = 0; i < (int)NColorGroups; i++) d->br[i][cr] = b; resolve_mask |= (1<<cr); return; } else if(cg == Current) { cg = (ColorGroup)current_group; } else { qWarning("QPalette::setBrush: Unknown ColorGroup: %d", (int)cg); cg = Active; } } d->br[cg][cr] = b; resolve_mask |= (1<<cr); } /*! \since 4.2 Returns true if the ColorGroup \a cg and ColorRole \a cr has been set previously on this palette; otherwise returns false. \sa setBrush() */ bool QPalette::isBrushSet(ColorGroup cg, ColorRole cr) const { Q_UNUSED(cg); return (resolve_mask & (1<<cr)); } /*! \internal */ void QPalette::detach() { if (d->ref != 1) { QPalettePrivate *x = new QPalettePrivate; for(int grp = 0; grp < (int)NColorGroups; grp++) { for(int role = 0; role < (int)NColorRoles; role++) x->br[grp][role] = d->br[grp][role]; } if(!d->ref.deref()) delete d; d = x; } ++d->detach_no; } /*! \fn bool QPalette::operator!=(const QPalette &p) const Returns true (slowly) if this palette is different from \a p; otherwise returns false (usually quickly). */ /*! Returns true (usually quickly) if this palette is equal to \a p; otherwise returns false (slowly). */ bool QPalette::operator==(const QPalette &p) const { if (isCopyOf(p)) return true; for(int grp = 0; grp < (int)NColorGroups; grp++) { for(int role = 0; role < (int)NColorRoles; role++) { if(d->br[grp][role] != p.d->br[grp][role]) return false; } } return true; } #ifdef QT3_SUPPORT bool QColorGroup::operator==(const QColorGroup &other) const { if (isCopyOf(other)) return true; for (int role = 0; role < int(NColorRoles); role++) { if(d->br[current_group][role] != other.d->br[other.current_group][role]) return false; } return true; } /*! Returns the color group as a QVariant */ QColorGroup::operator QVariant() const { return QVariant(QVariant::ColorGroup, this); } #endif /*! \fn bool QPalette::isEqual(ColorGroup cg1, ColorGroup cg2) const Returns true (usually quickly) if color group \a cg1 is equal to \a cg2; otherwise returns false. */ bool QPalette::isEqual(QPalette::ColorGroup group1, QPalette::ColorGroup group2) const { if(group1 >= (int)NColorGroups) { if(group1 == Current) { group1 = (ColorGroup)current_group; } else { qWarning("QPalette::brush: Unknown ColorGroup(1): %d", (int)group1); group1 = Active; } } if(group2 >= (int)NColorGroups) { if(group2 == Current) { group2 = (ColorGroup)current_group; } else { qWarning("QPalette::brush: Unknown ColorGroup(2): %d", (int)group2); group2 = Active; } } if(group1 == group2) return true; for(int role = 0; role < (int)NColorRoles; role++) { if(d->br[group1][role] != d->br[group2][role]) return false; } return true; } /*! \obsolete Returns a number that identifies the contents of this QPalette object. Distinct QPalette objects can only have the same serial number if they refer to the same contents (but they don't have to). Also, the serial number of a QPalette may change during the lifetime of the object. Use cacheKey() instead. \warning The serial number doesn't necessarily change when the palette is altered. This means that it may be dangerous to use it as a cache key. \sa operator==() */ int QPalette::serialNumber() const { return d->ser_no; } /*! Returns a number that identifies the contents of this QPalette object. Distinct QPalette objects can have the same key if they refer to the same contents. The cacheKey() will change when the palette is altered. */ qint64 QPalette::cacheKey() const { return (((qint64) d->ser_no) << 32) | ((qint64) (d->detach_no)); } /*! Returns a new QPalette that has attributes copied from \a other. */ QPalette QPalette::resolve(const QPalette &other) const { if ((*this == other && resolve_mask == other.resolve_mask) || resolve_mask == 0) { QPalette o = other; o.resolve_mask = resolve_mask; return o; } QPalette palette(*this); palette.detach(); for(int role = 0; role < (int)NColorRoles; role++) if (!(resolve_mask & (1<<role))) for(int grp = 0; grp < (int)NColorGroups; grp++) palette.d->br[grp][role] = other.d->br[grp][role]; return palette; } /*! \fn uint QPalette::resolve() const \internal */ /*! \fn void QPalette::resolve(uint mask) \internal */ /***************************************************************************** QPalette stream functions *****************************************************************************/ #ifndef QT_NO_DATASTREAM static const int NumOldRoles = 7; static const int oldRoles[7] = { QPalette::Foreground, QPalette::Background, QPalette::Light, QPalette::Dark, QPalette::Mid, QPalette::Text, QPalette::Base }; /*! \relates QPalette Writes the palette, \a p to the stream \a s and returns a reference to the stream. \sa \link datastreamformat.html Format of the QDataStream operators \endlink */ QDataStream &operator<<(QDataStream &s, const QPalette &p) { for (int grp = 0; grp < (int)QPalette::NColorGroups; grp++) { if (s.version() == 1) { // Qt 1.x for (int i = 0; i < NumOldRoles; ++i) s << p.d->br[grp][oldRoles[i]].color(); } else { int max = QPalette::ToolTipText + 1; if (s.version() <= QDataStream::Qt_2_1) max = QPalette::HighlightedText + 1; else if (s.version() <= QDataStream::Qt_4_3) max = QPalette::AlternateBase + 1; for (int r = 0; r < max; r++) s << p.d->br[grp][r]; } } return s; } static void readV1ColorGroup(QDataStream &s, QPalette &pal, QPalette::ColorGroup grp) { for (int i = 0; i < NumOldRoles; ++i) { QColor col; s >> col; pal.setColor(grp, (QPalette::ColorRole)oldRoles[i], col); } } /*! \relates QPalette Reads a palette from the stream, \a s into the palette \a p, and returns a reference to the stream. \sa \link datastreamformat.html Format of the QDataStream operators \endlink */ QDataStream &operator>>(QDataStream &s, QPalette &p) { if(s.version() == 1) { p = QPalette(); readV1ColorGroup(s, p, QPalette::Active); readV1ColorGroup(s, p, QPalette::Disabled); readV1ColorGroup(s, p, QPalette::Inactive); } else { int max = QPalette::NColorRoles; if (s.version() <= QDataStream::Qt_2_1) { p = QPalette(); max = QPalette::HighlightedText + 1; } else if (s.version() <= QDataStream::Qt_4_3) { p = QPalette(); max = QPalette::AlternateBase + 1; } QBrush tmp; for(int grp = 0; grp < (int)QPalette::NColorGroups; ++grp) { for(int role = 0; role < max; ++role) { s >> tmp; p.setBrush((QPalette::ColorGroup)grp, (QPalette::ColorRole)role, tmp); } } } return s; } #endif //QT_NO_DATASTREAM /*! Returns true if this palette and \a p are copies of each other, i.e. one of them was created as a copy of the other and neither was subsequently modified; otherwise returns false. This is much stricter than equality. \sa operator=() operator==() */ bool QPalette::isCopyOf(const QPalette &p) const { return d == p.d; } /*! Sets a the group at \a cg. You can pass either brushes, pixmaps or plain colors for \a windowText, \a button, \a light, \a dark, \a mid, \a text, \a bright_text, \a base and \a window. \sa QBrush */ void QPalette::setColorGroup(ColorGroup cg, const QBrush &windowText, const QBrush &button, const QBrush &light, const QBrush &dark, const QBrush &mid, const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &window) { QBrush alt_base = QBrush(qt_mix_colors(base.color(), button.color())); QBrush mid_light = QBrush(qt_mix_colors(button.color(), light.color())); QColor toolTipBase(255, 255, 220); QColor toolTipText(0, 0, 0); setColorGroup(cg, windowText, button, light, dark, mid, text, bright_text, base, alt_base, window, mid_light, text, QBrush(Qt::black), QBrush(Qt::darkBlue), QBrush(Qt::white), QBrush(Qt::blue), QBrush(Qt::magenta), QBrush(toolTipBase), QBrush(toolTipText)); resolve_mask &= ~(1 << Highlight); resolve_mask &= ~(1 << HighlightedText); resolve_mask &= ~(1 << LinkVisited); resolve_mask &= ~(1 << Link); } /*!\internal*/ void QPalette::setColorGroup(ColorGroup cg, const QBrush &foreground, const QBrush &button, const QBrush &light, const QBrush &dark, const QBrush &mid, const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &alternate_base, const QBrush &background, const QBrush &midlight, const QBrush &button_text, const QBrush &shadow, const QBrush &highlight, const QBrush &highlighted_text, const QBrush &link, const QBrush &link_visited) { setColorGroup(cg, foreground, button, light, dark, mid, text, bright_text, base, alternate_base, background, midlight, button_text, shadow, highlight, highlighted_text, link, link_visited, background, foreground); } /*!\internal*/ void QPalette::setColorGroup(ColorGroup cg, const QBrush &foreground, const QBrush &button, const QBrush &light, const QBrush &dark, const QBrush &mid, const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &alternate_base, const QBrush &background, const QBrush &midlight, const QBrush &button_text, const QBrush &shadow, const QBrush &highlight, const QBrush &highlighted_text, const QBrush &link, const QBrush &link_visited, const QBrush &toolTipBase, const QBrush &toolTipText) { detach(); setBrush(cg, WindowText, foreground); setBrush(cg, Button, button); setBrush(cg, Light, light); setBrush(cg, Dark, dark); setBrush(cg, Mid, mid); setBrush(cg, Text, text); setBrush(cg, BrightText, bright_text); setBrush(cg, Base, base); setBrush(cg, AlternateBase, alternate_base); setBrush(cg, Window, background); setBrush(cg, Midlight, midlight); setBrush(cg, ButtonText, button_text); setBrush(cg, Shadow, shadow); setBrush(cg, Highlight, highlight); setBrush(cg, HighlightedText, highlighted_text); setBrush(cg, Link, link); setBrush(cg, LinkVisited, link_visited); setBrush(cg, ToolTipBase, toolTipBase); setBrush(cg, ToolTipText, toolTipText); } /*! \fn QPalette QPalette::copy() const Use simple assignment instead. */ /*! \fn QColorGroup QPalette::normal() const \obsolete Returns the active color group. Use active() instead. Use createColorGroup(Active) instead. */ /*! \fn void QPalette::setNormal(const QColorGroup &colorGroup) Sets the normal color group to \a colorGroup. \sa QColorGroup */ /*! \fn QColorGroup QPalette::active() const Returns the active color group. \sa QColorGroup */ /*! \fn QColorGroup QPalette::disabled() const Returns the disabled color group. \sa QColorGroup */ /*! \fn QColorGroup QPalette::inactive() const Returns the inactive color group. \sa QColorGroup */ /*! \fn void QPalette::setActive(const QColorGroup &colorGroup) Sets the active color group to \a colorGroup. \sa QColorGroup */ /*! \fn void QPalette::setDisabled(const QColorGroup &colorGroup) Sets the disabled color group to \a colorGroup. \sa QColorGroup */ /*! \fn void QPalette::setInactive(const QColorGroup &colorGroup) Sets the inactive color group. \sa QColorGroup */ /*! \class QColorGroup \brief The QColorGroup class contains color groups for each widget state. \compat */ /*! \fn QColorGroup::QColorGroup() Use QPalette() instead. */ /*! \fn QColorGroup::QColorGroup(const QBrush &foreground, const QBrush &button, \ const QBrush &light, const QBrush &dark, const QBrush &mid, \ const QBrush &text, const QBrush &bright_text, const QBrush &base, const QBrush &background) Use QPalette(\a foreground, \a button, \a light, \a dark, \a mid, \a text, \a bright_text, \a base, \a background) instead. */ /*! \fn QColorGroup::QColorGroup(const QColor &foreground, const QColor &background, \ const QColor &light, const QColor &dark, const QColor &mid, \ const QColor &text, const QColor &base) Use QColorGroup(\a foreground, \a background, \a light, \a dark, \a mid, \a text, \a base) instead. */ /*! \fn QColorGroup::QColorGroup(const QColorGroup &other) Use QPalette(\a other) instead. */ /*! \fn QColorGroup::QColorGroup(const QPalette &pal) Use QPalette(\a pal) instead. */ /*! \fn const QColor &QColorGroup::foreground() const Use QPalette::windowText().color() instead. */ /*! \fn const QColor &QColorGroup::button() const Use QPalette::button().color() instead. */ /*! \fn const QColor &QColorGroup::light() const Use QPalette::light().color() instead. */ /*! \fn const QColor &QColorGroup::dark() const Use QPalette::dark().color() instead. */ /*! \fn const QColor &QColorGroup::mid() const Use QPalette::mid().color() instead. */ /*! \fn const QColor &QColorGroup::text() const Use QPalette::text().color() instead. */ /*! \fn const QColor &QColorGroup::base() const Use QPalette::base().color() instead. */ /*! \fn const QColor &QColorGroup::background() const Use QPalette::window().color() instead. */ /*! \fn const QColor &QColorGroup::midlight() const Use QPalette::midlight().color() instead. */ /*! \fn const QColor &QColorGroup::brightText() const Use QPalette::brightText().color() instead. */ /*! \fn const QColor &QColorGroup::buttonText() const Use QPalette::buttonText().color() instead. */ /*! \fn const QColor &QColorGroup::shadow() const Use QPalette::shadow().color() instead. */ /*! \fn const QColor &QColorGroup::highlight() const Use QPalette::highlight().color() instead. */ /*! \fn const QColor &QColorGroup::highlightedText() const Use QPalette::highlightedText().color() instead. */ /*! \fn const QColor &QColorGroup::link() const Use QPalette::link().color() instead. */ /*! \fn const QColor &QColorGroup::linkVisited() const Use QPalette::linkVisited().color() instead. */ /*! \fn QDataStream &operator<<(QDataStream &ds, const QColorGroup &colorGroup) \relates QColorGroup \compat */ /*! \fn QDataStream &operator>>(QDataStream &ds, QColorGroup &colorGroup) \relates QColorGroup \compat */ /*! \fn bool QColorGroup::operator==(const QColorGroup &other) const Returns true if this color group is equal to \a other; otherwise returns false. */ /*! \fn bool QColorGroup::operator!=(const QColorGroup &other) const Returns true if this color group is not equal to \a other; otherwise returns false. */ QT_END_NAMESPACE
lgpl-2.1
PascalLike/OSGeoLive
app-data/jupyter/static/custom/testing/history/history.js
5150
// Copyright (C) 2013 The IPython Development Team // // Distributed under the terms of the BSD License. The full license is in // the file COPYING, distributed as part of this software. //---------------------------------------------------------------------------- /* How does it work ? send each cell to a server for storing */ var ws; /* http://stackoverflow.com/questions/3231459/create-unique-id-with-javascript */ function uniqueid(){ // always start with a letter (for DOM friendlyness) var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65)); do { // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90) var ascicode=Math.floor((Math.random()*42)+48); if (ascicode<58 || ascicode>64){ // exclude all chars between : (58) and @ (64) idstr+=String.fromCharCode(ascicode); } } while (idstr.length<32); return (idstr); } /** * Called when a cell is executed * * @param {Object} event * @param {Object} current notebook cell */ var execute_cell = function (event,cell) { // create unique id if not already exists if (cell.metadata.history == undefined) { cell.metadata.history = {}; cell.metadata.history.id = uniqueid(); } // now send cell text to server var obj = { 'id' : cell.metadata.history.id , 'text' : cell.get_text() }; var str = JSON.stringify(obj); ws.send(str); }; // var pb = '<div id="container" style="width:100%; height:10px;"><div id="progressbar" style="width:'+value+'%;height:10px;background:#FFA500"></div></div>' // cell.element.prepend(pb); // div_slideshow = cell.element.find('div.slideshow'); // div_slideshow.css("background","#FFA500"); // div_slideshow.css("height","17px"); var set_progressbar = function(cell,idx,imax) { var div_history = cell.element.find('div.history'); if (div_history.length == 0) { cell.element.prepend('<div class="history"><p>Init</p></div>'); div_history = cell.element.find('div.history'); } if (idx < imax) { div_history.html('<p>'+idx+'/'+imax+'</p>'); } else { div_history.html('<p></p>'); } } /* receive update */ var update_history = function(evt) { var obj = $.parseJSON(evt.data); var cells = IPython.notebook.get_cells(); for(var i in cells) { var cell = cells[i]; if (cell.metadata.history != undefined) { if (cell.metadata.history.id == obj.id) { cell.set_text(obj.text); set_progressbar(cell,obj.idx+1, obj.imax); if (cell instanceof IPython.CodeCell) { cell.execute(); } else { cell.rendered = false; cell.render(); } IPython.notebook.dirty = true; } } } }; /** * Move one step forward in cell history * */ var history_forward = function() { var cell = IPython.notebook.get_selected_cell(); if (cell.metadata.history != undefined) { var obj = { 'id' : cell.metadata.history.id , 'action' : 'forward' }; var str = JSON.stringify(obj); ws.send(str); } }; /** * Move one step back in cell history * */ var history_back = function() { var cell = IPython.notebook.get_selected_cell(); if (cell.metadata.history != undefined) { var obj = { 'id' : cell.metadata.history.id , 'action' : 'back' }; var str = JSON.stringify(obj); ws.send(str); } }; var history_latest = function() { var cells = IPython.notebook.get_cells(); for(var i in cells) { var cell = cells[i]; if (cell.metadata.history != undefined) { var obj = { 'id' : cell.metadata.history.id , 'action' : 'latest' }; var str = JSON.stringify(obj); ws.send(str); } } }; /** * Called when a notebook is loaded * */ var init_history = function () { /* add toolbar buttons */ IPython.toolbar.add_buttons_group([ { id : 'forward', label : 'Move cell history one step forward', icon : 'ui-icon-circle-plus', callback : history_forward }, { id : 'back', label : 'Move cell history one step back', icon : 'ui-icon-circle-minus', callback : history_back }, { id : 'end', label : 'All cells to latest step', icon : 'ui-icon-arrowstep-1-e', callback : history_latest }, ]); /* connect to websocket */ ws = new WebSocket("ws://localhost:8889/websocket"); ws.onmessage = update_history }; $([IPython.events]).on('execute_cell.Notebook',execute_cell); $([IPython.events]).on('notebook_loaded.Notebook',init_history); console.log("History extension loaded correctly")
lgpl-2.1
dabrahams/0install
tests/testlaunch.py
7547
#!/usr/bin/env python from __future__ import print_function from basetest import BaseTest, StringIO, BytesIO import sys, tempfile, os, imp import unittest import logging foo_iface_uri = 'http://foo' sys.path.insert(0, '..') from zeroinstall import SafeException from zeroinstall.support import tasks from zeroinstall.injector import run, cli, namespaces, qdom, selections from zeroinstall.zerostore import Store; Store._add_with_helper = lambda *unused: False from zeroinstall.injector.requirements import Requirements from zeroinstall.injector.driver import Driver mydir = os.path.abspath(os.path.dirname(__file__)) class SilenceLogger(logging.Filter): def filter(self, record): return 0 silenceLogger = SilenceLogger() class TestLaunch(BaseTest): def run_0launch(self, args): old_stdout = sys.stdout old_stderr = sys.stderr try: sys.stdout = StringIO() sys.stderr = StringIO() ex = None try: cli.main(args) print("Finished") except NameError: raise except SystemExit: pass except TypeError: raise except AttributeError: raise except AssertionError: raise except Exception as ex2: ex = ex2 # Python 3 out = sys.stdout.getvalue() err = sys.stderr.getvalue() if ex is not None: err += str(ex.__class__) finally: sys.stdout = old_stdout sys.stderr = old_stderr return (out, err) def testHelp(self): out, err = self.run_0launch([]) assert out.lower().startswith("usage:") assert not err def testList(self): out, err = self.run_0launch(['--list']) assert not err self.assertEqual("Finished\n", out) cached_ifaces = os.path.join(self.cache_home, '0install.net', 'interfaces') os.makedirs(cached_ifaces) open(os.path.join(cached_ifaces, 'file%3a%2f%2ffoo'), 'w').close() out, err = self.run_0launch(['--list']) assert not err self.assertEqual("file://foo\nFinished\n", out) out, err = self.run_0launch(['--list', 'foo']) assert not err self.assertEqual("file://foo\nFinished\n", out) out, err = self.run_0launch(['--list', 'bar']) assert not err self.assertEqual("Finished\n", out) out, err = self.run_0launch(['--list', 'one', 'two']) assert not err assert out.lower().startswith("usage:") def testVersion(self): out, err = self.run_0launch(['--version']) assert not err assert out.startswith("0launch (zero-install)") def testInvalid(self): a = tempfile.NamedTemporaryFile() out, err = self.run_0launch(['-q', a.name]) assert err def testOK(self): out, err = self.run_0launch(['--dry-run', 'http://foo/d']) self.assertEqual("Would download 'http://foo/d'\nFinished\n", out) self.assertEqual("", err) def testRun(self): out, err = self.run_0launch(['Local.xml']) self.assertEqual("", out) assert "test-echo' does not exist" in err, err def testAbsMain(self): with tempfile.NamedTemporaryFile(prefix = 'test-', delete = False) as tmp: tmp.write(( """<?xml version="1.0" ?> <interface last-modified="1110752708" uri="%s" xmlns="http://zero-install.sourceforge.net/2004/injector/interface"> <name>Foo</name> <summary>Foo</summary> <description>Foo</description> <group main='/bin/sh'> <implementation id='.' version='1'/> </group> </interface>""" % foo_iface_uri).encode('utf-8')) driver = Driver(requirements = Requirements(tmp.name), config = self.config) try: downloaded = driver.solve_and_download_impls() if downloaded: tasks.wait_for_blocker(downloaded) run.execute_selections(driver.solver.selections, [], stores = self.config.stores) assert False except SafeException as ex: assert 'Command path must be relative' in str(ex), ex def testOffline(self): out, err = self.run_0launch(['--offline', 'http://foo/d']) self.assertEqual("Interface 'http://foo/d' has no usable implementations in the cache (and 0install is in off-line mode)\n", err) self.assertEqual("", out) def testDisplay(self): os.environ['DISPLAY'] = ':foo' out, err = self.run_0launch(['--dry-run', 'http://foo/d']) # Uses local copy of GUI assert out.startswith("Would execute: "), repr((out, err)) assert 'basetest.py' in out self.assertEqual("", err) del os.environ['DISPLAY'] out, err = self.run_0launch(['--gui']) self.assertEqual("Can't use GUI because $DISPLAY is not set\n", err) self.assertEqual("", out) def testRefreshDisplay(self): os.environ['DISPLAY'] = ':foo' out, err = self.run_0launch(['--dry-run', '--refresh', 'http://foo/d']) assert out.startswith("Would execute: ") assert 'basetest.py' in out self.assertEqual("", err) def testNeedDownload(self): os.environ['DISPLAY'] = ':foo' out, err = self.run_0launch(['--download-only', '--dry-run', 'Foo.xml']) self.assertEqual("", err) self.assertEqual("Finished\n", out) def testSelectOnly(self): os.environ['DISPLAY'] = ':foo' out, err = self.run_0launch(['--get-selections', '--select-only', 'Hello.xml']) self.assertEqual("", err) assert out.endswith("Finished\n") out = out[:-len("Finished\n")] root = qdom.parse(BytesIO(str(out).encode('utf-8'))) self.assertEqual(namespaces.XMLNS_IFACE, root.uri) sels = selections.Selections(root) sel,= sels.selections.values() self.assertEqual("sha1=3ce644dc725f1d21cfcf02562c76f375944b266a", sel.id) def testHello(self): out, err = self.run_0launch(['--dry-run', 'Foo.xml']) self.assertEqual("", err) assert out.startswith("Would execute: ") out, err = self.run_0launch(['Foo.xml']) # (Foo.xml tries to run a directory; plash gives a different error) assert "Permission denied" in err or "Is a directory" in err def testSource(self): out, err = self.run_0launch(['--dry-run', '--source', '--not-before=1', 'Source.xml']) self.assertEqual("", err) assert 'Compiler.xml' in out def testRanges(self): out, err = self.run_0launch(['--get-selections', '--before=1', '--not-before=0.2', 'Foo.xml']) assert 'tests/rpm' in out, out self.assertEqual("", err) def testLogging(self): log = logging.getLogger() log.addFilter(silenceLogger) out, err = self.run_0launch(['-v', '--list', 'UNKNOWN']) self.assertEqual(logging.INFO, log.level) out, err = self.run_0launch(['-vv', '--version']) self.assertEqual(logging.DEBUG, log.level) log.removeFilter(silenceLogger) log.setLevel(logging.WARN) def testHelp2(self): out, err = self.run_0launch(['--help']) self.assertEqual("", err) assert 'options:' in out.lower() out, err = self.run_0launch([]) self.assertEqual("", err) assert 'options:' in out.lower() def testBadFD(self): copy = os.dup(1) try: os.close(1) cli.main(['--list', 'UNKNOWN']) finally: os.dup2(copy, 1) def testShow(self): command_feed = os.path.join(mydir, 'Command.xml') out, err = self.run_0launch(['--show', command_feed]) self.assertEqual("", err) assert 'Local.xml' in out, out def testExecutables(self): # Check top-level scripts are readable (detects white-space errors) for script in ['0launch', '0alias', '0store', '0desktop', '0install']: path = os.path.join('..', script) old_stdout = sys.stdout old_stderr = sys.stderr old_argv = sys.argv try: sys.argv = [script, '--help'] sys.stderr = sys.stdout = StringIO() imp.load_source(script, path) except SystemExit as ex: out = sys.stdout.getvalue() assert 'Usage: ' in out, (script, out) else: assert False finally: sys.stdout = old_stdout sys.stderr = old_stderr sys.argv = old_argv if __name__ == '__main__': unittest.main()
lgpl-2.1
tenderlove/racc
ext/racc/cparse/extconf.rb
135
# frozen_string_literal: false # require 'mkmf' have_func('rb_block_call') have_func('rb_ary_subseq') create_makefile 'racc/cparse'
lgpl-2.1
Supporting/pmuc
src/api/vector3f.cpp
2776
/* * Plant Mock-Up Converter * * Copyright (c) 2013, EDF. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include "vector3f.h" #include <iostream> Vector3F::Vector3F() { } Vector3F::Vector3F(const float& x, const float& y, const float& z) { m_values[0] = x; m_values[1] = y; m_values[2] = z; } Vector3F::Vector3F(const Vector3F& v) { m_values[0] = v[0]; m_values[1] = v[1]; m_values[2] = v[2]; } Vector3F::Vector3F(const std::vector<float>& v) { m_values[0] = v[0]; m_values[1] = v[1]; m_values[2] = v[2]; } Vector3F Vector3F::cross(const Vector3F& v) { Vector3F d; d.m_values[0] = y() * v.z() - v.y() * z(); d.m_values[1] = z() * v.x() - v.z() * x(); d.m_values[2] = x() * v.y() - v.x() * y(); return d; } Vector3F operator-(const std::vector<float>& p1, const std::vector<float>& p2) { Vector3F d; d.m_values[0] = p1[0] - p2[0]; d.m_values[1] = p1[1] - p2[1]; d.m_values[2] = p1[2] - p2[2]; return d; } Vector3F operator-(const Vector3F& p1, const Vector3F& p2) { Vector3F d; d.m_values[0] = p1.m_values[0] - p2.m_values[0]; d.m_values[1] = p1.m_values[1] - p2.m_values[1]; d.m_values[2] = p1.m_values[2] - p2.m_values[2]; return d; } Vector3F operator+(const Vector3F& p1, const Vector3F& p2) { Vector3F d; d.m_values[0] = p1.m_values[0] + p2.m_values[0]; d.m_values[1] = p1.m_values[1] + p2.m_values[1]; d.m_values[2] = p1.m_values[2] + p2.m_values[2]; return d; } float operator*(const Vector3F& p1, const Vector3F& p2) { return p1.m_values[0] * p2.m_values[0] + p1.m_values[1] * p2.m_values[1] + p1.m_values[2] * p2.m_values[2]; } Vector3F operator*(const Vector3F& v, float f) { Vector3F r; r.m_values[0] = v.m_values[0] * f; r.m_values[1] = v.m_values[1] * f; r.m_values[2] = v.m_values[2] * f; return r; } std::ostream& operator<<(std::ostream& out, const Vector3F& vec) { out << "(" << vec.m_values[0] << ", " << vec.m_values[1] << ", " << vec.m_values[2] << ")"; return out; }
lgpl-2.1
jtalks-org/jtalks-common
jtalks-common-model/src/test/java/org/jtalks/common/model/permissions/JtalksPermissionTest.java
3001
/** * Copyright (C) 2011 JTalks.org Team * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.common.model.permissions; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import static org.testng.AssertJUnit.assertNotSame; /** * @author stanislav bashkirtsev */ public class JtalksPermissionTest { /** * Looks for all the permission classes within JTalks, reads all their constants and compares to each other making * sure that there are no duplicates (those that have the same bit mask). * * @param permissions all the permissions in the project to compare to each other * @throws Exception these are tests, who would care */ @Test(dataProvider = "allProjectPermissions") public void testNoIdenticalConstants(List<JtalksPermission> permissions) throws Exception { for (int i = 0; i < permissions.size(); i++) { for (int j = i + 1; j < permissions.size(); j++) { JtalksPermission first = permissions.get(i); JtalksPermission second = permissions.get(j); assertNotSame("Permissions with identical bit mask were encountered: " + first.getName() + " & " + second.getName(), first.getMask(), second.getMask()); } } } /** * This method looks at all the classes that contain {@link JtalksPermission}, looks up for its declared fields, * then filters out those that are not of type {@link JtalksPermission} and returns only permissions. If you * implement another such class which contains permissions, then you should add it to this method so that your class * will be tested as well. * * @return all the instances-constants of {@link JtalksPermission} from all the classes in the project */ @DataProvider(name = "allProjectPermissions") protected Object[][] getAllProjectPermissions() { List<JtalksPermission> permissions = new ArrayList<JtalksPermission>(); permissions.addAll(BranchPermission.getAllAsList()); permissions.addAll(GeneralPermission.getAllAsList()); permissions.addAll(ProfilePermission.getAllAsList()); return new Object[][]{{permissions}}; } }
lgpl-2.1
tavlima/fosstrak-reader
reader-rprm-core/src/main/java/org/fosstrak/reader/rprm/core/msg/MessageDispatcher.java
6487
/* * Copyright (C) 2007 ETH Zurich * * This file is part of Fosstrak (www.fosstrak.org). * * Fosstrak is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * Fosstrak 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 Fosstrak; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ package org.fosstrak.reader.rprm.core.msg; import org.fosstrak.reader.rprm.core.msg.command.Command; import org.fosstrak.reader.rprm.core.msg.reply.Reply; import org.apache.log4j.Logger; /** * The <code>ServiceDispatcher</code> receives plain messages in XML or TEXT format from the * <code>IncomingMessageBuffer</code>. This dispatcher then parses the messages and * passes the intermediate representation (IR) of a parsed command to the * <code>MessageDispatcher</code>. Resulting replies from the <code>MessageDispatcher</code> * are serialized into the plain message format and are sent to the * <code>OutgoingMessageDispatcher</code>.<br> * <br> * The class is a singleton. * * @author Andreas Fürer, ETH Zurich Switzerland, Winter 2005/06 */ public class MessageDispatcher extends Thread { //==================================================================== //---------------------------- Fields ------------------------------// //==================================================================== /** The clients part of the system */ private Clients clients; /** The dispatcher for all outgoing messages */ private OutgoingMessageDispatcher outMsgDispatcher; /** The logger */ private static Logger log; /** The message parser which extracts the parameters from the incomming message. */ private MessageParser parser; /** The factory creating the message parser */ private MessageFactory messageFactory; /** The service dispatcher */ private static MessageDispatcher dispatcher; /** Indicates if the thread shall be suspended. */ private boolean suspendThread = false; /** The message buffer that buffers the incoming messages. */ private IncomingMessageBuffer buffer; /** The message serializer */ private MessageSerializer serializer = null; /** Command Dispatcher which handles and dispatches the command invocations */ private static CommandDispatcher commandDispatcher = null; //==================================================================== //------------------------ Constructor -----------------------------// //==================================================================== /** * Constructs a new instance of <code>ServiceDispatcher</code>. * * @param msgLayer The <code>MessageLayer</code> holding this <code>MessageDispatcher</code>. */ private MessageDispatcher(MessageLayer msgLayer) { super(); log = Logger.getLogger(getClass().getName()); commandDispatcher = CommandDispatcher.getInstance(msgLayer); } //==================================================================== //-------------------------- Methods -------------------------------// //==================================================================== /** * Returns the single Instance of a <code>ServiceDispatcher</code>. * * @param msgLayer The <code>MessageLayer</code> holding this <code>MessageDispatcher</code>. * @return The <code>ServiceDispatcher</code>. */ public static MessageDispatcher getInstance(MessageLayer msgLayer) { if (dispatcher == null) { dispatcher = new MessageDispatcher(msgLayer); } return dispatcher; } /** * Initializes the Dispatcher. * * @param buffer the <code>IncommingMessageBuffer</code> * @param clients the clients * @param outMsgDispatcher the <code>OutgoingMessageDispatcher</code> * @exception Exception */ public void initialize(IncomingMessageBuffer buffer, Clients clients, OutgoingMessageDispatcher outMsgDispatcher) throws Exception { log.info("Initializing the dispatcher!"); this.buffer = buffer; this.clients = clients; this.outMsgDispatcher = outMsgDispatcher; this.messageFactory = MessageFactory.getInstance(); } /** * Checks <code>IncommingMessageBuffer</code> for new requests and executes them. */ public void run() { String response = null; IncomingMessage im = null; log.info("Dispatcher is now waiting for incoming messages!"); while (!suspendThread) { im = (IncomingMessage)this.buffer.get(); response = this.dispatchMessage(im); log.debug("Response message: " + response); outMsgDispatcher.sendMessage(clients.getClientID(im.getConnection()), response); } } private String dispatchMessage(IncomingMessage im) { Command command = null; Reply reply = null; String inMsg = null; String outMsg = null; MessageFormat senderMsgFormat = null; MessageFormat receiverMsgFormat = null; log.debug("dispatch message"); try { inMsg = im.getMessage(); senderMsgFormat = im.getConnection().getSenderMessageFormat(); receiverMsgFormat = im.getConnection().getReceiverMessageFormat(); parser = messageFactory.createParser(senderMsgFormat, Context.COMMAND); serializer = messageFactory.createSerializer(receiverMsgFormat, Context.COMMAND); command = (Command)parser.parseCommandMessage(inMsg); reply = commandDispatcher.dispatch(command, im); if (reply != null) { outMsg = serializer.serialize(reply); } else { outMsg = null; } } catch (MessageParsingException e) { reply = parser.createParserErrorReply(e); try { outMsg = serializer.serialize(reply); } catch (MessageSerializingException e1) { log.error("Could not create the error reply for a MessageParsingException."); } } catch (MessageSerializingException e) { log.error(e); } return outMsg; } /** * Supends the thread. */ public void suspendThread() { suspendThread = true; this.suspend(); } }
lgpl-2.1
zsoltii/dss
dss-cades/src/test/java/eu/europa/esig/dss/cades/validation/MockDataLoader.java
890
package eu.europa.esig.dss.cades.validation; import java.io.IOException; import eu.europa.esig.dss.DSSDocument; import eu.europa.esig.dss.DSSException; import eu.europa.esig.dss.FileDocument; import eu.europa.esig.dss.client.http.commons.CommonsDataLoader; import eu.europa.esig.dss.utils.Utils; public class MockDataLoader extends CommonsDataLoader { private static final long serialVersionUID = -8743201861357700742L; public MockDataLoader() { } @Override public byte[] get(final String urlString) { if (urlString.equals("https://sede.060.gob.es/politica_de_firma_anexo_1.pdf")) { DSSDocument document = new FileDocument("src/test/resources/validation/dss-728/politica_de_firma_anexo_1.pdf"); try { return Utils.toByteArray(document.openStream()); } catch (IOException e) { throw new DSSException(e); } } else { return super.get(urlString); } } }
lgpl-2.1
mono/linux-packaging-monodevelop
external/mono-addins/Mono.Addins.Setup/Mono.Addins.Setup/RepositoryReaderWriter.cs
31031
// It is automatically generated using System; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Text; using System.Collections; using System.Globalization; namespace Mono.Addins.Setup { internal class RepositoryReader : XmlSerializationReader { static readonly System.Reflection.MethodInfo fromBinHexStringMethod = typeof (XmlConvert).GetMethod ("FromBinHexString", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic, null, new Type [] {typeof (string)}, null); static byte [] FromBinHexString (string input) { return input == null ? null : (byte []) fromBinHexStringMethod.Invoke (null, new object [] {input}); } public object ReadRoot_Repository () { Reader.MoveToContent(); if (Reader.LocalName != "Repository" || Reader.NamespaceURI != "") throw CreateUnknownNodeException(); return ReadObject_Repository (true, true); } public Mono.Addins.Setup.Repository ReadObject_Repository (bool isNullable, bool checkType) { Mono.Addins.Setup.Repository ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t == null) { } else if (t.Name != "Repository" || t.Namespace != "") throw CreateUnknownTypeException(t); } ob = (Mono.Addins.Setup.Repository) Activator.CreateInstance(typeof(Mono.Addins.Setup.Repository), true); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement (); Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b0=false, b1=false, b2=false, b3=false; Mono.Addins.Setup.RepositoryEntryCollection o5; o5 = ob.@Repositories; Mono.Addins.Setup.RepositoryEntryCollection o7; o7 = ob.@Addins; int n4=0, n6=0; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "Addin" && Reader.NamespaceURI == "" && !b3) { if (((object)o7) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Setup.RepositoryEntryCollection"); o7.Add (ReadObject_PackageRepositoryEntry (false, true)); n6++; } else if (Reader.LocalName == "Repository" && Reader.NamespaceURI == "" && !b2) { if (((object)o5) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Setup.RepositoryEntryCollection"); o5.Add (ReadObject_ReferenceRepositoryEntry (false, true)); n4++; } else if (Reader.LocalName == "Name" && Reader.NamespaceURI == "" && !b0) { b0 = true; string s8 = Reader.ReadElementString (); ob.@Name = s8; } else if (Reader.LocalName == "Url" && Reader.NamespaceURI == "" && !b1) { b1 = true; string s9 = Reader.ReadElementString (); ob.@Url = s9; } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public Mono.Addins.Setup.PackageRepositoryEntry ReadObject_PackageRepositoryEntry (bool isNullable, bool checkType) { Mono.Addins.Setup.PackageRepositoryEntry ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t == null) { } else if (t.Name != "PackageRepositoryEntry" || t.Namespace != "") throw CreateUnknownTypeException(t); } ob = (Mono.Addins.Setup.PackageRepositoryEntry) Activator.CreateInstance(typeof(Mono.Addins.Setup.PackageRepositoryEntry), true); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement (); Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b10=false, b11=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "Addin" && Reader.NamespaceURI == "" && !b11) { b11 = true; ob.@Addin = ReadObject_AddinInfo (false, true); } else if (Reader.LocalName == "Url" && Reader.NamespaceURI == "" && !b10) { b10 = true; string s12 = Reader.ReadElementString (); ob.@Url = s12; } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public Mono.Addins.Setup.ReferenceRepositoryEntry ReadObject_ReferenceRepositoryEntry (bool isNullable, bool checkType) { Mono.Addins.Setup.ReferenceRepositoryEntry ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t == null) { } else if (t.Name != "ReferenceRepositoryEntry" || t.Namespace != "") throw CreateUnknownTypeException(t); } ob = (Mono.Addins.Setup.ReferenceRepositoryEntry) Activator.CreateInstance(typeof(Mono.Addins.Setup.ReferenceRepositoryEntry), true); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement (); Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b13=false, b14=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "Url" && Reader.NamespaceURI == "" && !b13) { b13 = true; string s15 = Reader.ReadElementString (); ob.@Url = s15; } else if (Reader.LocalName == "LastModified" && Reader.NamespaceURI == "" && !b14) { b14 = true; string s16 = Reader.ReadElementString (); ob.@LastModified = XmlConvert.ToDateTime (s16, XmlDateTimeSerializationMode.RoundtripKind); } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public Mono.Addins.Setup.AddinInfo ReadObject_AddinInfo (bool isNullable, bool checkType) { Mono.Addins.Setup.AddinInfo ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t == null) { } else if (t.Name != "AddinInfo" || t.Namespace != "") throw CreateUnknownTypeException(t); } ob = (Mono.Addins.Setup.AddinInfo) Activator.CreateInstance(typeof(Mono.Addins.Setup.AddinInfo), true); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement (); Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b17=false, b18=false, b19=false, b20=false, b21=false, b22=false, b23=false, b24=false, b25=false, b26=false, b27=false, b28=false, b29=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "Version" && Reader.NamespaceURI == "" && !b20) { b20 = true; string s30 = Reader.ReadElementString (); ob.@Version = s30; } else if (Reader.LocalName == "Dependencies" && Reader.NamespaceURI == "" && !b27) { if (((object)ob.@Dependencies) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Description.DependencyCollection"); if (Reader.IsEmptyElement) { Reader.Skip(); } else { int n31 = 0; Reader.ReadStartElement(); Reader.MoveToContent(); while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "AssemblyDependency" && Reader.NamespaceURI == "") { if (((object)ob.@Dependencies) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Description.DependencyCollection"); ob.@Dependencies.Add (ReadObject_AssemblyDependency (false, true)); n31++; } else if (Reader.LocalName == "NativeDependency" && Reader.NamespaceURI == "") { if (((object)ob.@Dependencies) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Description.DependencyCollection"); ob.@Dependencies.Add (ReadObject_NativeReference (false, true)); n31++; } else if (Reader.LocalName == "AddinDependency" && Reader.NamespaceURI == "") { if (((object)ob.@Dependencies) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Description.DependencyCollection"); ob.@Dependencies.Add (ReadObject_AddinReference (false, true)); n31++; } else UnknownNode (null); } else UnknownNode (null); Reader.MoveToContent(); } ReadEndElement(); } b27 = true; } else if (Reader.LocalName == "Name" && Reader.NamespaceURI == "" && !b19) { b19 = true; string s32 = Reader.ReadElementString (); ob.@Name = s32; } else if (Reader.LocalName == "BaseVersion" && Reader.NamespaceURI == "" && !b21) { b21 = true; string s33 = Reader.ReadElementString (); ob.@BaseVersion = s33; } else if (Reader.LocalName == "Id" && Reader.NamespaceURI == "" && !b17) { b17 = true; string s34 = Reader.ReadElementString (); ob.@LocalId = s34; } else if (Reader.LocalName == "Url" && Reader.NamespaceURI == "" && !b24) { b24 = true; string s35 = Reader.ReadElementString (); ob.@Url = s35; } else if (Reader.LocalName == "Copyright" && Reader.NamespaceURI == "" && !b23) { b23 = true; string s36 = Reader.ReadElementString (); ob.@Copyright = s36; } else if (Reader.LocalName == "Description" && Reader.NamespaceURI == "" && !b25) { b25 = true; string s37 = Reader.ReadElementString (); ob.@Description = s37; } else if (Reader.LocalName == "Author" && Reader.NamespaceURI == "" && !b22) { b22 = true; string s38 = Reader.ReadElementString (); ob.@Author = s38; } else if (Reader.LocalName == "OptionalDependencies" && Reader.NamespaceURI == "" && !b28) { if (((object)ob.@OptionalDependencies) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Description.DependencyCollection"); if (Reader.IsEmptyElement) { Reader.Skip(); } else { int n39 = 0; Reader.ReadStartElement(); Reader.MoveToContent(); while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "AssemblyDependency" && Reader.NamespaceURI == "") { if (((object)ob.@OptionalDependencies) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Description.DependencyCollection"); ob.@OptionalDependencies.Add (ReadObject_AssemblyDependency (false, true)); n39++; } else if (Reader.LocalName == "NativeDependency" && Reader.NamespaceURI == "") { if (((object)ob.@OptionalDependencies) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Description.DependencyCollection"); ob.@OptionalDependencies.Add (ReadObject_NativeReference (false, true)); n39++; } else if (Reader.LocalName == "AddinDependency" && Reader.NamespaceURI == "") { if (((object)ob.@OptionalDependencies) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Description.DependencyCollection"); ob.@OptionalDependencies.Add (ReadObject_AddinReference (false, true)); n39++; } else UnknownNode (null); } else UnknownNode (null); Reader.MoveToContent(); } ReadEndElement(); } b28 = true; } else if (Reader.LocalName == "Properties" && Reader.NamespaceURI == "" && !b29) { if (((object)ob.@Properties) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Setup.AddinPropertyCollectionImpl"); if (Reader.IsEmptyElement) { Reader.Skip(); } else { int n40 = 0; Reader.ReadStartElement(); Reader.MoveToContent(); while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "Property" && Reader.NamespaceURI == "") { if (((object)ob.@Properties) == null) throw CreateReadOnlyCollectionException ("Mono.Addins.Setup.AddinPropertyCollectionImpl"); ob.@Properties.Add (ReadObject_AddinProperty (false, true)); n40++; } else UnknownNode (null); } else UnknownNode (null); Reader.MoveToContent(); } ReadEndElement(); } b29 = true; } else if (Reader.LocalName == "Namespace" && Reader.NamespaceURI == "" && !b18) { b18 = true; string s41 = Reader.ReadElementString (); ob.@Namespace = s41; } else if (Reader.LocalName == "Category" && Reader.NamespaceURI == "" && !b26) { b26 = true; string s42 = Reader.ReadElementString (); ob.@Category = s42; } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public Mono.Addins.Description.AssemblyDependency ReadObject_AssemblyDependency (bool isNullable, bool checkType) { Mono.Addins.Description.AssemblyDependency ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t == null) { } else if (t.Name != "AssemblyDependency" || t.Namespace != "") throw CreateUnknownTypeException(t); } ob = (Mono.Addins.Description.AssemblyDependency) Activator.CreateInstance(typeof(Mono.Addins.Description.AssemblyDependency), true); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement (); Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b43=false, b44=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "Package" && Reader.NamespaceURI == "" && !b44) { b44 = true; string s45 = Reader.ReadElementString (); ob.@Package = s45; } else if (Reader.LocalName == "FullName" && Reader.NamespaceURI == "" && !b43) { b43 = true; string s46 = Reader.ReadElementString (); ob.@FullName = s46; } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } #pragma warning disable CS0612 // Type or member is obsolete public Mono.Addins.Description.NativeDependency ReadObject_NativeReference (bool isNullable, bool checkType) { Mono.Addins.Description.NativeDependency ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t == null) { } else if (t.Name != "NativeReference" || t.Namespace != "") throw CreateUnknownTypeException(t); } ob = (Mono.Addins.Description.NativeDependency) Activator.CreateInstance(typeof(Mono.Addins.Description.NativeDependency), true); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement (); Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { UnknownNode (ob); } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } #pragma warning restore CS0612 // Type or member is obsolete public Mono.Addins.Description.AddinDependency ReadObject_AddinReference (bool isNullable, bool checkType) { Mono.Addins.Description.AddinDependency ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t == null) { } else if (t.Name != "AddinReference" || t.Namespace != "") throw CreateUnknownTypeException(t); } ob = (Mono.Addins.Description.AddinDependency) Activator.CreateInstance(typeof(Mono.Addins.Description.AddinDependency), true); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement (); Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b47=false, b48=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "Version" && Reader.NamespaceURI == "" && !b48) { b48 = true; string s49 = Reader.ReadElementString (); ob.@Version = s49; } else if (Reader.LocalName == "AddinId" && Reader.NamespaceURI == "" && !b47) { b47 = true; string s50 = Reader.ReadElementString (); ob.@AddinId = s50; } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public Mono.Addins.Description.AddinProperty ReadObject_AddinProperty (bool isNullable, bool checkType) { Mono.Addins.Description.AddinProperty ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t == null) { } else if (t.Name != "AddinProperty" || t.Namespace != "") throw CreateUnknownTypeException(t); } ob = (Mono.Addins.Description.AddinProperty) Activator.CreateInstance(typeof(Mono.Addins.Description.AddinProperty), true); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.@Name = Reader.Value; } else if (Reader.LocalName == "locale" && Reader.NamespaceURI == "") { ob.@Locale = Reader.Value; } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement (); Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { UnknownNode (ob); } else if (Reader.NodeType == System.Xml.XmlNodeType.Text || Reader.NodeType == System.Xml.XmlNodeType.CDATA) { ob.@Value = ReadString (ob.@Value); } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } protected override void InitCallbacks () { } protected override void InitIDs () { } } internal class RepositoryWriter : XmlSerializationWriter { const string xmlNamespace = "http://www.w3.org/2000/xmlns/"; static readonly System.Reflection.MethodInfo toBinHexStringMethod = typeof (XmlConvert).GetMethod ("ToBinHexString", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic, null, new Type [] {typeof (byte [])}, null); static string ToBinHexString (byte [] input) { return input == null ? null : (string) toBinHexStringMethod.Invoke (null, new object [] {input}); } public void WriteRoot_Repository (object o) { WriteStartDocument (); Mono.Addins.Setup.Repository ob = (Mono.Addins.Setup.Repository) o; TopLevelElement (); WriteObject_Repository (ob, "Repository", "", true, false, true); } void WriteObject_Repository (Mono.Addins.Setup.Repository ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (((object)ob) == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } System.Type type = ob.GetType (); if (type == typeof(Mono.Addins.Setup.Repository)) { } else { throw CreateUnknownTypeException (ob); } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("Repository", ""); WriteElementString ("Name", "", ob.@Name); WriteElementString ("Url", "", ob.@Url); if (ob.@Repositories != null) { for (int n51 = 0; n51 < ob.@Repositories.Count; n51++) { WriteObject_ReferenceRepositoryEntry (((Mono.Addins.Setup.ReferenceRepositoryEntry) ob.@Repositories[n51]), "Repository", "", false, false, true); } } if (ob.@Addins != null) { for (int n52 = 0; n52 < ob.@Addins.Count; n52++) { WriteObject_PackageRepositoryEntry (((Mono.Addins.Setup.PackageRepositoryEntry) ob.@Addins[n52]), "Addin", "", false, false, true); } } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_ReferenceRepositoryEntry (Mono.Addins.Setup.ReferenceRepositoryEntry ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (((object)ob) == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } System.Type type = ob.GetType (); if (type == typeof(Mono.Addins.Setup.ReferenceRepositoryEntry)) { } else { throw CreateUnknownTypeException (ob); } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("ReferenceRepositoryEntry", ""); WriteElementString ("Url", "", ob.@Url); WriteElementString ("LastModified", "", XmlConvert.ToString (ob.@LastModified, XmlDateTimeSerializationMode.RoundtripKind)); if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_PackageRepositoryEntry (Mono.Addins.Setup.PackageRepositoryEntry ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (((object)ob) == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } System.Type type = ob.GetType (); if (type == typeof(Mono.Addins.Setup.PackageRepositoryEntry)) { } else { throw CreateUnknownTypeException (ob); } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("PackageRepositoryEntry", ""); WriteElementString ("Url", "", ob.@Url); WriteObject_AddinInfo (ob.@Addin, "Addin", "", false, false, true); if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_AddinInfo (Mono.Addins.Setup.AddinInfo ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (((object)ob) == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } System.Type type = ob.GetType (); if (type == typeof(Mono.Addins.Setup.AddinInfo)) { } else { throw CreateUnknownTypeException (ob); } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("AddinInfo", ""); WriteElementString ("Id", "", ob.@LocalId); WriteElementString ("Namespace", "", ob.@Namespace); WriteElementString ("Name", "", ob.@Name); WriteElementString ("Version", "", ob.@Version); WriteElementString ("BaseVersion", "", ob.@BaseVersion); WriteElementString ("Author", "", ob.@Author); WriteElementString ("Copyright", "", ob.@Copyright); WriteElementString ("Url", "", ob.@Url); WriteElementString ("Description", "", ob.@Description); WriteElementString ("Category", "", ob.@Category); if (ob.@Dependencies != null) { WriteStartElement ("Dependencies", "", ob.@Dependencies); for (int n53 = 0; n53 < ob.@Dependencies.Count; n53++) { if (((object)ob.@Dependencies[n53]) == null) { } else if (ob.@Dependencies[n53].GetType() == typeof(Mono.Addins.Description.AssemblyDependency)) { WriteObject_AssemblyDependency (((Mono.Addins.Description.AssemblyDependency) ob.@Dependencies[n53]), "AssemblyDependency", "", false, false, true); } #pragma warning disable CS0612 // Type or member is obsolete else if (ob.@Dependencies[n53].GetType() == typeof(Mono.Addins.Description.NativeDependency)) { WriteObject_NativeReference (((Mono.Addins.Description.NativeDependency) ob.@Dependencies[n53]), "NativeDependency", "", false, false, true); } #pragma warning restore CS0612 // Type or member is obsolete else if (ob.@Dependencies[n53].GetType() == typeof(Mono.Addins.Description.AddinDependency)) { WriteObject_AddinReference (((Mono.Addins.Description.AddinDependency) ob.@Dependencies[n53]), "AddinDependency", "", false, false, true); } else throw CreateUnknownTypeException (ob.@Dependencies[n53]); } WriteEndElement (ob.@Dependencies); } if (ob.@OptionalDependencies != null) { WriteStartElement ("OptionalDependencies", "", ob.@OptionalDependencies); for (int n54 = 0; n54 < ob.@OptionalDependencies.Count; n54++) { if (((object)ob.@OptionalDependencies[n54]) == null) { } else if (ob.@OptionalDependencies[n54].GetType() == typeof(Mono.Addins.Description.AssemblyDependency)) { WriteObject_AssemblyDependency (((Mono.Addins.Description.AssemblyDependency) ob.@OptionalDependencies[n54]), "AssemblyDependency", "", false, false, true); } #pragma warning disable CS0612 // Type or member is obsolete else if (ob.@OptionalDependencies[n54].GetType() == typeof(Mono.Addins.Description.NativeDependency)) { WriteObject_NativeReference (((Mono.Addins.Description.NativeDependency) ob.@OptionalDependencies[n54]), "NativeDependency", "", false, false, true); } #pragma warning restore CS0612 // Type or member is obsolete else if (ob.@OptionalDependencies[n54].GetType() == typeof(Mono.Addins.Description.AddinDependency)) { WriteObject_AddinReference (((Mono.Addins.Description.AddinDependency) ob.@OptionalDependencies[n54]), "AddinDependency", "", false, false, true); } else throw CreateUnknownTypeException (ob.@OptionalDependencies[n54]); } WriteEndElement (ob.@OptionalDependencies); } if (ob.@Properties != null) { WriteStartElement ("Properties", "", ob.@Properties); for (int n55 = 0; n55 < ob.@Properties.Count; n55++) { WriteObject_AddinProperty (ob.@Properties[n55], "Property", "", false, false, true); } WriteEndElement (ob.@Properties); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_AssemblyDependency (Mono.Addins.Description.AssemblyDependency ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (((object)ob) == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } System.Type type = ob.GetType (); if (type == typeof(Mono.Addins.Description.AssemblyDependency)) { } else { throw CreateUnknownTypeException (ob); } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("AssemblyDependency", ""); WriteElementString ("FullName", "", ob.@FullName); WriteElementString ("Package", "", ob.@Package); if (writeWrappingElem) WriteEndElement (ob); } #pragma warning disable CS0612 // Type or member is obsolete void WriteObject_NativeReference (Mono.Addins.Description.NativeDependency ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (((object)ob) == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } System.Type type = ob.GetType (); if (type == typeof(Mono.Addins.Description.NativeDependency)) { } else { throw CreateUnknownTypeException (ob); } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("NativeReference", ""); if (writeWrappingElem) WriteEndElement (ob); } #pragma warning restore CS0612 // Type or member is obsolete void WriteObject_AddinReference (Mono.Addins.Description.AddinDependency ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (((object)ob) == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } System.Type type = ob.GetType (); if (type == typeof(Mono.Addins.Description.AddinDependency)) { } else { throw CreateUnknownTypeException (ob); } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("AddinReference", ""); WriteElementString ("AddinId", "", ob.@AddinId); WriteElementString ("Version", "", ob.@Version); if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_AddinProperty (Mono.Addins.Description.AddinProperty ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (((object)ob) == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } System.Type type = ob.GetType (); if (type == typeof(Mono.Addins.Description.AddinProperty)) { } else { throw CreateUnknownTypeException (ob); } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("AddinProperty", ""); WriteAttribute ("name", "", ob.@Name); WriteAttribute ("locale", "", ob.@Locale); WriteValue (ob.@Value); if (writeWrappingElem) WriteEndElement (ob); } protected override void InitCallbacks () { } } }
lgpl-2.1
poppogbr/genropy
dojo_libs/dojo_11/dojo/dojox/charting/plot2d/Markers.js
621
/* Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved. Licensed under the Academic Free License version 2.1 or above OR the modified BSD license. For more information on Dojo licensing, see: http://dojotoolkit.org/book/dojo-book-0-9/introduction/licensing */ if(!dojo._hasResource["dojox.charting.plot2d.Markers"]){ dojo._hasResource["dojox.charting.plot2d.Markers"]=true; dojo.provide("dojox.charting.plot2d.Markers"); dojo.require("dojox.charting.plot2d.Default"); dojo.declare("dojox.charting.plot2d.Markers",dojox.charting.plot2d.Default,{constructor:function(){ this.opt.markers=true; }}); }
lgpl-2.1
webbfontaine/josso1
agents/josso-php-agent/src/main/php/josso-php-agent/autologin/class.bot_automatic_login_strategy.php
6334
<?php /** * PHP Bot automatic login class definition. */ /** JOSSO: Java Open Single Sign-On Copyright 2004-2009, Atricore, Inc. This is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 this software; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ require_once('class.abstract_automatic_login_strategy.php'); require_once('class.robot.php'); /** * PHP Bot automatic login strategy implementation. * This will not require an automatic login when a bot is crawling the site. * @package org.josso.agent.php */ class bot_automatic_login_strategy extends abstract_automatic_login_strategy { /** * Robots file path. * * @var string * @access private */ var $botsFile; /** * Robots. * * @var array * @access private */ var $bots; /** * Constructor * * @access public */ function bot_automatic_login_strategy() { } /** * Componenets must evaluate if automatic login is required for the received request. * * @return true if automatic login is required, false otherwise */ function isAutomaticLoginRequired() { if (!isset($this->bots)) { $this->loadRobots(); } $userAgent = $_SERVER['HTTP_USER_AGENT']; if (isset($this->bots[$userAgent])) { return FALSE; } return TRUE; } /** * Load robots from the file. */ function loadRobots() { $this->bots = array(); $robot = new robot(); if (file_exists($this->botsFile) && is_readable($this->botsFile)) { $file_handle = fopen($this->botsFile, 'r'); while (!feof($file_handle)) { $line = fgets($file_handle); if (isset($line) && trim($line) != '') { if ($this->startsWith($line, 'robot-') || $this->startsWith($line, 'modified-')) { $separatorIndex = strpos($line, ':'); $name = substr($line, 0, $separatorIndex); $value = trim(substr($line, $separatorIndex + 1)); $this->setRobotProperty($robot, $name, $value, FALSE); } else { $this->setRobotProperty($robot, $name, $line, TRUE); } } else { $this->bots[$robot->getUserAgent()] = $robot; $robot = new robot(); $name = null; $value = null; } } fclose($file_handle); } } /** * Sets robot property value. * * @param robot $robot robot * @param string $name property name * @param string $value property value * @param boolean $append true if value should be appended to existing value, false otherwise */ function setRobotProperty($robot, $name, $value, $append) { if (!isset($robot) || !isset($name) || !isset($value)) { return; } $value = trim($value); if ($this->startsWith($name, 'robot-id')) { $robot->setId($value); } else if ($this->startsWith($name, 'robot-name')) { $robot->setName($value); } else if ($this->startsWith($name, 'robot-cover-url')) { $robot->setCoverUrl($value); } else if ($this->startsWith($name, 'robot-details-url')) { $robot->setDetailsUrl($value); } else if ($this->startsWith($name, 'robot-owner-name')) { $robot->setOwnerName($value); } else if ($this->startsWith($name, 'robot-owner-url')) { $robot->setOwnerUrl($value); } else if ($this->startsWith($name, 'robot-owner-email')) { $robot->setOwnerEmail($value); } else if ($this->startsWith($name, 'robot-status')) { $robot->setStatus($value); } else if ($this->startsWith($name, 'robot-purpose')) { $robot->setPurpose($value); } else if ($this->startsWith($name, 'robot-type')) { $robot->setType($value); } else if ($this->startsWith($name, 'robot-platform')) { $robot->setPlatform($value); } else if ($this->startsWith($name, 'robot-availability')) { $robot->setAvailability($value); } else if ($this->startsWith($name, 'robot-exclusion-useragent')) { $robot->setExclusionUserAgent($value); } else if ($this->startsWith($name, 'robot-exclusion')) { $robot->setExclusion($value); } else if ($this->startsWith($name, 'robot-noindex')) { $robot->setNoindex($value); } else if ($this->startsWith($name, 'robot-host')) { $robot->setHost($value); } else if ($this->startsWith($name, 'robot-from')) { $robot->setFrom($value); } else if ($this->startsWith($name, 'robot-useragent')) { $robot->setUserAgent($value); } else if ($this->startsWith($name, 'robot-language')) { $robot->setLanguage($value); } else if ($this->startsWith($name, 'robot-description')) { $description = $robot->getDescription(); if (append && isset($description)) { $robot->setDescription($description . ' ' . $value); } else { $robot->setDescription($value); } } else if ($this->startsWith($name, 'robot-history')) { $history = $robot->getHistory(); if (append && isset($history)) { $robot->setHistory($history . ' ' . $value); } else { $robot->setHistory($value); } } else if ($this->startsWith($name, 'robot-environment')) { $robot->setEnvironment($value); } else if ($this->startsWith($name, 'modified-date')) { $robot->setModifiedDate($value); } else if ($this->startsWith($name, 'modified-by')) { $robot->setModifiedBy($value); } } function startsWith($haystack,$needle,$case=true) { if ($case) { return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0); } return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0); } /** * @return string bots file * * @access public */ function getBotsFile() { return $this->botsFile; } /** * @param string $botsFile the bots file to set * * @access public */ function setBotsFile($botsFile) { $this->botsFile = $botsFile; } } ?>
lgpl-2.1
karansapra/OpenDwarfs
finite-state-machine/tdm/dataio.cpp
3403
#include "dataio.h" #include "global.h" #include <stdio.h> #include <stdlib.h> char symbolToChar( char l, int n ) { return (l - 'a')*8 + (n-1) + '!'; } void charToSymbol( char c, char& l, int& n ) { n = (c-'!')%8+1; l = (c-'!'-(n-1))/8 + 'a'; } unsigned int countLinesInFile( char* filename ) { int ch, prev = '\n' /* so empty files have no lines */, lines = 0; FILE* file = fopen( filename, "r" ); // Count lines, each line is an symbol/timestamp pair // Retrieved from http://www.daniweb.com/code/snippet325.html // Author: Dave Sinkula if ( file ) { while ( (ch = fgetc(file)) != EOF ) /* Read all chars in the file. */ { if ( ch == '\n' ) { ++lines; /* Bump the counter for every newline. */ } prev = ch; /* Keep a copy to later test whether... */ } fclose(file); if ( prev != '\n' ) /* ...the last line did not end in a newline. */ { ++lines; /* If so, add one more to the total. */ } } return lines; } void loadTemporalConstraints(char* filename, float** constraints, unsigned int* constraintCount) { FILE* temporalFile; uint count = countLinesInFile(filename); temporalFile = fopen( filename, "r" ); if ( !temporalFile ) { printf("ERROR: %s does not exist.\n", filename); return; } float* tc = (float*)malloc(count*2*sizeof(float)); //printf("Count: %d\n", count); for ( uint idx = 0; idx < count; idx++ ) { fscanf( temporalFile, "%f %f\n", &tc[2*idx+0], &tc[2*idx+1] ); } fclose(temporalFile); *constraints = tc; *constraintCount = count; } void loadData(char* filename, ubyte** events, float** times, uint* eventCount, uint* eventType, uint* uniqueEvents) { FILE* eventFile; uint eventSize; *eventCount = eventSize = countLinesInFile(filename); eventFile = fopen( filename, "r" ); *events = (ubyte*)malloc(eventSize * sizeof(ubyte)); *times = (float*)malloc(eventSize * sizeof(float)); // test file for one or two-char inputs char c1, c2; fscanf( eventFile, "%c%c", &c1, &c2 ); if ( c2 == ',' ) { *eventType = EVENT_26; *uniqueEvents = 26; } else { *eventType = EVENT_64; *uniqueEvents = 64; } rewind( eventFile ); char symbol = 0; char c; int v; float time = 0; for ( uint idx = 0; idx < eventSize; idx++ ) { if ( *eventType == EVENT_26 ) fscanf( eventFile, "%c,%f\n", &symbol, &time ); else { fscanf( eventFile, "%c%d,%f\n", &c, &v, &time ); symbol = symbolToChar( c, v ); } (*events)[idx] = symbol; (*times)[idx] = time; } fclose( eventFile ); } void saveResult(FILE* dumpFile, int level, uint episodes, uint* support, ubyte* candidates, float* intervals, uint eventType) { fprintf( dumpFile, "-----------------------\nEpisodes of size = %d\n-----------------------\n", level ); unsigned int newcount = 0; char c; int v; for ( int idx = 0; idx < episodes; idx++ ) { newcount++; for ( int levelIdx = 0; levelIdx < level; levelIdx++ ) { if ( levelIdx > 0 ) { fprintf(dumpFile, "-[%f,%f]-", intervals[idx*(level-1)*2+levelIdx*2+0], intervals[idx*(level-1)*2+levelIdx*2+1]); } if ( eventType == EVENT_26 ) fprintf( dumpFile, "%c", candidates[idx*level+levelIdx] ); else { charToSymbol( candidates[idx*level+levelIdx], c, v ); fprintf( dumpFile, "%c%d", c, v ); } } fprintf( dumpFile, ": %d\n", support[idx]); } fprintf( dumpFile, "No. of %d node frequent episodes = %d\n\n", level, newcount); }
lgpl-2.1
krafczyk/spack
var/spack/repos/builtin/packages/pacbio-daligner/package.py
2025
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser 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 ############################################################################## from spack import * class PacbioDaligner(MakefilePackage): """Daligner: The Dazzler "Overlap" Module. This is a special fork required for some pacbio utilities.""" homepage = "https://github.com/PacificBiosciences/DALIGNER" git = "https://github.com/PacificBiosciences/DALIGNER.git" version('2017-08-05', commit='0fe5240d2cc6b55bf9e04465b700b76110749c9d') depends_on('gmake', type='build') depends_on('pacbio-dazz-db') def edit(self, spec, prefix): mkdir(prefix.bin) makefile = FileFilter('Makefile') makefile.filter('DEST_DIR\s*=\s*~/bin', 'DEST_DIR = ' + prefix.bin) gmf = FileFilter('GNUmakefile') gmf.filter('rsync\s*-av\s*\$\{ALL\}\s*\$\{PREFIX\}/bin', 'cp ${ALL} ' + prefix.bin)
lgpl-2.1
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/tool/schema/spi/ScriptSourceInput.java
971
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.tool.schema.spi; import java.util.List; import org.hibernate.tool.hbm2ddl.ImportSqlCommandExtractor; /** * Contract for hiding the differences between a passed Reader, File or URL in terms of how we read input * scripts. * * @author Steve Ebersole */ public interface ScriptSourceInput { /** * Prepare source for use. */ void prepare(); /** * Read the abstracted script, using the given extractor to split up the input into individual commands. * * @param commandExtractor The extractor for individual commands within the input. * * @return The scripted commands */ List<String> read(ImportSqlCommandExtractor commandExtractor); /** * Release this input. */ void release(); }
lgpl-2.1
likuolin/ib-ruby
spec/gw.rb
89
puts 'To run specs against the Gateway port, use:' puts '$ rspec -rgw spec' PORT = 4002
lgpl-2.1
jbarriosc/ACSUFRO
LGPL/CommonSoftware/bulkDataNT/src/bulkDataNTSenderImpl.cpp
11453
/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <ACS_BD_ErrorsC.h> #include <ACSBulkDataError.h> // error definition ?? #include <Tokenizer_T.h> #include "bulkDataNTSenderFlow.h" #include "bulkDataNTSenderImpl.h" using namespace ACS_BD_Errors; BulkDataNTSenderImpl::BulkDataNTSenderImpl(const ACE_CString& name,maci::ContainerServices* containerServices): CharacteristicComponentImpl(name,containerServices), parser_m(0), defaultFlowsCount_m(-1) { ACS_TRACE("BulkDataNTSenderImpl::BulkDataNTSenderImpl"); } BulkDataNTSenderImpl::~BulkDataNTSenderImpl() { ACS_TRACE("BulkDataNTSenderImpl::~BulkDataNTSenderImpl"); delete parser_m; } void BulkDataNTSenderImpl::initialize() { AUTO_TRACE(__PRETTY_FUNCTION__); CharacteristicComponentImpl::initialize(); // Read the configuration from the CDB and parse it as necessary // This code has been copy/pasted from bulkDataNTReceiverImpl.i, so // it could probably be shared char buf[BUFSIZ]; // get the DAO and read the alma/ branch of the component out from the CDB CDB::DAL_ptr dal_p = getContainerServices()->getCDB(); if(CORBA::is_nil(dal_p)) { ACS_SHORT_LOG((LM_ERROR,"BulkDataNTSenderImpl::initialize error getting DAL reference")); ACSBulkDataError::AVOpenReceiverErrorExImpl err = ACSBulkDataError::AVOpenReceiverErrorExImpl(__FILE__,__LINE__,"BulkDataNTSenderImpl::initialize"); throw err.getAVOpenReceiverErrorEx(); } ACE_CString CDBpath="alma/"; CDBpath += name(); CDB::DAO_ptr dao_p = dal_p->get_DAO_Servant(CDBpath.c_str()); if(CORBA::is_nil(dao_p)) { ACS_SHORT_LOG((LM_ERROR,"BulkDataNTSenderImpl::initialize error getting DAO reference")); ACSBulkDataError::AVOpenReceiverErrorExImpl err = ACSBulkDataError::AVOpenReceiverErrorExImpl(__FILE__,__LINE__,"BulkDataNTSenderImpl::initialize"); throw err.getAVOpenReceiverErrorEx(); } // Check which kind of configuration we have (the old "TCP"-based one, or the new schema-based one) char *sender_protocols = 0; bool useNewConfigMechanism = false; try { sender_protocols = dao_p->get_string("sender_protocols"); ACE_OS::strcpy(buf,sender_protocols); // TODO: put log saying that old config mechanism is going to be used instead of the new one } catch(cdbErrType::CDBFieldDoesNotExistEx &ex) { useNewConfigMechanism = true; } if( useNewConfigMechanism ) { // Use the new mechanism to parse the XML document and create the streams/flows char *xmlNode = dal_p->get_DAO(CDBpath.c_str()); try { // Parse the XML document and check if we got any configuration object parser_m = new AcsBulkdata::BulkDataConfigurationParser(name()); parser_m->parseSenderConfig(xmlNode); if( parser_m->getAllSenderStreamNames().size() == 0 ) ACS_SHORT_LOG((LM_NOTICE,"BulkDataNTSenderImpl::initialize No Sender Streams configured, streams created in the future will have a default configuration")); } catch(CDBProblemExImpl &ex) { ACSBulkDataError::AVOpenReceiverErrorExImpl err = ACSBulkDataError::AVOpenReceiverErrorExImpl(ex,__FILE__,__LINE__,"BulkDataNTSenderImpl::initialize"); err.log(LM_DEBUG); throw err.getAVOpenReceiverErrorEx(); } catch(...) { ACSErrTypeCommon::UnknownExImpl ex = ACSErrTypeCommon::UnknownExImpl(__FILE__,__LINE__,"BulkDataNTSenderImpl::initialize"); ACSBulkDataError::AVOpenReceiverErrorExImpl err = ACSBulkDataError::AVOpenReceiverErrorExImpl(ex,__FILE__,__LINE__,"BulkDataNTSenderImpl::initialize"); err.log(LM_DEBUG); throw err.getAVOpenReceiverErrorEx(); } } else { // Use the old mechanism and remember the number of flows try { // Create default config objects for the stream and the necessary flows if(ACE_OS::strcmp(buf, "") != 0) { ACE_Tokenizer addressToken(buf); addressToken.delimiter('/'); defaultFlowsCount_m = 0; while( addressToken.next() != 0 ) defaultFlowsCount_m++; // TODO: Does this "> 19" condition make any sense? if( defaultFlowsCount_m < 0 || defaultFlowsCount_m > 19 ) { ACS_SHORT_LOG((LM_ERROR, "BulkDataNTSenderImpl::initialize too many flows specified - maximum 19")); ACSBulkDataError::AVInvalidFlowNumberExImpl err = ACSBulkDataError::AVInvalidFlowNumberExImpl(__FILE__,__LINE__,"BulkDataNTSenderImpl::initialize"); throw err; } } } catch(ACSErr::ACSbaseExImpl &ex) { ACSBulkDataError::AVOpenReceiverErrorExImpl err = ACSBulkDataError::AVOpenReceiverErrorExImpl(ex,__FILE__,__LINE__,"BulkDataNTSenderImpl::initialize"); err.log(LM_DEBUG); throw err.getAVOpenReceiverErrorEx(); } catch(...) { ACSErrTypeCommon::UnknownExImpl ex = ACSErrTypeCommon::UnknownExImpl(__FILE__,__LINE__,"BulkDataNTSenderImpl::initialize"); ACSBulkDataError::AVOpenReceiverErrorExImpl err = ACSBulkDataError::AVOpenReceiverErrorExImpl(ex,__FILE__,__LINE__,"BulkDataNTSenderImpl::initialize"); throw err.getAVOpenReceiverErrorEx(); } } // if (useNewConfigMechanism) } void BulkDataNTSenderImpl::cleanUp() { disconnect(); } bool BulkDataNTSenderImpl::usesOldConfigurationMechanism() { return (parser_m == 0); } void BulkDataNTSenderImpl::connect(bulkdata::BulkDataReceiver_ptr receiverObj_p) { ACS_TRACE("BulkDataNTSenderImpl::connect - deprecated"); // check if initialize has been called if( parser_m == 0 && defaultFlowsCount_m == -1 ) { acsErrTypeLifeCycle::LifeCycleExImpl lcEx = acsErrTypeLifeCycle::LifeCycleExImpl(__FILE__,__LINE__,__PRETTY_FUNCTION__); lcEx.log(LM_DEBUG); throw lcEx.getacsErrTypeLifeCycleEx(); } // Here we currently open all senders, new methods might be added later to the IDL interface openSenders(); }//connect void BulkDataNTSenderImpl::openSenders() { ACS_TRACE(__PRETTY_FUNCTION__); try { // With the old config mechanism only one stream, namely "DefaultStream", is allowed if( usesOldConfigurationMechanism() ) { if( senderStreams_m.find("DefaultStream") != senderStreams_m.end() ) return; ACS_SHORT_LOG((LM_NOTICE,"BulkDataNTSenderImpl::openSenders Opening sender stream 'DefaultStream' with '%d' flows", defaultFlowsCount_m)); AcsBulkdata::BulkDataNTSenderStream* stream = createDefaultSenderStream(); senderStreams_m["DefaultStream"] = stream; return; } // With the new configuration mechanism check all the configured sender streams // and open them all (if not already opened) std::set<const char *> streamNames = parser_m->getAllSenderStreamNames(); std::set<const char *>::iterator it; for(it = streamNames.begin(); it != streamNames.end(); it++) { // Double check that we don't re-create existing streams if( senderStreams_m.find(*it) != senderStreams_m.end() ) continue; ACS_SHORT_LOG((LM_INFO,"BulkDataNTSenderImpl::openSenders Opening sender stream '%s' with configuration from CDB", *it)); AcsBulkdata::BulkDataNTSenderStream* stream = createSenderStream(*it); senderStreams_m[*it] = stream; } } catch(StreamCreateProblemExImpl &ex) { ACSBulkDataError::AVOpenReceiverErrorExImpl err = ACSBulkDataError::AVOpenReceiverErrorExImpl(ex,__FILE__,__LINE__,__PRETTY_FUNCTION__); err.log(LM_DEBUG); throw err.getAVOpenReceiverErrorEx(); } catch(FlowCreateProblemExImpl &ex) { ACSBulkDataError::AVOpenReceiverErrorExImpl err = ACSBulkDataError::AVOpenReceiverErrorExImpl(ex,__FILE__,__LINE__,__PRETTY_FUNCTION__); err.log(LM_DEBUG); throw err.getAVOpenReceiverErrorEx(); } catch(...) { ACSErrTypeCommon::UnknownExImpl ex = ACSErrTypeCommon::UnknownExImpl(__FILE__,__LINE__,__PRETTY_FUNCTION__); ACSBulkDataError::AVOpenReceiverErrorExImpl err = ACSBulkDataError::AVOpenReceiverErrorExImpl(ex,__FILE__,__LINE__,__PRETTY_FUNCTION__); throw err.getAVOpenReceiverErrorEx(); } } AcsBulkdata::BulkDataNTSenderStream* BulkDataNTSenderImpl::createSenderStream(const char *stream_name) { // Create the stream with the configuration pointed out by the iterator AcsBulkdata::BulkDataNTSenderStream *stream = 0; stream = new AcsBulkdata::BulkDataNTSenderStream(stream_name, *parser_m->getSenderStreamConfiguration(stream_name)); // Create also all the necessary flows that have been configured in the CDB std::set<const char *> flowNames = parser_m->getAllSenderFlowNames(stream_name); std::set<const char *>::iterator it; for(it = flowNames.begin(); it != flowNames.end(); it++) { const char * flowName = *it; stream->createFlow(flowName, *parser_m->getSenderFlowConfiguration(stream_name, flowName)); } return stream; } AcsBulkdata::BulkDataNTSenderStream* BulkDataNTSenderImpl::createDefaultSenderStream() { // Create the default stream AcsBulkdata::BulkDataNTSenderStream *stream = 0; stream = new AcsBulkdata::BulkDataNTSenderStream("DefaultStream"); // Add the specified of flows for(int i=0; i < defaultFlowsCount_m; i++) { std::stringstream s; s << "Flow" << i; stream->createFlow(s.str().c_str()); } return stream; } void BulkDataNTSenderImpl::disconnect() { ACS_TRACE("BulkDataNTSenderImpl::disconnect - deprecated"); try { StreamMap::iterator it; for( it = senderStreams_m.begin(); it != senderStreams_m.end(); it++ ) { ACS_SHORT_LOG((LM_ERROR,"BulkDataNTSenderImpl::disconnect Closing sender stream '%s'", it->first.c_str())); closeStream(it); } } catch(ACSErr::ACSbaseExImpl &ex) { ACSBulkDataError::AVCloseReceiverErrorExImpl err = ACSBulkDataError::AVCloseReceiverErrorExImpl(ex,__FILE__,__LINE__,"BulkDataNTSenderImpl::disconnect"); err.log(LM_DEBUG); throw err.getAVCloseReceiverErrorEx(); } catch(...) { ACSErrTypeCommon::UnknownExImpl ex = ACSErrTypeCommon::UnknownExImpl(__FILE__,__LINE__,"BulkDataNTSenderImpl::disconnect"); ACSBulkDataError::AVCloseReceiverErrorExImpl err = ACSBulkDataError::AVCloseReceiverErrorExImpl(ex,__FILE__,__LINE__,"BulkDataNTSenderImpl::disconnect"); throw err.getAVCloseReceiverErrorEx(); } } void BulkDataNTSenderImpl::closeStream(StreamMap::iterator &it) { delete it->second; senderStreams_m.erase(it); } AcsBulkdata::BulkDataNTSenderStream* BulkDataNTSenderImpl::getSenderStream() { if( senderStreams_m.size() != 0 ) return senderStreams_m.begin()->second; //here we come just in case of an error StreamNotExistExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); throw ex; } AcsBulkdata::BulkDataNTSenderStream* BulkDataNTSenderImpl::getSenderStream(const char *streamName) { if( senderStreams_m.size() != 0 ) { StreamMap::iterator it; it = senderStreams_m.find(streamName); if (it!=senderStreams_m.end()) return it->second; } //here we come just in case of an error StreamNotExistExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setStreamName(streamName); throw ex; }
lgpl-2.1
gwenniger/joshua
src/joshua/util/Counted.java
2870
/* * This file is part of the Joshua Machine Translation System. * * Joshua is free software; you can redistribute it and/or modify it under the terms of the GNU * Lesser General Public License as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library 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 this library; * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ package joshua.util; import java.util.Comparator; /** * Represents an object being counted, with the associated count. * * @author Lane Schwartz */ public class Counted<E> implements Comparable<Counted<E>> { /** The element being counted. */ private final E element; /** The count associated with the element. */ private final Integer count; /** * Constructs an object wrapping an element and its associated count. * * @param element An element being counted * @param count The count associated with the element */ public Counted(E element, int count) { this.element = element; this.count = count; } /** * Gets the count associated with this object's element. * * @return The count associated with this object's element */ public int getCount() { return count; } /** * Gets the element associated with this object. * * @return The element associated with this object */ public E getElement() { return element; } /** * Compares this object to another counted object, according to the natural order of the counts * associated with each object. * * @param o Another counted object * @return -1 if the count of this object is less than the count of the other object, 0 if the * counts are equal, or 1 if the count of this object is greater than the count of the * other object */ public int compareTo(Counted<E> o) { return count.compareTo(o.count); } /** * Gets a comparator that compares two counted objects based on the reverse of the natural order * of the counts associated with each object. * * @param <E> * @return A comparator that compares two counted objects based on the reverse of the natural * order of the counts associated with each object */ public static <E> Comparator<Counted<E>> getDescendingComparator() { return new Comparator<Counted<E>>() { public int compare(Counted<E> o1, Counted<E> o2) { return (o2.count.compareTo(o1.count)); } }; } }
lgpl-2.1
AgNO3/jcifs-ng
src/main/java/jcifs/internal/smb1/com/SmbComTreeConnectAndXResponse.java
4264
/* jcifs smb client library in Java * Copyright (C) 2000 "Michael B. Allen" <jcifs at samba dot org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.internal.smb1.com; import java.io.UnsupportedEncodingException; import jcifs.Configuration; import jcifs.internal.TreeConnectResponse; import jcifs.internal.smb1.AndXServerMessageBlock; import jcifs.internal.smb1.ServerMessageBlock; /** * * @author mbechler * */ public class SmbComTreeConnectAndXResponse extends AndXServerMessageBlock implements TreeConnectResponse { private static final int SMB_SUPPORT_SEARCH_BITS = 0x0001; private static final int SMB_SHARE_IS_IN_DFS = 0x0002; private boolean supportSearchBits, shareIsInDfs; private String service, nativeFileSystem = ""; /** * * @param config * @param andx */ public SmbComTreeConnectAndXResponse ( Configuration config, ServerMessageBlock andx ) { super(config, andx); } /** * @return the service */ @Override public final String getService () { return this.service; } /** * @return the nativeFileSystem */ public final String getNativeFileSystem () { return this.nativeFileSystem; } /** * @return the supportSearchBits */ public final boolean isSupportSearchBits () { return this.supportSearchBits; } /** * @return the shareIsInDfs */ @Override public final boolean isShareDfs () { return this.shareIsInDfs; } /** * {@inheritDoc} * * @see jcifs.internal.TreeConnectResponse#isValidTid() */ @Override public boolean isValidTid () { return getTid() != 0xFFFF; } @Override protected int writeParameterWordsWireFormat ( byte[] dst, int dstIndex ) { return 0; } @Override protected int writeBytesWireFormat ( byte[] dst, int dstIndex ) { return 0; } @Override protected int readParameterWordsWireFormat ( byte[] buffer, int bufferIndex ) { this.supportSearchBits = ( buffer[ bufferIndex ] & SMB_SUPPORT_SEARCH_BITS ) == SMB_SUPPORT_SEARCH_BITS; this.shareIsInDfs = ( buffer[ bufferIndex ] & SMB_SHARE_IS_IN_DFS ) == SMB_SHARE_IS_IN_DFS; return 2; } @Override protected int readBytesWireFormat ( byte[] buffer, int bufferIndex ) { int start = bufferIndex; int len = readStringLength(buffer, bufferIndex, 32); try { this.service = new String(buffer, bufferIndex, len, "ASCII"); } catch ( UnsupportedEncodingException uee ) { return 0; } bufferIndex += len + 1; // win98 observed not returning nativeFileSystem /* * Problems here with iSeries returning ASCII even though useUnicode = true * Fortunately we don't really need nativeFileSystem for anything. * if( byteCount > bufferIndex - start ) { * nativeFileSystem = readString( buffer, bufferIndex ); * bufferIndex += stringWireLength( nativeFileSystem, bufferIndex ); * } */ return bufferIndex - start; } @Override public String toString () { String result = new String( "SmbComTreeConnectAndXResponse[" + super.toString() + ",supportSearchBits=" + this.supportSearchBits + ",shareIsInDfs=" + this.shareIsInDfs + ",service=" + this.service + ",nativeFileSystem=" + this.nativeFileSystem + "]"); return result; } }
lgpl-2.1
nonrational/qt-everywhere-opensource-src-4.8.6
tools/porting/src/codemodelattributes.cpp
7315
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the qt3to4 porting application of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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 Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "codemodelattributes.h" #include "tokenengine.h" QT_BEGIN_NAMESPACE using namespace CodeModel; using namespace TokenEngine; /* Walk the codemodel. */ void CodeModelAttributes::createAttributes(TranslationUnit translationUnit) { m_translationUnit = translationUnit; parseScope(const_cast<CodeModel::NamespaceScope *>(translationUnit.codeModel())); } /* Create attributes for each name use and assign to the token. */ void CodeModelAttributes::parseNameUse(CodeModel::NameUse *nameUse) { // Get the container for this token. TokenRef ref = nameUse->nameToken(); const int containerIndex = ref.containerIndex(); TokenAttributes *attributes = ref.tokenContainer().tokenAttributes(); if (!areAttributesEnabled(attributes)) return; // Test if the nameUse refers to a UnknownType. If so we add and // "unknown" attribute. if (TypeMember *typeMember = nameUse->declaration()->toTypeMember()) { if (typeMember->type()->toUnknownType()) { attributes->addAttribute(containerIndex, "unknown", nameUse->name()); return; } } // Add attributes this namnUse. attributes->addAttribute(containerIndex, "nameUse", nameUse->name()); attributes->addAttribute(containerIndex, "parentScope", nameUse->declaration()->parent()->name() ); if (CodeModel::Scope * skop = nameUse->declaration()->parent()->parent()) { attributes->addAttribute(containerIndex, "grandParentScope", skop->name()); } createNameTypeAttribute(nameUse); } /* Create attributes for members and assign to token. */ void CodeModelAttributes::parseMember(CodeModel::Member *member) { if(!member || member->name() == QByteArray()) return; //get the container for this token TokenRef ref = member->nameToken(); const int containerIndex = ref.containerIndex(); TokenAttributes *attributes = ref.tokenContainer().tokenAttributes(); if (areAttributesEnabled(attributes)) { //add attributes for this declaration static const QByteArray textDeclaration = "declaration"; attributes->addAttribute(containerIndex, textDeclaration, member->name()); createNameTypeAttribute(member); } CodeModelWalker::parseMember(member); } void CodeModelAttributes::parseFunctionMember(CodeModel::FunctionMember *member) { CodeModel::ArgumentCollection arguments = member->arguments(); CodeModel::ArgumentCollection::ConstIterator it = arguments.constBegin(); TokenRef ref = member->nameToken(); TokenAttributes *attributes = ref.tokenContainer().tokenAttributes(); if (areAttributesEnabled(attributes)) { while (it != arguments.constEnd()) { const int containerIndex = (*it)->nameToken().containerIndex(); const QByteArray name = (*it)->name(); attributes->addAttribute(containerIndex, "declaration", name); attributes->addAttribute(containerIndex, "nameType", "variable"); ++it; } } CodeModelWalker::parseFunctionMember(member); } /* NameType attributes gives information on what kind of member this is. */ void CodeModelAttributes::createNameTypeAttribute(CodeModel::Member *member) { if(!member) return; //get the container for the token accosiated with this member. TokenRef ref = member->nameToken(); const int containerIndex = ref.containerIndex(); TokenAttributes *attributes = ref.tokenContainer().tokenAttributes(); createNameTypeAttributeAtIndex(attributes, containerIndex, member); } /* A NameUse has the same NameType as the declaration it is referring to. */ void CodeModelAttributes::createNameTypeAttribute(CodeModel::NameUse *nameUse) { if(!nameUse) return; //get the container for the token accosiated with this NameUse. TokenRef ref = nameUse->nameToken(); const int containerIndex = ref.containerIndex(); TokenAttributes *attributes = ref.tokenContainer().tokenAttributes(); createNameTypeAttributeAtIndex(attributes, containerIndex, nameUse->declaration()); } void CodeModelAttributes::createNameTypeAttributeAtIndex(TokenEngine::TokenAttributes *attributes, int index, CodeModel::Member *member) { QByteArray nameType = "unknown"; if (member->toFunctionMember()) { nameType = "function"; } else if (CodeModel::VariableMember *variableMember = member->toVariableMember()) { if (variableMember->type()->toEnumType()) nameType = "enumerator"; else nameType = "variable"; } else if (CodeModel::TypeMember *typeMember = member->toTypeMember()) { if (CodeModel::Type *type = typeMember->type()) { if (type->toClassType()) { nameType = "class"; } else if (type->toEnumType()) { nameType = "enum"; } } } attributes->addAttribute(index, "nameType", nameType); } bool CodeModelAttributes::areAttributesEnabled(const TokenAttributes *attributes) const { static const QByteArray tstCreateAttributes("CreateAttributes"); static const QByteArray tstTrue("True"); return (attributes->attribute(tstCreateAttributes) == tstTrue); } QT_END_NAMESPACE
lgpl-2.1
CastMi/iverilog
vhdlpp/vtype_match.cc
1359
/* * Copyright (c) 2013 Stephen Williams (steve@icarus.com) * Copyright CERN 2013 / Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form 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. */ # include "vtype.h" bool VType::type_match(const VType*that) const { if(this == that) return true; if(const VTypeDef*tdef = dynamic_cast<const VTypeDef*>(that)) { if(type_match(tdef->peek_definition())) return true; } return false; } bool VTypeDef::type_match(const VType*that) const { if(VType::type_match(that)) return true; return VType::type_match(type_); }
lgpl-2.1
iulian787/spack
var/spack/repos/builtin/packages/perl/package.py
15458
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) # # Author: Milton Woods <milton.woods@bom.gov.au> # Date: March 22, 2017 # Author: George Hartzell <hartzell@alerce.com> # Date: July 21, 2016 # Author: Justin Too <justin@doubleotoo.com> # Date: September 6, 2015 # import re import os from contextlib import contextmanager from llnl.util.lang import match_predicate from spack import * class Perl(Package): # Perl doesn't use Autotools, it should subclass Package """Perl 5 is a highly capable, feature-rich programming language with over 27 years of development.""" homepage = "http://www.perl.org" # URL must remain http:// so Spack can bootstrap curl url = "http://www.cpan.org/src/5.0/perl-5.24.1.tar.gz" executables = [r'^perl(-?\d+.*)?$'] # see http://www.cpan.org/src/README.html for # explanation of version numbering scheme # Development releases (odd numbers) version('5.33.3', sha256='4f4ba0aceb932e6cf7c05674d05e51ef759d1c97f0685dee65a8f3d190f737cd') version('5.31.7', sha256='d05c4e72128f95ef6ffad42728ecbbd0d9437290bf0f88268b51af011f26b57d') version('5.31.4', sha256='418a7e6fe6485cc713a86d1227ef112f0bb3f80322e3b715ffe42851d97804a5') # Maintenance releases (even numbers, recommended) version('5.32.0', sha256='efeb1ce1f10824190ad1cadbcccf6fdb8a5d37007d0100d2d9ae5f2b5900c0b4', preferred=True) version('5.30.3', sha256='32e04c8bb7b1aecb2742a7f7ac0eabac100f38247352a73ad7fa104e39e7406f') version('5.30.2', sha256='66db7df8a91979eb576fac91743644da878244cf8ee152f02cd6f5cd7a731689') version('5.30.1', sha256='bf3d25571ff1ee94186177c2cdef87867fd6a14aa5a84f0b1fb7bf798f42f964') version('5.30.0', sha256='851213c754d98ccff042caa40ba7a796b2cee88c5325f121be5cbb61bbf975f2') # End of life releases version('5.28.0', sha256='7e929f64d4cb0e9d1159d4a59fc89394e27fa1f7004d0836ca0d514685406ea8') version('5.26.2', sha256='572f9cea625d6062f8a63b5cee9d3ee840800a001d2bb201a41b9a177ab7f70d') version('5.24.1', sha256='e6c185c9b09bdb3f1b13f678999050c639859a7ef39c8cad418448075f5918af') version('5.22.4', sha256='ba9ef57c2b709f2dad9c5f6acf3111d9dfac309c484801e0152edbca89ed61fa') version('5.22.3', sha256='1b351fb4df7e62ec3c8b2a9f516103595b2601291f659fef1bbe3917e8410083') version('5.22.2', sha256='81ad196385aa168cb8bd785031850e808c583ed18a7901d33e02d4f70ada83c2') version('5.22.1', sha256='2b475d0849d54c4250e9cba4241b7b7291cffb45dfd083b677ca7b5d38118f27') version('5.22.0', sha256='0c690807f5426bbd1db038e833a917ff00b988bf03cbf2447fa9ffdb34a2ab3c') version('5.20.3', sha256='3524e3a76b71650ab2f794fd68e45c366ec375786d2ad2dca767da424bbb9b4a') version('5.18.4', sha256='01a4e11a9a34616396c4a77b3cef51f76a297e1a2c2c490ae6138bf0351eb29f') version('5.16.3', sha256='69cf08dca0565cec2c5c6c2f24b87f986220462556376275e5431cc2204dedb6') extendable = True depends_on('gdbm') depends_on('berkeley-db') # there has been a long fixed issue with 5.22.0 with regard to the ccflags # definition. It is well documented here: # https://rt.perl.org/Public/Bug/Display.html?id=126468 patch('protect-quotes-in-ccflags.patch', when='@5.22.0') # Fix build on Fedora 28 # https://bugzilla.redhat.com/show_bug.cgi?id=1536752 patch('https://src.fedoraproject.org/rpms/perl/raw/004cea3a67df42e92ffdf4e9ac36d47a3c6a05a4/f/perl-5.26.1-guard_old_libcrypt_fix.patch', level=1, sha256='0eac10ed90aeb0459ad8851f88081d439a4e41978e586ec743069e8b059370ac', when='@:5.26.2') # Fix 'Unexpected product version' error on macOS 11.0 Big Sur # https://github.com/Perl/perl5/pull/17946 patch('macos-11-version-check.patch', when='@5.24.1:5.32.0 platform=darwin') # Enable builds with the NVIDIA compiler patch('nvhpc.patch', when='%nvhpc') # Installing cpanm alongside the core makes it safe and simple for # people/projects to install their own sets of perl modules. Not # having it in core increases the "energy of activation" for doing # things cleanly. variant('cpanm', default=True, description='Optionally install cpanm with the core packages.') variant('shared', default=True, description='Build a shared libperl.so library') variant('threads', default=True, description='Build perl with threads support') resource( name="cpanm", url="http://search.cpan.org/CPAN/authors/id/M/MI/MIYAGAWA/App-cpanminus-1.7042.tar.gz", sha256="9da50e155df72bce55cb69f51f1dbb4b62d23740fb99f6178bb27f22ebdf8a46", destination="cpanm", placement="cpanm" ) phases = ['configure', 'build', 'install'] @classmethod def determine_version(cls, exe): perl = spack.util.executable.Executable(exe) output = perl('--version', output=str, error=str) if output: match = re.search(r'perl.*\(v([0-9.]+)\)', output) if match: return match.group(1) return None @classmethod def determine_variants(cls, exes, version): for exe in exes: perl = spack.util.executable.Executable(exe) output = perl('-V', output=str, error=str) variants = '' if output: match = re.search(r'-Duseshrplib', output) if match: variants += '+shared' else: variants += '~shared' match = re.search(r'-Duse.?threads', output) if match: variants += '+threads' else: variants += '~threads' path = os.path.dirname(exe) if 'cpanm' in os.listdir(path): variants += '+cpanm' else: variants += '~cpanm' return variants # On a lustre filesystem, patch may fail when files # aren't writeable so make pp.c user writeable # before patching. This should probably walk the # source and make everything writeable in the future. def do_stage(self, mirror_only=False): # Do Spack's regular stage super(Perl, self).do_stage(mirror_only) # Add write permissions on file to be patched filename = join_path(self.stage.source_path, 'pp.c') perm = os.stat(filename).st_mode os.chmod(filename, perm | 0o200) def configure_args(self): spec = self.spec prefix = self.prefix config_args = [ '-des', '-Dprefix={0}'.format(prefix), '-Dlocincpth=' + self.spec['gdbm'].prefix.include, '-Dloclibpth=' + self.spec['gdbm'].prefix.lib, ] # Extensions are installed into their private tree via # `INSTALL_BASE`/`--install_base` (see [1]) which results in a # "predictable" installation tree that sadly does not match the # Perl core's @INC structure. This means that when activation # merges the extension into the extendee[2], the directory tree # containing the extensions is not on @INC and the extensions can # not be found. # # This bit prepends @INC with the directory that is used when # extensions are activated [3]. # # [1] https://metacpan.org/pod/ExtUtils::MakeMaker#INSTALL_BASE # [2] via the activate method in the PackageBase class # [3] https://metacpan.org/pod/distribution/perl/INSTALL#APPLLIB_EXP config_args.append('-Accflags=-DAPPLLIB_EXP=\\"' + self.prefix.lib.perl5 + '\\"') # Discussion of -fPIC for Intel at: # https://github.com/spack/spack/pull/3081 and # https://github.com/spack/spack/pull/4416 if spec.satisfies('%intel'): config_args.append('-Accflags={0}'.format( self.compiler.cc_pic_flag)) if '+shared' in spec: config_args.append('-Duseshrplib') if '+threads' in spec: config_args.append('-Dusethreads') # Development versions have an odd second component if spec.version[1] % 2 == 1: config_args.append('-Dusedevel') return config_args def configure(self, spec, prefix): configure = Executable('./Configure') configure(*self.configure_args()) def build(self, spec, prefix): make() @run_after('build') @on_package_attributes(run_tests=True) def build_test(self): make('test') def install(self, spec, prefix): make('install') @run_after('install') def install_cpanm(self): spec = self.spec if '+cpanm' in spec: with working_dir(join_path('cpanm', 'cpanm')): perl = spec['perl'].command perl('Makefile.PL') make() make('install') def _setup_dependent_env(self, env, dependent_spec, deptypes): """Set PATH and PERL5LIB to include the extension and any other perl extensions it depends on, assuming they were installed with INSTALL_BASE defined.""" perl_lib_dirs = [] for d in dependent_spec.traverse(deptype=deptypes): if d.package.extends(self.spec): perl_lib_dirs.append(d.prefix.lib.perl5) if perl_lib_dirs: perl_lib_path = ':'.join(perl_lib_dirs) env.prepend_path('PERL5LIB', perl_lib_path) def setup_dependent_build_environment(self, env, dependent_spec): self._setup_dependent_env(env, dependent_spec, deptypes=('build', 'run')) def setup_dependent_run_environment(self, env, dependent_spec): self._setup_dependent_env(env, dependent_spec, deptypes=('run',)) def setup_dependent_package(self, module, dependent_spec): """Called before perl modules' install() methods. In most cases, extensions will only need to have one line: perl('Makefile.PL','INSTALL_BASE=%s' % self.prefix) """ # If system perl is used through packages.yaml # there cannot be extensions. if dependent_spec.package.is_extension: # perl extension builds can have a global perl # executable function module.perl = self.spec['perl'].command # Add variables for library directory module.perl_lib_dir = dependent_spec.prefix.lib.perl5 # Make the site packages directory for extensions, # if it does not exist already. mkdirp(module.perl_lib_dir) @run_after('install') def filter_config_dot_pm(self): """Run after install so that Config.pm records the compiler that Spack built the package with. If this isn't done, $Config{cc} will be set to Spack's cc wrapper script. These files are read-only, which frustrates filter_file on some filesystems (NFSv4), so make them temporarily writable. """ kwargs = {'ignore_absent': True, 'backup': False, 'string': False} # Find the actual path to the installed Config.pm file. perl = self.spec['perl'].command config_dot_pm = perl('-MModule::Loaded', '-MConfig', '-e', 'print is_loaded(Config)', output=str) with self.make_briefly_writable(config_dot_pm): match = 'cc *=>.*' substitute = "cc => '{cc}',".format(cc=self.compiler.cc) filter_file(match, substitute, config_dot_pm, **kwargs) # And the path Config_heavy.pl d = os.path.dirname(config_dot_pm) config_heavy = join_path(d, 'Config_heavy.pl') with self.make_briefly_writable(config_heavy): match = '^cc=.*' substitute = "cc='{cc}'".format(cc=self.compiler.cc) filter_file(match, substitute, config_heavy, **kwargs) match = '^ld=.*' substitute = "ld='{ld}'".format(ld=self.compiler.cc) filter_file(match, substitute, config_heavy, **kwargs) match = "^ccflags='" substitute = "ccflags='%s " % ' '\ .join(self.spec.compiler_flags['cflags']) filter_file(match, substitute, config_heavy, **kwargs) @contextmanager def make_briefly_writable(self, path): """Temporarily make a file writable, then reset""" perm = os.stat(path).st_mode os.chmod(path, perm | 0o200) yield os.chmod(path, perm) # ======================================================================== # Handle specifics of activating and deactivating perl modules. # ======================================================================== def perl_ignore(self, ext_pkg, args): """Add some ignore files to activate/deactivate args.""" ignore_arg = args.get('ignore', lambda f: False) # Many perl packages describe themselves in a perllocal.pod file, # so the files conflict when multiple packages are activated. # We could merge the perllocal.pod files in activated packages, # but this is unnecessary for correct operation of perl. # For simplicity, we simply ignore all perllocal.pod files: patterns = [r'perllocal\.pod$'] return match_predicate(ignore_arg, patterns) def activate(self, ext_pkg, view, **args): ignore = self.perl_ignore(ext_pkg, args) args.update(ignore=ignore) super(Perl, self).activate(ext_pkg, view, **args) extensions_layout = view.extensions_layout exts = extensions_layout.extension_map(self.spec) exts[ext_pkg.name] = ext_pkg.spec def deactivate(self, ext_pkg, view, **args): ignore = self.perl_ignore(ext_pkg, args) args.update(ignore=ignore) super(Perl, self).deactivate(ext_pkg, view, **args) extensions_layout = view.extensions_layout exts = extensions_layout.extension_map(self.spec) # Make deactivate idempotent if ext_pkg.name in exts: del exts[ext_pkg.name] @property def command(self): """Returns the Perl command, which may vary depending on the version of Perl. In general, Perl comes with a ``perl`` command. However, development releases have a ``perlX.Y.Z`` command. Returns: Executable: the Perl command """ for ver in ('', self.spec.version): path = os.path.join(self.prefix.bin, '{0}{1}'.format( self.spec.name, ver)) if os.path.exists(path): return Executable(path) else: msg = 'Unable to locate {0} command in {1}' raise RuntimeError(msg.format(self.spec.name, self.prefix.bin)) def test(self): """Smoke tests""" exe = self.spec['perl'].command.name reason = 'test: checking version is {0}'.format(self.spec.version) self.run_test(exe, '--version', ['perl', str(self.spec.version)], installed=True, purpose=reason) reason = 'test: ensuring perl runs' msg = 'Hello, World!' options = ['-e', 'use warnings; use strict;\nprint("%s\n");' % msg] self.run_test(exe, options, msg, installed=True, purpose=reason)
lgpl-2.1
vovkasm/liteide
liteidex/src/3rdparty/libucd/src/LangFrenchModel.cpp
9777
/** * @file LangFrenchModel.cpp * @brief LangFrenchModel * @license GPL 2.0/LGPL 2.1 */ #include "nsSBCharSetProber.h" static const unsigned char french_WINDOWS_1252CharToOrderMap[] = { 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 30, 40, 31, 37, 27, 44, 48, 52, 32, 45, 61, 25, 29, 41, 43, 34, 53, 38, 35, 39, 46, 42, 68, 63, 65, 71,255,255,255,255,255, 255, 2, 20, 12, 11, 1, 17, 18, 21, 4, 24, 57, 9, 13, 5, 10, 14, 19, 7, 3, 6, 8, 16, 54, 23, 28, 36,255,255,255,255,255, 64,180,179,178,177, 75,176,175,174,173,172,171, 91,170,169,168, 167,166, 62,111,110, 67, 78, 88,165, 97,164, 90, 82,163,162,161, 160,159,158,157,156,155,154, 86, 84, 69,101, 50,109,153, 96,152, 81,151,108,150,100,149,148, 80,147,107,146, 51,145,144,143,142, 70,141, 79, 72,140,139,138, 73, 77, 60, 76,137,136,135, 99,134, 106,133,132,131, 83,130, 98, 92,129, 95,128, 94,127,126,125,124, 22, 93, 49,123,105,104, 89, 47, 26, 15, 33, 74,122,121, 56, 66, 120,103,119,118, 55,102, 87,117,116, 59,115, 58, 85,114,113,112, }; static const PRUint8 frenchLangModel[] = { 2,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,2,3,2,0,3,2,0,0,0,3,2,0,0,0, 0,0,0,3,0,0,1,1,0,0,0,1,0,0,2,0,2,0,2,0,0,3,1,0,2,3,0,0,0,0,1,0, 2,2,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,0,2,3,0,0,0,3,0,0,0,0, 0,0,1,3,0,0,0,0,0,0,0,0,0,0,3,0,0,0,1,0,0,1,1,3,3,0,0,0,0,0,0,0, 3,3,3,3,2,3,2,3,3,3,1,3,3,3,3,1,2,2,3,2,2,0,0,1,1,3,0,3,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,1,0,1,2,2,0,0,0,2,0,0, 3,3,3,2,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,1,0,3,2,1,3,0,1,0,0,0,0, 1,2,0,3,0,0,0,2,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,0,2,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,2,3,3,3,2,2,3,3,3,3,3,2,3,0,2,2,0,2,0,2,0,1,0,0, 3,0,0,3,0,0,0,0,1,0,0,1,0,0,3,0,2,0,1,0,0,0,1,0,2,1,0,0,0,2,0,0, 3,3,3,3,1,3,3,3,2,3,1,2,2,3,3,0,1,0,0,1,3,0,0,0,0,3,0,2,0,0,0,0, 3,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,2,0,1,0,0,1,3,1,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,1,1,0,3,0,3,0,0,0,2, 3,0,0,2,0,0,0,0,0,0,0,0,0,0,3,0,3,0,1,0,0,1,3,1,3,2,0,0,0,0,0,0, 3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,2,0,3,3,0,2,0,3,0,0,0,0, 3,0,0,2,0,0,0,0,0,0,0,0,0,0,1,1,2,0,1,0,0,0,0,1,2,0,0,0,0,2,0,0, 3,3,3,3,1,3,1,3,3,3,2,3,3,3,3,2,2,3,3,3,3,3,1,0,0,3,1,3,0,0,0,0, 2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,3,0,1,0,0,0,2,1,2,2,0,0,0,3,0,0, 3,2,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,2,0,2,2,0,2,0,3,0,0,0,0, 2,0,0,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,2,2,3,3,0,0,0,0,0, 3,3,3,3,1,2,3,3,1,3,2,1,3,0,3,2,1,2,1,2,2,0,0,2,0,3,1,2,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,1,2,2,0,2,0,0,0,2,0,0, 3,3,3,3,3,3,3,3,3,3,2,3,1,0,3,0,1,2,3,0,3,0,0,0,0,3,0,2,0,0,1,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,3,0,2,1,0,0,0,2,0,0, 3,3,2,3,3,3,1,3,2,3,0,0,3,3,3,0,0,1,0,3,0,0,0,0,0,3,0,2,0,0,0,0, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1,0,0,0,2,1,0,2,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,1,2,0,3,3,0,0,2,0,1,3,0,2,0,0,3,0,2,0,0,0,0, 3,0,1,0,0,0,0,0,0,0,0,0,0,0,2,0,3,0,0,0,0,1,2,1,0,2,0,0,0,0,0,0, 3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,2,0,0,3,0,0,0,0,0,0,0,0, 0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,0,2,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,0,3,0,0,3,3,0,3,0,0,0,0,3,0,0,1,0,0,0,0,0,0,0,3,0,1,0,0,0,0, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,2,0,0,0,0,0,1,0,0, 3,3,3,3,0,1,3,3,3,3,0,1,0,0,3,0,3,1,0,0,0,0,0,0,0,2,0,1,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0,2,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,1,0,2,0,3,1,0,2,0,2,3,0,0,0,0,3,0,2,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,1,2,0,0,0,0,0,0,0, 0,1,1,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0, 3,3,3,3,1,2,3,3,3,3,2,1,1,0,3,1,0,0,0,3,0,0,0,2,0,2,0,3,0,0,0,0, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,2,0,1,0,0,0,0,0,0, 3,3,1,3,3,3,3,3,2,3,1,0,2,2,3,0,0,0,0,0,0,0,0,0,0,3,0,2,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,3,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,0,3,0,3,0,2,0,2,0,3,0,3,2,0,0,0,2,0,2,0,1,0,0,1,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,0,1,0,0,0,3,0,3,0,0,0,2,1,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0, 3,3,0,3,0,0,0,3,2,3,0,0,0,0,2,0,0,0,0,0,2,2,0,0,2,0,3,2,2,3,1,3, 0,0,1,0,1,0,2,0,1,1,2,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,2,1,2,0,0, 0,0,3,0,3,3,3,0,2,0,2,3,3,1,0,3,1,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,3,1,3,3,2,3,3,0,2,2,3,1,0,2,1,2,1,0,3,0,2,0,2,0,2,0,2,2,2,2, 0,2,3,1,2,3,2,2,3,1,1,1,0,2,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,2,0, 3,3,3,1,2,2,3,0,2,3,2,2,2,2,3,1,1,2,0,1,0,0,1,0,0,1,0,1,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,0,3,0,0,0,2,1,3,0,1,3,0,2,0,0,1,0,0,0,0,0,0,1,2,2,1,2,2,1,2, 2,2,1,0,0,0,1,1,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,3,2,3,3,3,0,2,2,2,3,0,2,2,2,1,3,3,0,0,2,2,0,1,2,2,1,2,2, 0,2,2,2,1,2,2,2,3,2,0,2,1,2,0,2,0,0,0,0,3,0,0,0,1,0,0,0,2,0,0,0, 3,3,0,2,0,0,2,2,3,3,0,0,0,0,2,0,1,0,0,0,3,0,0,0,2,0,2,2,0,2,1,2, 0,2,2,0,1,1,2,0,2,0,2,1,0,2,0,2,0,0,0,2,1,0,1,0,0,0,0,0,2,1,0,0, 1,0,2,0,3,2,2,0,3,1,2,2,2,0,0,1,0,1,0,1,0,0,0,0,2,0,3,0,2,2,2,3, 0,2,2,1,1,2,3,2,3,3,2,2,0,0,0,2,0,0,0,1,2,0,0,0,0,0,0,1,1,0,2,0, 0,0,0,0,2,3,0,0,2,0,0,3,3,1,0,3,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,0,3,0,0,3,3,3,3,0,0,0,0,2,0,0,0,0,0,3,0,0,0,2,2,2,1,0,2,1,2, 0,1,2,0,2,3,2,0,0,0,2,1,2,2,0,0,1,0,0,2,0,0,1,0,0,0,0,1,1,0,0,0, 3,3,0,3,0,2,0,3,1,3,0,2,1,2,2,0,0,0,1,0,2,0,0,0,0,1,2,2,1,2,1,2, 0,2,2,0,1,1,2,2,1,0,2,2,0,2,0,0,0,0,0,1,0,0,0,0,1,1,0,2,2,0,0,0, 3,3,0,2,1,0,1,1,1,3,0,0,1,1,2,0,0,1,0,1,1,0,0,0,0,1,0,3,0,0,0,0, 0,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,0,3,0,0,2,3,0,2,0,0,1,2,3,0,0,0,0,0,0,0,0,1,1,2,3,0,0,2,1,2, 0,0,2,0,0,2,0,0,1,1,2,2,1,2,0,1,0,0,0,1,0,0,0,0,0,0,0,2,0,1,0,0, 3,3,0,2,0,0,0,2,0,3,0,0,0,0,3,0,0,0,0,0,2,0,0,0,2,0,3,1,2,2,2,2, 0,2,2,0,2,2,2,2,2,2,3,1,0,2,0,1,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0, 3,3,1,2,0,0,3,3,0,3,0,1,0,0,2,0,0,0,0,0,3,0,0,0,2,1,3,1,1,2,2,3, 0,1,2,0,0,2,2,0,1,1,2,1,0,2,0,1,0,0,0,3,0,2,0,0,0,0,0,2,0,0,0,0, 3,3,0,3,0,0,3,2,3,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,2,0,1,2,1,2, 0,0,1,0,2,2,1,1,2,0,2,1,1,2,0,0,1,0,0,0,0,1,0,0,0,0,0,2,0,0,0,0, 3,3,0,3,0,0,0,2,0,3,0,1,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,2, 0,2,3,0,2,1,3,1,2,1,1,2,0,2,0,2,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0, 3,3,0,3,0,0,1,2,2,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,1,0,2,0,2, 1,0,0,0,1,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,2,3,1,3,3,2,0,1,2,1,2,0,2,1,1,0,2,3,0,0,0,2,0,2,0,2,1,2,2, 0,2,2,0,2,2,2,2,3,2,1,2,2,2,0,1,0,0,0,0,0,0,0,0,1,0,2,0,0,0,1,0, 2,3,0,2,1,0,3,2,2,3,0,0,0,1,3,0,0,0,0,1,1,0,1,0,2,0,2,0,2,3,0,2, 1,2,2,0,0,2,0,1,1,0,2,1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0, 3,3,0,0,0,0,0,2,0,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0, 0,0,0,0,2,0,1,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,3,2,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,3,0,2,2,2,2, 0,2,2,0,2,3,2,2,2,1,2,1,0,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,2,0, 0,3,0,0,0,0,0,3,0,3,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0, 2,3,0,2,0,0,3,3,1,3,0,0,1,0,2,0,0,0,0,0,1,0,0,0,1,0,2,1,0,2,0,1, 1,1,1,0,0,1,1,2,2,2,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0, 0,0,1,2,2,3,0,0,3,0,0,3,2,2,0,1,0,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1,0,1,0,0,0,0,0,0,2,0,2,0,2,2,2,2, 0,2,2,0,2,1,2,2,2,2,2,1,2,1,0,1,0,0,0,2,2,0,0,0,0,0,0,1,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,0,2,0,0,0,3,0,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,3,1,0,2,0,2, 0,0,0,0,1,2,1,1,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,2,0,0,0,0, 0,1,1,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,3,2,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,2,3,0,0,3,0,2,0,2,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,3,3,0,0,2,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,3,0,1,1,2,1,3,0,1,2,0,1,0,1,1,0,1,2,0,0,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,1,3,2,0,2,0,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,2,1,0,2,0,2,2,1,1,0,2,0,2,0,1,0,0,0,0,2,0,2,0,2,0,2,0, 0,2,2,0,2,2,1,0,1,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,0,2,0,0,2,1,1,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,2,0,1,1,0,0, 0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0, 2,2,0,2,0,0,0,2,0,2,0,0,0,0,2,0,0,0,0,0,2,1,0,0,0,0,2,1,0,2,0,2, 1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0, 1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,3, 0,0,0,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; const SequenceModel WINDOWS_1252frenchModel = { french_WINDOWS_1252CharToOrderMap, frenchLangModel, (float)0.985451, PR_TRUE, "WINDOWS-1252", "french" };
lgpl-2.1
cstb/ifc2x3-SDK
src/ifc2x3/IfcMemberType.cpp
4492
// IFC SDK : IFC2X3 C++ Early Classes // Copyright (C) 2009 CSTB // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full license is in Licence.txt file included with this // distribution or is available at : // http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html // // This library 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. #include <ifc2x3/IfcMemberType.h> #include <ifc2x3/CopyOp.h> #include <ifc2x3/IfcBuildingElementType.h> #include <ifc2x3/Visitor.h> #include <Step/BaseObject.h> #include <Step/ClassType.h> #include <string> #include "precompiled.h" using namespace ifc2x3; IfcMemberType::IfcMemberType(Step::Id id, Step::SPFData *args) : IfcBuildingElementType(id, args) { m_predefinedType = IfcMemberTypeEnum_UNSET; } IfcMemberType::~IfcMemberType() { } bool IfcMemberType::acceptVisitor(Step::BaseVisitor *visitor) { return static_cast< Visitor * > (visitor)->visitIfcMemberType(this); } const std::string &IfcMemberType::type() const { return IfcMemberType::s_type.getName(); } const Step::ClassType &IfcMemberType::getClassType() { return IfcMemberType::s_type; } const Step::ClassType &IfcMemberType::getType() const { return IfcMemberType::s_type; } bool IfcMemberType::isOfType(const Step::ClassType &t) const { return IfcMemberType::s_type == t ? true : IfcBuildingElementType::isOfType(t); } IfcMemberTypeEnum IfcMemberType::getPredefinedType() { if (Step::BaseObject::inited()) { return m_predefinedType; } else { return IfcMemberTypeEnum_UNSET; } } const IfcMemberTypeEnum IfcMemberType::getPredefinedType() const { IfcMemberType * deConstObject = const_cast< IfcMemberType * > (this); return deConstObject->getPredefinedType(); } void IfcMemberType::setPredefinedType(IfcMemberTypeEnum value) { m_predefinedType = value; } void IfcMemberType::unsetPredefinedType() { m_predefinedType = IfcMemberTypeEnum_UNSET; } bool IfcMemberType::testPredefinedType() const { return getPredefinedType() != IfcMemberTypeEnum_UNSET; } bool IfcMemberType::init() { bool status = IfcBuildingElementType::init(); std::string arg; if (!status) { return false; } arg = m_args->getNext(); if (arg == "$" || arg == "*") { m_predefinedType = IfcMemberTypeEnum_UNSET; } else { if (arg == ".BRACE.") { m_predefinedType = IfcMemberTypeEnum_BRACE; } else if (arg == ".CHORD.") { m_predefinedType = IfcMemberTypeEnum_CHORD; } else if (arg == ".COLLAR.") { m_predefinedType = IfcMemberTypeEnum_COLLAR; } else if (arg == ".MEMBER.") { m_predefinedType = IfcMemberTypeEnum_MEMBER; } else if (arg == ".MULLION.") { m_predefinedType = IfcMemberTypeEnum_MULLION; } else if (arg == ".PLATE.") { m_predefinedType = IfcMemberTypeEnum_PLATE; } else if (arg == ".POST.") { m_predefinedType = IfcMemberTypeEnum_POST; } else if (arg == ".PURLIN.") { m_predefinedType = IfcMemberTypeEnum_PURLIN; } else if (arg == ".RAFTER.") { m_predefinedType = IfcMemberTypeEnum_RAFTER; } else if (arg == ".STRINGER.") { m_predefinedType = IfcMemberTypeEnum_STRINGER; } else if (arg == ".STRUT.") { m_predefinedType = IfcMemberTypeEnum_STRUT; } else if (arg == ".STUD.") { m_predefinedType = IfcMemberTypeEnum_STUD; } else if (arg == ".USERDEFINED.") { m_predefinedType = IfcMemberTypeEnum_USERDEFINED; } else if (arg == ".NOTDEFINED.") { m_predefinedType = IfcMemberTypeEnum_NOTDEFINED; } } return true; } void IfcMemberType::copy(const IfcMemberType &obj, const CopyOp &copyop) { IfcBuildingElementType::copy(obj, copyop); setPredefinedType(obj.m_predefinedType); return; } IFC2X3_EXPORT Step::ClassType IfcMemberType::s_type("IfcMemberType");
lgpl-2.1
lxde/translations
lxqt-panel/plugin-desktopswitch/desktopswitch_pl.ts
2043
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="pl"> <context> <name>DesktopSwitch</name> <message> <location filename="../../../desktopswitch.cpp" line="84"/> <source>Switch to desktop %1</source> <translation>Przełącz na pulpit %1</translation> </message> <message> <location filename="../../../desktopswitch.cpp" line="141"/> <location filename="../../../desktopswitch.cpp" line="151"/> <source>Desktop %1</source> <translation>Pulpit %1</translation> </message> </context> <context> <name>DesktopSwitchConfiguration</name> <message> <location filename="../../../desktopswitchconfiguration.ui" line="14"/> <source>DesktopSwitch settings</source> <translation>Ustawienia przełączania pulpitu</translation> </message> <message> <location filename="../../../desktopswitchconfiguration.ui" line="46"/> <source>Number of rows:</source> <translation>Liczba rzędów:</translation> </message> <message> <location filename="../../../desktopswitchconfiguration.ui" line="39"/> <source>Desktop labels:</source> <translation>Podpisy pulpitów:</translation> </message> <message> <location filename="../../../desktopswitchconfiguration.ui" line="20"/> <source>Appearance</source> <translation>Wygląd</translation> </message> <message> <location filename="../../../desktopswitchconfiguration.ui" line="54"/> <source>Numbers</source> <translation>Liczby</translation> </message> <message> <location filename="../../../desktopswitchconfiguration.ui" line="59"/> <source>Names</source> <translation>Nazwy</translation> </message> <message> <location filename="../../../desktopswitchconfiguration.ui" line="70"/> <source>Desktop names</source> <translation>Nazwy pulpitów</translation> </message> </context> </TS>
lgpl-2.1