repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
simeshev/parabuild-ci
3rdparty/javamail-1.4.2/demo/webapp/src/taglib/demo/MessageInfo.java
8112
/* * Copyright 2001-2007 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package demo; import java.text.*; import java.util.*; import javax.mail.*; import javax.mail.internet.*; /** * Used to store message information. */ public class MessageInfo { private Message message; /** * Returns the bcc field. */ public String getBcc() throws MessagingException { return formatAddresses( message.getRecipients(Message.RecipientType.BCC)); } /** * Returns the body of the message (if it's plain text). */ public String getBody() throws MessagingException, java.io.IOException { Object content = message.getContent(); if (message.isMimeType("text/plain")) { return (String)content; } else if (message.isMimeType("multipart/alternative")) { Multipart mp = (Multipart)message.getContent(); int numParts = mp.getCount(); for (int i = 0; i < numParts; ++i) { if (mp.getBodyPart(i).isMimeType("text/plain")) return (String)mp.getBodyPart(i).getContent(); } return ""; } else if (message.isMimeType("multipart/*")) { Multipart mp = (Multipart)content; if (mp.getBodyPart(0).isMimeType("text/plain")) return (String)mp.getBodyPart(0).getContent(); else return ""; } else return ""; } /** * Returns the cc field. */ public String getCc() throws MessagingException { return formatAddresses( message.getRecipients(Message.RecipientType.CC)); } /** * Returns the date the message was sent (or received if the sent date * is null. */ public String getDate() throws MessagingException { Date date; SimpleDateFormat df = new SimpleDateFormat("EE M/d/yy"); if ((date = message.getSentDate()) != null) return (df.format(date)); else if ((date = message.getReceivedDate()) != null) return (df.format(date)); else return ""; } /** * Returns the from field. */ public String getFrom() throws MessagingException { return formatAddresses(message.getFrom()); } /** * Returns the address to reply to. */ public String getReplyTo() throws MessagingException { Address[] a = message.getReplyTo(); if (a.length > 0) return ((InternetAddress)a[0]).getAddress(); else return ""; } /** * Returns the javax.mail.Message object. */ public Message getMessage() { return message; } /** * Returns the message number. */ public String getNum() { return (Integer.toString(message.getMessageNumber())); } /** * Returns the received date field. */ public String getReceivedDate() throws MessagingException { if (hasReceivedDate()) return (message.getReceivedDate().toString()); else return ""; } /** * Returns the sent date field. */ public String getSentDate() throws MessagingException { if (hasSentDate()) return (message.getSentDate().toString()); else return ""; } /** * Returns the subject field. */ public String getSubject() throws MessagingException { if (hasSubject()) return message.getSubject(); else return ""; } /** * Returns the to field. */ public String getTo() throws MessagingException { return formatAddresses( message.getRecipients(Message.RecipientType.TO)); } /** * Method for checking if the message has attachments. */ public boolean hasAttachments() throws java.io.IOException, MessagingException { boolean hasAttachments = false; if (message.isMimeType("multipart/*")) { Multipart mp = (Multipart)message.getContent(); if (mp.getCount() > 1) hasAttachments = true; } return hasAttachments; } /** * Method for checking if the message has a bcc field. */ public boolean hasBcc() throws MessagingException { return (message.getRecipients(Message.RecipientType.BCC) != null); } /** * Method for checking if the message has a cc field. */ public boolean hasCc() throws MessagingException { return (message.getRecipients(Message.RecipientType.CC) != null); } /** * Method for checking if the message has a date field. */ public boolean hasDate() throws MessagingException { return (hasSentDate() || hasReceivedDate()); } /** * Method for checking if the message has a from field. */ public boolean hasFrom() throws MessagingException { return (message.getFrom() != null); } /** * Method for checking if the message has the desired mime type. */ public boolean hasMimeType(String mimeType) throws MessagingException { return message.isMimeType(mimeType); } /** * Method for checking if the message has a received date field. */ public boolean hasReceivedDate() throws MessagingException { return (message.getReceivedDate() != null); } /** * Method for checking if the message has a sent date field. */ public boolean hasSentDate() throws MessagingException { return (message.getSentDate() != null); } /** * Method for checking if the message has a subject field. */ public boolean hasSubject() throws MessagingException { return (message.getSubject() != null); } /** * Method for checking if the message has a to field. */ public boolean hasTo() throws MessagingException { return (message.getRecipients(Message.RecipientType.TO) != null); } /** * Method for mapping a message to this MessageInfo class. */ public void setMessage(Message message) { this.message = message; } /** * Utility method for formatting msg header addresses. */ private String formatAddresses(Address[] addrs) { if (addrs == null) return ""; StringBuffer strBuf = new StringBuffer(getDisplayAddress(addrs[0])); for (int i = 1; i < addrs.length; i++) { strBuf.append(", ").append(getDisplayAddress(addrs[i])); } return strBuf.toString(); } /** * Utility method which returns a string suitable for msg header display. */ private String getDisplayAddress(Address a) { String pers = null; String addr = null; if (a instanceof InternetAddress && ((pers = ((InternetAddress)a).getPersonal()) != null)) { addr = pers + " "+"&lt;"+((InternetAddress)a).getAddress()+"&gt;"; } else addr = a.toString(); return addr; } }
lgpl-3.0
SoftwareEngineeringToolDemos/FSE-2011-EvoSuite
client/src/main/java/org/evosuite/contracts/SingleContractChecker.java
3120
/** * Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser Public License as published by the * Free Software Foundation, either version 3.0 of the License, or (at your * option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License along * with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ /** * */ package org.evosuite.contracts; import org.evosuite.testcase.statements.Statement; import org.evosuite.testcase.execution.ExecutionObserver; import org.evosuite.testcase.execution.ExecutionResult; import org.evosuite.testcase.execution.Scope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * SingleContractChecker class. * </p> * * @author fraser */ public class SingleContractChecker extends ExecutionObserver { private final Contract contract; private final static Logger logger = LoggerFactory.getLogger(SingleContractChecker.class); private boolean valid = true; /** * <p> * Constructor for SingleContractChecker. * </p> * * @param contract * a {@link org.evosuite.contracts.Contract} object. */ public SingleContractChecker(Contract contract) { this.contract = contract; } /** * <p> * isValid * </p> * * @return a boolean. */ public boolean isValid() { return valid; } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#output(int, java.lang.String) */ /** {@inheritDoc} */ @Override public void output(int position, String output) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#statement(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope, java.lang.Throwable) */ /** {@inheritDoc} */ @Override public void afterStatement(Statement statement, Scope scope, Throwable exception) { try { logger.debug("Checking contract "+contract); if (contract.check(statement, scope, exception) != null) { //FailingTestSet.addFailingTest(currentTest, contract, statement, exception); valid = false; } } catch (Throwable t) { logger.info("Caught exception during contract checking: "+t); } } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#beforeStatement(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope) */ @Override public void beforeStatement(Statement statement, Scope scope) { // Do nothing } /* (non-Javadoc) * @see org.evosuite.testcase.ExecutionObserver#clear() */ /** {@inheritDoc} */ @Override public void clear() { // TODO Auto-generated method stub } @Override public void testExecutionFinished(ExecutionResult r, Scope s) { // do nothing } }
lgpl-3.0
Bananasft/MBINCompiler
MBINCompiler/Models/Structs/TkVertexElement.cs
481
namespace MBINCompiler.Models.Structs { public class TkVertexElement : NMSTemplate { public int SemanticID; public int Size; public int Type; // 0x140b(Vec4) or 0x1401(Vec2) public int Offset; public int Normalise; public int Instancing; public string[] InstancingValues() { return new[] { "PerVertex", "PerModel" }; } [NMS(Size = 8)] public string PlatformData; } }
lgpl-3.0
johngerome/Flux-CP-themes---Design-no-3
modules/ranking/death.php
1701
<?php if (!defined('FLUX_ROOT')) exit; $title = 'Death Ranking'; $classes = Flux::config('JobClasses')->toArray(); $jobClass = $params->get('jobclass'); $bind = array((int)Flux::config('RankingHideLevel')); if (trim($jobClass) === '') { $jobClass = null; } if (!is_null($jobClass) && !array_key_exists($jobClass, $classes)) { $this->deny(); } $col = "ch.char_id, ch.name AS char_name, ch.class AS char_class, ch.base_level, ch.job_level, "; $col .= "ch.guild_id, guild.name AS guild_name, guild.emblem_len AS guild_emblem_len, "; $col .= "CAST(IFNULL(reg.value, '0') AS UNSIGNED) AS death_count"; $sql = "SELECT $col FROM {$server->charMapDatabase}.`char` AS ch "; $sql .= "LEFT JOIN {$server->charMapDatabase}.guild ON guild.guild_id = ch.guild_id "; $sql .= "LEFT JOIN {$server->loginDatabase}.login ON login.account_id = ch.account_id "; $sql .= "LEFT JOIN {$server->charMapDatabase}.`global_reg_value` AS reg ON reg.char_id = ch.char_id AND reg.str = 'PC_DIE_COUNTER' "; $sql .= "WHERE 1=1 "; if (Flux::config('HidePermBannedDeathRank')) { $sql .= "AND login.state != 5 "; } if (Flux::config('HideTempBannedDeathRank')) { $sql .= "AND (login.unban_time IS NULL OR login.unban_time = 0) "; } $sql .= "AND login.level < ? "; if ($days=Flux::config('DeathRankingThreshold')) { $sql .= 'AND TIMESTAMPDIFF(DAY, login.lastlogin, NOW()) <= ? '; $bind[] = $days * 24 * 60 * 60; } if (!is_null($jobClass)) { $sql .= "AND ch.class = ? "; $bind[] = $jobClass; } $sql .= "ORDER BY death_count DESC, ch.char_id DESC "; $sql .= "LIMIT ".(int)Flux::config('DeathRankingLimit'); $sth = $server->connection->getStatement($sql); $sth->execute($bind); $chars = $sth->fetchAll(); ?>
lgpl-3.0
mohanaraosv/sonarqube
server/sonar-server/src/test/java/org/sonar/server/computation/component/ReportComponent.java
5626
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.component; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Arrays.asList; /** * Implementation of {@link Component} to unit test report components. */ public class ReportComponent implements Component { private static final FileAttributes DEFAULT_FILE_ATTRIBUTES = new FileAttributes(false, null); public static final Component DUMB_PROJECT = builder(Type.PROJECT, 1).setKey("PROJECT_KEY").setUuid("PROJECT_UUID").setName("Project Name").setVersion("1.0-SNAPSHOT").build(); private final Type type; private final String name; private final String key; private final String uuid; private final ReportAttributes reportAttributes; private final FileAttributes fileAttributes; private final List<Component> children; private ReportComponent(Builder builder) { this.type = builder.type; this.key = builder.key; this.name = builder.name == null ? String.valueOf(builder.key) : builder.name; this.uuid = builder.uuid; this.reportAttributes = new ReportAttributes(builder.ref, builder.version); this.fileAttributes = builder.fileAttributes == null ? DEFAULT_FILE_ATTRIBUTES : builder.fileAttributes; this.children = ImmutableList.copyOf(builder.children); } @Override public Type getType() { return type; } @Override public String getUuid() { if (uuid == null) { throw new UnsupportedOperationException(String.format("Component uuid of ref '%d' has not be fed yet", this.reportAttributes.getRef())); } return uuid; } @Override public String getKey() { if (key == null) { throw new UnsupportedOperationException(String.format("Component key of ref '%d' has not be fed yet", this.reportAttributes.getRef())); } return key; } @Override public String getName() { return this.name; } @Override public List<Component> getChildren() { return children; } @Override public ReportAttributes getReportAttributes() { return this.reportAttributes; } @Override public FileAttributes getFileAttributes() { checkState(this.type == Type.FILE, "Only component of type FILE can have a FileAttributes object"); return this.fileAttributes; } @Override public ProjectViewAttributes getProjectViewAttributes() { throw new IllegalStateException("Only component of type PROJECT_VIEW can have a ProjectViewAttributes object"); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReportComponent that = (ReportComponent) o; return reportAttributes.getRef() == that.reportAttributes.getRef(); } @Override public int hashCode() { return this.reportAttributes.getRef(); } @Override public String toString() { return "ReportComponent{" + "ref=" + this.reportAttributes.getRef() + ", key='" + key + '\'' + ", type=" + type + '}'; } public static Builder builder(Type type, int ref) { return new Builder(type, ref); } public static final class Builder { private final Type type; private final int ref; private String uuid; private String key; private String name; private String version; private FileAttributes fileAttributes; private final List<Component> children = new ArrayList<>(); private Builder(Type type, int ref) { checkArgument(type.isReportType(), "Component type must not be a report type"); this.type = type; this.ref = ref; } public Builder setUuid(@Nullable String s) { this.uuid = s; return this; } public Builder setName(@Nullable String s) { this.name = s; return this; } public Builder setKey(@Nullable String s) { this.key = s; return this; } public Builder setVersion(@Nullable String s) { this.version = s; return this; } public Builder setFileAttributes(FileAttributes fileAttributes){ checkState(type == Type.FILE, "Only Component of type File can have File attributes"); this.fileAttributes = fileAttributes; return this; } public Builder addChildren(Component... c) { for (Component component : c) { checkArgument(component.getType().isReportType()); } this.children.addAll(asList(c)); return this; } public ReportComponent build() { return new ReportComponent(this); } } }
lgpl-3.0
Builders-SonarSource/sonarqube-bis
sonar-duplications/src/test/java/org/sonar/duplications/statement/StatementChannelTest.java
3959
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * 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 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 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.duplications.statement; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.mockito.Matchers; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.duplications.statement.matcher.AnyTokenMatcher; import org.sonar.duplications.statement.matcher.TokenMatcher; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; public class StatementChannelTest { @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNull() { StatementChannel.create((TokenMatcher[]) null); } @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptEmpty() { StatementChannel.create(new TokenMatcher[] {}); } @Test public void shouldPushForward() { TokenQueue tokenQueue = mock(TokenQueue.class); TokenMatcher matcher = mock(TokenMatcher.class); List<Statement> output = mock(List.class); StatementChannel channel = StatementChannel.create(matcher); assertThat(channel.consume(tokenQueue, output), is(false)); ArgumentCaptor<List> matchedTokenList = ArgumentCaptor.forClass(List.class); verify(matcher).matchToken(Matchers.eq(tokenQueue), matchedTokenList.capture()); verifyNoMoreInteractions(matcher); verify(tokenQueue).pushForward(matchedTokenList.getValue()); verifyNoMoreInteractions(tokenQueue); verifyNoMoreInteractions(output); } @Test public void shouldCreateStatement() { Token token = new Token("a", 1, 1); TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(token))); TokenMatcher matcher = spy(new AnyTokenMatcher()); StatementChannel channel = StatementChannel.create(matcher); List<Statement> output = mock(List.class); assertThat(channel.consume(tokenQueue, output), is(true)); verify(matcher).matchToken(Matchers.eq(tokenQueue), Matchers.anyList()); verifyNoMoreInteractions(matcher); ArgumentCaptor<Statement> statement = ArgumentCaptor.forClass(Statement.class); verify(output).add(statement.capture()); assertThat(statement.getValue().getValue(), is("a")); assertThat(statement.getValue().getStartLine(), is(1)); assertThat(statement.getValue().getEndLine(), is(1)); verifyNoMoreInteractions(output); } @Test public void shouldNotCreateStatement() { TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(new Token("a", 1, 1)))); TokenMatcher matcher = spy(new AnyTokenMatcher()); StatementChannel channel = StatementChannel.create(matcher); List<Statement> output = mock(List.class); assertThat(channel.consume(tokenQueue, output), is(true)); verify(matcher).matchToken(Matchers.eq(tokenQueue), Matchers.anyList()); verifyNoMoreInteractions(matcher); verify(output).add(Matchers.any(Statement.class)); verifyNoMoreInteractions(output); } }
lgpl-3.0
dailypips/cocoflow
test/benchmark_sleep.cc
1072
#include <string.h> #include <time.h> #include <iostream> #include "cocoflow.h" using namespace std; #define TEST_TIMES 1000 #define TEST_NUM 1000 #define ASSERT(x) \ do { \ if (!(x)) \ { \ fprintf(stderr, "[ASSERT]: " #x " failed at " __FILE__ ":%u\n", __LINE__); \ abort(); \ } \ } while(0) static clock_t time_bgn, time_cut, time_end; typedef ccf::task<15> test_task; class sleep_task: public test_task { void run() { for (int i=0; i<TEST_TIMES; i++) { ccf::sleep s(0); await(s); } } }; class main_task: public test_task { void run() { for (int i=0; i<TEST_NUM; i++) { sleep_task* s = new sleep_task(); ASSERT(s->status() == ccf::ready); ccf::start(s); } } }; int main() { time_bgn = clock(); ccf::event_task::init(1); test_task::init(TEST_NUM + 1); main_task tMain; time_cut = clock(); ccf::cocoflow(tMain); time_end = clock(); cout << "Init: " << (time_cut - time_bgn) << endl; cout << "Proc: " << (time_end - time_cut) << endl; cout << "Total: " << (time_end - time_bgn) << endl; return 0; }
lgpl-3.0
peterstevens130561/sonarlint-vs
its/PcapDotNet-71480/PcapDotNet.Packets/Dns/DnsDatagram.cs
24671
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Dns { /// <summary> /// RFC 1035, 4035. /// All communications inside of the domain protocol are carried in a single format called a message. /// The top level format of message is divided into 5 sections (some of which are empty in certain cases) shown below: /// <pre> /// +-----+----+--------+----+----+----+----+---+----+----+-------+ /// | bit | 0 | 1-4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12-15 | /// +-----+----+--------+----+----+----+----+---+----+----+-------+ /// | 0 | ID | /// +-----+----+--------+----+----+----+----+---+----+----+-------+ /// | 16 | QR | Opcode | AA | TC | RD | RA | Z | AD | CD | RCODE | /// +-----+----+--------+----+----+----+----+---+----+----+-------+ /// | 32 | QDCOUNT | /// +-----+-------------------------------------------------------+ /// | 48 | ANCOUNT | /// +-----+-------------------------------------------------------+ /// | 64 | NSCOUNT | /// +-----+-------------------------------------------------------+ /// | 80 | ARCOUNT | /// +-----+-------------------------------------------------------+ /// | 96 | Question - the question for the name server | /// +-----+-------------------------------------------------------+ /// | | Answer - RRs answering the question | /// +-----+-------------------------------------------------------+ /// | | Authority - RRs pointing toward an authority | /// +-----+-------------------------------------------------------+ /// | | Additional - RRs holding additional information | /// +-----+-------------------------------------------------------+ /// </pre> /// The header section is always present. /// The header includes fields that specify which of the remaining sections are present, /// and also specify whether the message is a query or a response, a standard query or some other opcode, etc. /// The names of the sections after the header are derived from their use in standard queries. /// The question section contains fields that describe a question to a name server. /// These fields are a query type (QTYPE), a query class (QCLASS), and a query domain name (QNAME). /// The last three sections have the same format: a possibly empty list of concatenated resource records (RRs). /// The answer section contains RRs that answer the question; the authority section contains RRs that point toward an authoritative name server; /// the additional records section contains RRs which relate to the query, but are not strictly answers for the question. /// </summary> public sealed class DnsDatagram : Datagram { private static class Offset { public const int Id = 0; public const int IsResponse = 2; public const int OpCode = 2; public const int IsAuthoritiveAnswer = 2; public const int IsTruncated = 2; public const int IsRecusionDesired = 2; public const int IsRecusionAvailable = 3; public const int FutureUse = 3; public const int IsAuthenticData = 3; public const int IsCheckingDisabled = 3; public const int ResponseCode = 3; public const int QueryCount = 4; public const int AnswerCount = 6; public const int AuthorityCount = 8; public const int AdditionalCount = 10; public const int Query = 12; } private static class Mask { public const byte IsResponse = 0x80; public const byte OpCode = 0x78; public const byte IsAuthoritiveAnswer = 0x04; public const byte IsTruncated = 0x02; public const byte IsRecusionDesired = 0x01; public const byte IsRecursionAvailable = 0x80; public const byte FutureUse = 0x40; public const byte IsAuthenticData = 0x20; public const byte IsCheckingDisabled = 0x10; public const ushort ResponseCode = 0x000F; } private static class Shift { public const int OpCode = 3; } /// <summary> /// The number of bytes the DNS header takes. /// </summary> public const int HeaderLength = Offset.Query; /// <summary> /// A 16 bit identifier assigned by the program that generates any kind of query. /// This identifier is copied the corresponding reply and can be used by the requester to match up replies to outstanding queries. /// </summary> public ushort Id { get { return ReadUShort(Offset.Id, Endianity.Big); } } /// <summary> /// A one bit field that specifies whether this message is a query (0), or a response (1). /// </summary> public bool IsResponse { get { return ReadBool(Offset.IsResponse, Mask.IsResponse); } } /// <summary> /// Specifies whether this message is a query or a response. /// </summary> public bool IsQuery { get { return !IsResponse; } } /// <summary> /// Specifies kind of query in this message. /// This value is set by the originator of a query and copied into the response. /// </summary> public DnsOpCode OpCode { get { return (DnsOpCode)((this[Offset.OpCode] & Mask.OpCode) >> Shift.OpCode); } } /// <summary> /// This bit is valid in responses, and specifies that the responding name server is an authority for the domain name in question section. /// Note that the contents of the answer section may have multiple owner names because of aliases. /// The AA bit corresponds to the name which matches the query name, or the first owner name in the answer section. /// </summary> public bool IsAuthoritativeAnswer { get { return ReadBool(Offset.IsAuthoritiveAnswer, Mask.IsAuthoritiveAnswer); } } /// <summary> /// Specifies that this message was truncated due to length greater than that permitted on the transmission channel. /// </summary> public bool IsTruncated { get { return ReadBool(Offset.IsTruncated, Mask.IsTruncated); } } /// <summary> /// This bit may be set in a query and is copied into the response. /// If RD is set, it directs the name server to pursue the query recursively. /// Recursive query support is optional. /// </summary> public bool IsRecursionDesired { get { return ReadBool(Offset.IsRecusionDesired, Mask.IsRecusionDesired); } } /// <summary> /// This bit is set or cleared in a response, and denotes whether recursive query support is available in the name server. /// </summary> public bool IsRecursionAvailable { get { return ReadBool(Offset.IsRecusionAvailable, Mask.IsRecursionAvailable); } } /// <summary> /// Reserved for future use. /// Must be false in all queries and responses. /// </summary> public bool FutureUse { get { return ReadBool(Offset.FutureUse, Mask.FutureUse); } } /// <summary> /// The name server side of a security-aware recursive name server must not set the AD bit in a response /// unless the name server considers all RRsets in the Answer and Authority sections of the response to be authentic. /// The name server side should set the AD bit if and only if the resolver side considers all RRsets in the Answer section /// and any relevant negative response RRs in the Authority section to be authentic. /// The resolver side must follow the Authenticating DNS Responses procedure to determine whether the RRs in question are authentic. /// However, for backward compatibility, a recursive name server may set the AD bit when a response includes unsigned CNAME RRs /// if those CNAME RRs demonstrably could have been synthesized from an authentic DNAME RR that is also included in the response /// according to the synthesis rules described in RFC 2672. /// </summary> public bool IsAuthenticData { get { return ReadBool(Offset.IsAuthenticData, Mask.IsAuthenticData); } } /// <summary> /// Exists in order to allow a security-aware resolver to disable signature validation /// in a security-aware name server's processing of a particular query. /// /// The name server side must copy the setting of the CD bit from a query to the corresponding response. /// /// The name server side of a security-aware recursive name server must pass the state of the CD bit to the resolver side /// along with the rest of an initiating query, /// so that the resolver side will know whether it is required to verify the response data it returns to the name server side. /// If the CD bit is set, it indicates that the originating resolver is willing to perform whatever authentication its local policy requires. /// Thus, the resolver side of the recursive name server need not perform authentication on the RRsets in the response. /// When the CD bit is set, the recursive name server should, if possible, return the requested data to the originating resolver, /// even if the recursive name server's local authentication policy would reject the records in question. /// That is, by setting the CD bit, the originating resolver has indicated that it takes responsibility for performing its own authentication, /// and the recursive name server should not interfere. /// /// If the resolver side implements a BAD cache and the name server side receives a query that matches an entry in the resolver side's BAD cache, /// the name server side's response depends on the state of the CD bit in the original query. /// If the CD bit is set, the name server side should return the data from the BAD cache; /// if the CD bit is not set, the name server side must return RCODE 2 (server failure). /// /// The intent of the above rule is to provide the raw data to clients that are capable of performing their own signature verification checks /// while protecting clients that depend on the resolver side of a security-aware recursive name server to perform such checks. /// Several of the possible reasons why signature validation might fail involve conditions /// that may not apply equally to the recursive name server and the client that invoked it. /// For example, the recursive name server's clock may be set incorrectly, or the client may have knowledge of a relevant island of security /// that the recursive name server does not share. /// In such cases, "protecting" a client that is capable of performing its own signature validation from ever seeing the "bad" data does not help the client. /// </summary> public bool IsCheckingDisabled { get { return ReadBool(Offset.IsCheckingDisabled, Mask.IsCheckingDisabled); } } /// <summary> /// A response of the server that can sign errors or other messages. /// </summary> public DnsResponseCode ResponseCode { get { return (DnsResponseCode)(this[Offset.ResponseCode] & Mask.ResponseCode); } } /// <summary> /// An unsigned 16 bit integer specifying the number of entries in the question section. /// </summary> public ushort QueryCount { get { return ReadUShort(Offset.QueryCount, Endianity.Big); } } /// <summary> /// An unsigned 16 bit integer specifying the number of resource records in the answer section. /// </summary> public ushort AnswerCount { get { return ReadUShort(Offset.AnswerCount, Endianity.Big); } } /// <summary> /// An unsigned 16 bit integer specifying the number of name server resource records in the authority records section. /// </summary> public ushort AuthorityCount { get { return ReadUShort(Offset.AuthorityCount, Endianity.Big); } } /// <summary> /// An unsigned 16 bit integer specifying the number of resource records in the additional records section. /// </summary> public ushort AdditionalCount { get { return ReadUShort(Offset.AdditionalCount, Endianity.Big); } } /// <summary> /// The queries resource records. /// The amount of records here should be equal to <see cref="QueryCount"/>. /// Typically exactly one query will exist. /// </summary> public ReadOnlyCollection<DnsQueryResourceRecord> Queries { get { ParseQueries(); return _queries; } } /// <summary> /// The answers resource records. /// The amount of records here should be equal to <see cref="AnswerCount"/>. /// </summary> public ReadOnlyCollection<DnsDataResourceRecord> Answers { get { ParseAnswers(); return _answers; } } /// <summary> /// The authorities resource records. /// The amount of records here should be equal to <see cref="AuthorityCount"/>. /// </summary> public ReadOnlyCollection<DnsDataResourceRecord> Authorities { get { ParseAuthorities(); return _authorities; } } /// <summary> /// The additionals resource records. /// The amount of records here should be equal to <see cref="AdditionalCount"/>. /// </summary> public ReadOnlyCollection<DnsDataResourceRecord> Additionals { get { ParseAdditionals(); return _additionals; } } /// <summary> /// All the resource records in the datagram by order of appearance. /// </summary> public IEnumerable<DnsResourceRecord> ResourceRecords { get { return Queries.Cast<DnsResourceRecord>().Concat(DataResourceRecords); } } /// <summary> /// All the data resource records (all resource records but the queries) in the datagram by order of appearance. /// </summary> public IEnumerable<DnsDataResourceRecord> DataResourceRecords { get { return Answers.Concat(Authorities).Concat(Additionals); } } /// <summary> /// The special OPT resource record. /// This takes the first OPT resource record in additional section. /// </summary> public DnsOptResourceRecord OptionsRecord { get { ParseAdditionals(); return _options; } } /// <summary> /// Creates a Layer that represents the datagram to be used with PacketBuilder. /// </summary> public override ILayer ExtractLayer() { return new DnsLayer { Id = Id, IsQuery = IsQuery, OpCode = OpCode, IsAuthoritativeAnswer = IsAuthoritativeAnswer, IsTruncated = IsTruncated, IsRecursionDesired = IsRecursionDesired, IsRecursionAvailable = IsRecursionAvailable, FutureUse = FutureUse, IsAuthenticData = IsAuthenticData, IsCheckingDisabled = IsCheckingDisabled, ResponseCode = ResponseCode, Queries = Queries.ToList(), Answers = Answers.ToList(), Authorities = Authorities.ToList(), Additionals = Additionals.ToList(), }; } /// <summary> /// A DNS datagram is valid if parsing of all sections was successful. /// </summary> protected override bool CalculateIsValid() { if (_isValid == null) { _isValid = Length >= HeaderLength && QueryCount == Queries.Count && AnswerCount == Answers.Count && AuthorityCount == Authorities.Count && AdditionalCount == Additionals.Count; } return _isValid.Value; } internal DnsDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } internal static int GetLength(IEnumerable<DnsResourceRecord> resourceRecords, DnsDomainNameCompressionMode domainNameCompressionMode) { int length = HeaderLength; DnsDomainNameCompressionData compressionData = new DnsDomainNameCompressionData(domainNameCompressionMode); if (resourceRecords != null) { foreach (DnsResourceRecord record in resourceRecords) length += record.GetLength(compressionData, length); } return length; } internal static void Write(byte[] buffer, int offset, ushort id, bool isResponse, DnsOpCode opCode, bool isAuthoritiveAnswer, bool isTruncated, bool isRecursionDesired, bool isRecursionAvailable, bool futureUse, bool isAuthenticData, bool isCheckingDisabled, DnsResponseCode responseCode, IList<DnsQueryResourceRecord> queries, IList<DnsDataResourceRecord> answers, IList<DnsDataResourceRecord> authorities, IList<DnsDataResourceRecord> additionals, DnsDomainNameCompressionMode domainNameCompressionMode) { buffer.Write(offset + Offset.Id, id, Endianity.Big); byte flags0 = 0; if (isResponse) flags0 |= Mask.IsResponse; flags0 |= (byte)((((byte)opCode) << Shift.OpCode) & Mask.OpCode); if (isAuthoritiveAnswer) flags0 |= Mask.IsAuthoritiveAnswer; if (isTruncated) flags0 |= Mask.IsTruncated; if (isRecursionDesired) flags0 |= Mask.IsRecusionDesired; buffer.Write(offset + Offset.IsResponse, flags0); byte flags1 = 0; if (isRecursionAvailable) flags1 |= Mask.IsRecursionAvailable; if (futureUse) flags1 |= Mask.FutureUse; if (isAuthenticData) flags1 |= Mask.IsAuthenticData; if (isCheckingDisabled) flags1 |= Mask.IsCheckingDisabled; flags1 |= (byte)((ushort)responseCode & Mask.ResponseCode); buffer.Write(offset + Offset.IsRecusionAvailable, flags1); DnsDomainNameCompressionData compressionData = new DnsDomainNameCompressionData(domainNameCompressionMode); int recordOffset = HeaderLength; if (queries != null) { buffer.Write(offset + Offset.QueryCount, (ushort)queries.Count, Endianity.Big); foreach (DnsQueryResourceRecord record in queries) recordOffset += record.Write(buffer, offset, compressionData, recordOffset); } if (answers != null) { buffer.Write(offset + Offset.AnswerCount, (ushort)answers.Count, Endianity.Big); foreach (DnsDataResourceRecord record in answers) recordOffset += record.Write(buffer, offset, compressionData, recordOffset); } if (authorities != null) { buffer.Write(offset + Offset.AuthorityCount, (ushort)authorities.Count, Endianity.Big); foreach (DnsDataResourceRecord record in authorities) recordOffset += record.Write(buffer, offset, compressionData, recordOffset); } if (additionals != null) { buffer.Write(offset + Offset.AdditionalCount, (ushort)additionals.Count, Endianity.Big); foreach (DnsDataResourceRecord record in additionals) recordOffset += record.Write(buffer, offset, compressionData, recordOffset); } } private int AnswersOffset { get { ParseQueries(); return _answersOffset; } } private int AuthoritiesOffset { get { ParseAnswers(); return _authoritiesOffset; } } private int AdditionalsOffset { get { ParseAuthorities(); return _additionalsOffset; } } private void ParseQueries() { ParseRecords(Offset.Query, () => QueryCount, DnsQueryResourceRecord.Parse, ref _queries, ref _answersOffset); } private void ParseAnswers() { ParseRecords(AnswersOffset, () => AnswerCount, DnsDataResourceRecord.Parse, ref _answers, ref _authoritiesOffset); } private void ParseAuthorities() { ParseRecords(AuthoritiesOffset, () => AuthorityCount, DnsDataResourceRecord.Parse, ref _authorities, ref _additionalsOffset); } private void ParseAdditionals() { int nextOffset = 0; if (ParseRecords(AdditionalsOffset, () => AdditionalCount, DnsDataResourceRecord.Parse, ref _additionals, ref nextOffset) && _additionals != null) { _options = (DnsOptResourceRecord)_additionals.FirstOrDefault(additional => additional.DnsType == DnsType.Opt); } } private delegate TRecord ParseRecord<out TRecord>(DnsDatagram dns, int offset, out int numBytesRead); private bool ParseRecords<TRecord>(int offset, Func<ushort> countDelegate, ParseRecord<TRecord> parseRecord, ref ReadOnlyCollection<TRecord> parsedRecords, ref int nextOffset) where TRecord : DnsResourceRecord { if (parsedRecords == null && Length >= offset) { ushort count = countDelegate(); List<TRecord> records = new List<TRecord>(count); for (int i = 0; i != count; ++i) { int numBytesRead; TRecord record = parseRecord(this, offset, out numBytesRead); if (record == null) { offset = 0; break; } records.Add(record); offset += numBytesRead; } parsedRecords = new ReadOnlyCollection<TRecord>(records.ToArray()); nextOffset = offset; return true; } return false; } private ReadOnlyCollection<DnsQueryResourceRecord> _queries; private ReadOnlyCollection<DnsDataResourceRecord> _answers; private ReadOnlyCollection<DnsDataResourceRecord> _authorities; private ReadOnlyCollection<DnsDataResourceRecord> _additionals; private DnsOptResourceRecord _options; private int _answersOffset; private int _authoritiesOffset; private int _additionalsOffset; private bool? _isValid; } }
lgpl-3.0
malaverdiere/jseduite
hci/WebAdmin-IRSAM/src/java/webadmin/feedregistry/comparators/FeedRegistryClassComparatorDesc.java
413
package webadmin.feedregistry.comparators; import fr.unice.i3s.modalis.jseduite.technical.registry.Feed; import java.util.Comparator; /** * * @author Steve Colombié */ public class FeedRegistryClassComparatorDesc implements Comparator<Feed>{ public int compare(Feed o1, Feed o2) { return o2.getFeedClass().getName().toUpperCase().compareTo(o1.getFeedClass().getName().toUpperCase()); } }
lgpl-3.0
find-sec-bugs/find-sec-bugs
findsecbugs-samples-java/src/test/java/testcode/file/FileUploadCommon.java
714
package testcode.file; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.http.HttpServletRequest; import java.util.List; public class FileUploadCommon { public void handleFile(HttpServletRequest req) throws FileUploadException { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> fileItems = upload.parseRequest(req); for (FileItem item : fileItems) { System.out.println("Saving " + item.getName() + "..."); } } }
lgpl-3.0
iris-edu/pyweed
pyweed/gui/uic/WaveformDialog.py
14264
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'WaveformDialog.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_WaveformDialog(object): def setupUi(self, WaveformDialog): WaveformDialog.setObjectName("WaveformDialog") WaveformDialog.resize(1284, 724) self.verticalLayout = QtWidgets.QVBoxLayout(WaveformDialog) self.verticalLayout.setSpacing(0) self.verticalLayout.setObjectName("verticalLayout") self.topFrame = QtWidgets.QFrame(WaveformDialog) self.topFrame.setFrameShape(QtWidgets.QFrame.NoFrame) self.topFrame.setFrameShadow(QtWidgets.QFrame.Plain) self.topFrame.setObjectName("topFrame") self.horizontalLayout = QtWidgets.QHBoxLayout(self.topFrame) self.horizontalLayout.setContentsMargins(2, 2, 2, 2) self.horizontalLayout.setObjectName("horizontalLayout") self.downloadGroupBox = QtWidgets.QGroupBox(self.topFrame) self.downloadGroupBox.setEnabled(True) self.downloadGroupBox.setObjectName("downloadGroupBox") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.downloadGroupBox) self.verticalLayout_6.setContentsMargins(2, 2, 2, 2) self.verticalLayout_6.setSpacing(2) self.verticalLayout_6.setObjectName("verticalLayout_6") self.gridLayout = QtWidgets.QGridLayout() self.gridLayout.setVerticalSpacing(2) self.gridLayout.setObjectName("gridLayout") self.secondsBeforeLabel = QtWidgets.QLabel(self.downloadGroupBox) self.secondsBeforeLabel.setObjectName("secondsBeforeLabel") self.gridLayout.addWidget(self.secondsBeforeLabel, 0, 0, 1, 1) self.label = QtWidgets.QLabel(self.downloadGroupBox) self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 0, 2, 1, 1) self.secondsAfterPhaseComboBox = QtWidgets.QComboBox(self.downloadGroupBox) self.secondsAfterPhaseComboBox.setObjectName("secondsAfterPhaseComboBox") self.gridLayout.addWidget(self.secondsAfterPhaseComboBox, 1, 3, 1, 1) self.secondsBeforePhaseComboBox = QtWidgets.QComboBox(self.downloadGroupBox) self.secondsBeforePhaseComboBox.setObjectName("secondsBeforePhaseComboBox") self.gridLayout.addWidget(self.secondsBeforePhaseComboBox, 0, 3, 1, 1) spacerItem = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 0, 4, 1, 1) self.secondsAfterSpinBox = QtWidgets.QSpinBox(self.downloadGroupBox) self.secondsAfterSpinBox.setMaximum(21600) self.secondsAfterSpinBox.setSingleStep(100) self.secondsAfterSpinBox.setProperty("value", 600) self.secondsAfterSpinBox.setObjectName("secondsAfterSpinBox") self.gridLayout.addWidget(self.secondsAfterSpinBox, 1, 1, 1, 1) self.secondsBeforeSpinBox = QtWidgets.QSpinBox(self.downloadGroupBox) self.secondsBeforeSpinBox.setMaximum(3600) self.secondsBeforeSpinBox.setSingleStep(10) self.secondsBeforeSpinBox.setProperty("value", 60) self.secondsBeforeSpinBox.setObjectName("secondsBeforeSpinBox") self.gridLayout.addWidget(self.secondsBeforeSpinBox, 0, 1, 1, 1) self.label_2 = QtWidgets.QLabel(self.downloadGroupBox) self.label_2.setObjectName("label_2") self.gridLayout.addWidget(self.label_2, 1, 2, 1, 1) self.secondsAfterLabel = QtWidgets.QLabel(self.downloadGroupBox) self.secondsAfterLabel.setObjectName("secondsAfterLabel") self.gridLayout.addWidget(self.secondsAfterLabel, 1, 0, 1, 1) self.verticalLayout_6.addLayout(self.gridLayout) self.widget_5 = QtWidgets.QWidget(self.downloadGroupBox) self.widget_5.setObjectName("widget_5") self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.widget_5) self.horizontalLayout_7.setContentsMargins(2, 2, 2, 2) self.horizontalLayout_7.setObjectName("horizontalLayout_7") self.downloadPushButton = QtWidgets.QPushButton(self.widget_5) self.downloadPushButton.setMinimumSize(QtCore.QSize(200, 0)) self.downloadPushButton.setCheckable(False) self.downloadPushButton.setObjectName("downloadPushButton") self.horizontalLayout_7.addWidget(self.downloadPushButton) self.downloadStatusLabel = QtWidgets.QLabel(self.widget_5) self.downloadStatusLabel.setObjectName("downloadStatusLabel") self.horizontalLayout_7.addWidget(self.downloadStatusLabel, 0, QtCore.Qt.AlignLeft) self.verticalLayout_6.addWidget(self.widget_5) self.horizontalLayout.addWidget(self.downloadGroupBox) self.saveGroupBox = QtWidgets.QGroupBox(self.topFrame) self.saveGroupBox.setEnabled(True) self.saveGroupBox.setObjectName("saveGroupBox") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.saveGroupBox) self.verticalLayout_5.setContentsMargins(2, 2, 2, 2) self.verticalLayout_5.setSpacing(2) self.verticalLayout_5.setObjectName("verticalLayout_5") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setVerticalSpacing(2) self.gridLayout_2.setObjectName("gridLayout_2") self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.saveFormatComboBox = QtWidgets.QComboBox(self.saveGroupBox) self.saveFormatComboBox.setObjectName("saveFormatComboBox") self.horizontalLayout_4.addWidget(self.saveFormatComboBox) self.sacUseEventTimeCheckBox = QtWidgets.QCheckBox(self.saveGroupBox) self.sacUseEventTimeCheckBox.setWhatsThis("") self.sacUseEventTimeCheckBox.setObjectName("sacUseEventTimeCheckBox") self.horizontalLayout_4.addWidget(self.sacUseEventTimeCheckBox) spacerItem1 = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem1) self.horizontalLayout_4.setStretch(2, 1) self.gridLayout_2.addLayout(self.horizontalLayout_4, 1, 1, 1, 1) self.saveDirectoryLabel = QtWidgets.QLabel(self.saveGroupBox) self.saveDirectoryLabel.setObjectName("saveDirectoryLabel") self.gridLayout_2.addWidget(self.saveDirectoryLabel, 0, 0, 1, 1) self.saveFormatLabel = QtWidgets.QLabel(self.saveGroupBox) self.saveFormatLabel.setObjectName("saveFormatLabel") self.gridLayout_2.addWidget(self.saveFormatLabel, 1, 0, 1, 1) self.horizontalLayout_6 = QtWidgets.QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.saveDirectoryPushButton = QtWidgets.QPushButton(self.saveGroupBox) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.saveDirectoryPushButton.sizePolicy().hasHeightForWidth()) self.saveDirectoryPushButton.setSizePolicy(sizePolicy) self.saveDirectoryPushButton.setFocusPolicy(QtCore.Qt.NoFocus) self.saveDirectoryPushButton.setStyleSheet("QPushButton { text-align: left; }") self.saveDirectoryPushButton.setObjectName("saveDirectoryPushButton") self.horizontalLayout_6.addWidget(self.saveDirectoryPushButton) self.saveDirectoryBrowseToolButton = QtWidgets.QToolButton(self.saveGroupBox) self.saveDirectoryBrowseToolButton.setIconSize(QtCore.QSize(16, 16)) self.saveDirectoryBrowseToolButton.setObjectName("saveDirectoryBrowseToolButton") self.horizontalLayout_6.addWidget(self.saveDirectoryBrowseToolButton) spacerItem2 = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_6.addItem(spacerItem2) self.horizontalLayout_6.setStretch(2, 1) self.gridLayout_2.addLayout(self.horizontalLayout_6, 0, 1, 1, 1) self.verticalLayout_5.addLayout(self.gridLayout_2) self.widget_6 = QtWidgets.QWidget(self.saveGroupBox) self.widget_6.setObjectName("widget_6") self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.widget_6) self.horizontalLayout_8.setContentsMargins(2, 2, 2, 2) self.horizontalLayout_8.setObjectName("horizontalLayout_8") self.savePushButton = QtWidgets.QPushButton(self.widget_6) self.savePushButton.setMinimumSize(QtCore.QSize(200, 0)) self.savePushButton.setCheckable(False) self.savePushButton.setObjectName("savePushButton") self.horizontalLayout_8.addWidget(self.savePushButton) self.saveStatusLabel = QtWidgets.QLabel(self.widget_6) self.saveStatusLabel.setObjectName("saveStatusLabel") self.horizontalLayout_8.addWidget(self.saveStatusLabel, 0, QtCore.Qt.AlignLeft) self.verticalLayout_5.addWidget(self.widget_6) self.horizontalLayout.addWidget(self.saveGroupBox) self.verticalLayout.addWidget(self.topFrame) self.selectionTableFrame = QtWidgets.QFrame(WaveformDialog) self.selectionTableFrame.setObjectName("selectionTableFrame") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.selectionTableFrame) self.verticalLayout_2.setContentsMargins(2, 2, 2, 2) self.verticalLayout_2.setSpacing(2) self.verticalLayout_2.setObjectName("verticalLayout_2") self.filterGroupBox = QtWidgets.QGroupBox(self.selectionTableFrame) self.filterGroupBox.setEnabled(True) self.filterGroupBox.setObjectName("filterGroupBox") self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.filterGroupBox) self.horizontalLayout_2.setContentsMargins(2, 2, 2, 2) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.hideNoDataCheckBox = QtWidgets.QCheckBox(self.filterGroupBox) self.hideNoDataCheckBox.setObjectName("hideNoDataCheckBox") self.horizontalLayout_2.addWidget(self.hideNoDataCheckBox) spacerItem3 = QtWidgets.QSpacerItem(20, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem3) self.eventComboBox = QtWidgets.QComboBox(self.filterGroupBox) self.eventComboBox.setObjectName("eventComboBox") self.horizontalLayout_2.addWidget(self.eventComboBox) self.networkComboBox = QtWidgets.QComboBox(self.filterGroupBox) self.networkComboBox.setObjectName("networkComboBox") self.horizontalLayout_2.addWidget(self.networkComboBox) self.stationComboBox = QtWidgets.QComboBox(self.filterGroupBox) self.stationComboBox.setObjectName("stationComboBox") self.horizontalLayout_2.addWidget(self.stationComboBox) self.horizontalLayout_2.setStretch(2, 3) self.horizontalLayout_2.setStretch(3, 1) self.horizontalLayout_2.setStretch(4, 1) self.verticalLayout_2.addWidget(self.filterGroupBox) self.selectionTable = QtWidgets.QTableWidget(self.selectionTableFrame) self.selectionTable.setMinimumSize(QtCore.QSize(500, 100)) self.selectionTable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) self.selectionTable.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection) self.selectionTable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.selectionTable.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.selectionTable.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.selectionTable.setShowGrid(False) self.selectionTable.setObjectName("selectionTable") self.selectionTable.setColumnCount(0) self.selectionTable.setRowCount(0) self.selectionTable.horizontalHeader().setStretchLastSection(False) self.selectionTable.verticalHeader().setVisible(True) self.verticalLayout_2.addWidget(self.selectionTable) self.verticalLayout.addWidget(self.selectionTableFrame) self.verticalLayout.setStretch(1, 1) self.retranslateUi(WaveformDialog) QtCore.QMetaObject.connectSlotsByName(WaveformDialog) def retranslateUi(self, WaveformDialog): _translate = QtCore.QCoreApplication.translate WaveformDialog.setWindowTitle(_translate("WaveformDialog", "Dialog")) self.downloadGroupBox.setTitle(_translate("WaveformDialog", "Download / Preview Waveforms")) self.secondsBeforeLabel.setText(_translate("WaveformDialog", "Start:")) self.label.setText(_translate("WaveformDialog", "secs before")) self.label_2.setText(_translate("WaveformDialog", "secs after")) self.secondsAfterLabel.setText(_translate("WaveformDialog", "End:")) self.downloadPushButton.setText(_translate("WaveformDialog", "Download")) self.downloadStatusLabel.setText(_translate("WaveformDialog", "Download status")) self.saveGroupBox.setTitle(_translate("WaveformDialog", "Save Waveforms")) self.sacUseEventTimeCheckBox.setToolTip(_translate("WaveformDialog", "For SAC output, use the event time as the origin (iztype=\"io\")")) self.sacUseEventTimeCheckBox.setText(_translate("WaveformDialog", "Use event time")) self.saveDirectoryLabel.setText(_translate("WaveformDialog", "To:")) self.saveFormatLabel.setText(_translate("WaveformDialog", "As:")) self.saveDirectoryPushButton.setText(_translate("WaveformDialog", "Directory")) self.saveDirectoryBrowseToolButton.setText(_translate("WaveformDialog", "Open")) self.savePushButton.setText(_translate("WaveformDialog", "Save")) self.saveStatusLabel.setText(_translate("WaveformDialog", "Save status")) self.filterGroupBox.setTitle(_translate("WaveformDialog", "Table Filters")) self.hideNoDataCheckBox.setToolTip(_translate("WaveformDialog", "Hide rows when no data is found")) self.hideNoDataCheckBox.setText(_translate("WaveformDialog", "Hide no data")) self.selectionTable.setSortingEnabled(True)
lgpl-3.0
edwinspire/VSharp
class/System.Web.Mvc2/System.Web.Mvc/AreaRegistrationContext.cs
4748
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. All rights reserved. * * This software is subject to the Microsoft Public License (Ms-PL). * A copy of the license can be found in the license.htm file included * in this distribution. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ namespace System.Web.Mvc { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Web.Routing; public class AreaRegistrationContext { private readonly HashSet<string> _namespaces = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public AreaRegistrationContext(string areaName, RouteCollection routes) : this(areaName, routes, null) { } public AreaRegistrationContext(string areaName, RouteCollection routes, object state) { if (String.IsNullOrEmpty(areaName)) { throw Error.ParameterCannotBeNullOrEmpty("areaName"); } if (routes == null) { throw new ArgumentNullException("routes"); } AreaName = areaName; Routes = routes; State = state; } public string AreaName { get; private set; } public ICollection<string> Namespaces { get { return _namespaces; } } public RouteCollection Routes { get; private set; } public object State { get; private set; } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "This is not a regular URL as it may contain special routing characters.")] public Route MapRoute(string name, string url) { return MapRoute(name, url, (object)null /* defaults */); } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "This is not a regular URL as it may contain special routing characters.")] public Route MapRoute(string name, string url, object defaults) { return MapRoute(name, url, defaults, (object)null /* constraints */); } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "This is not a regular URL as it may contain special routing characters.")] public Route MapRoute(string name, string url, object defaults, object constraints) { return MapRoute(name, url, defaults, constraints, null /* namespaces */); } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "This is not a regular URL as it may contain special routing characters.")] public Route MapRoute(string name, string url, string[] namespaces) { return MapRoute(name, url, (object)null /* defaults */, namespaces); } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "This is not a regular URL as it may contain special routing characters.")] public Route MapRoute(string name, string url, object defaults, string[] namespaces) { return MapRoute(name, url, defaults, null /* constraints */, namespaces); } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "This is not a regular URL as it may contain special routing characters.")] public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces) { if (namespaces == null && Namespaces != null) { namespaces = Namespaces.ToArray(); } Route route = Routes.MapRoute(name, url, defaults, constraints, namespaces); route.DataTokens["area"] = AreaName; // disabling the namespace lookup fallback mechanism keeps this areas from accidentally picking up // controllers belonging to other areas bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0); route.DataTokens["UseNamespaceFallback"] = useNamespaceFallback; return route; } } }
lgpl-3.0
jlauinger/StartSSL_API
config.py
141
CERTFILE = "client_key.p12:geheim" # ------- STARTSSL_BASEURI = "https://www.startssl.com" STARTSSL_AUTHURI = "https://auth.startssl.com"
lgpl-3.0
respinar/staff
src/library/Frontend/Module/ModuleStaff.php
6506
<?php /** * Contao Open Source CMS * * Copyright (c) 2005-2015 Leo Feyer * * @package Staff * @author Hamid Abbaszadeh * @license GNU/LGPL3 * @copyright 2014-2015 */ /** * Namespace */ namespace Respinar\Staff\Frontend\Module; use Respinar\Staff\Model\StaffCategoryModel; /** * Class ModuleStaff */ abstract class ModuleStaff extends \Module { /** * URL cache array * @var array */ private static $arrUrlCache = array(); /** * Sort out protected categories * * @param array $arrCategories * * @return array */ protected function sortOutProtected($arrCategories) { if (BE_USER_LOGGED_IN || !is_array($arrCategories) || empty($arrCategories)) { return $arrCategories; } $this->import('FrontendUser', 'User'); $objCategory = StaffCategoryModel::findMultipleByIds($arrCategories); $arrCategories = array(); if ($objCategory !== null) { while ($objCategory->next()) { if ($objCategory->protected) { if (!FE_USER_LOGGED_IN) { continue; } $groups = deserialize($objCategory->groups); if (!is_array($groups) || empty($groups) || !count(array_intersect($groups, $this->User->groups))) { continue; } } $arrCategories[] = $objCategory->id; } } return $arrCategories; } /** * Parse an item and return it as string * @param object * @param boolean * @param string * @param integer * @return string */ protected function parseMember($objMember, $blnAddStaff=false, $strClass='', $intCount=0) { global $objPage; $objTemplate = new \FrontendTemplate($this->staff_member_template); $objTemplate->setData($objMember->row()); $objTemplate->class = (($this->staff_member_class != '') ? ' ' . $this->staff_member_class : '') . $strClass; if (!empty($objMember->education)) { $objTemplate->education = deserialize($objMember->education); } $objTemplate->link = $this->generateMemberUrl($objMember, $blnAddStaff); $objTemplate->staff = $objMember->getRelated('pid'); $objTemplate->txt_educations = $GLOBALS['TL_LANG']['MSC']['educations']; $objTemplate->txt_contact = $GLOBALS['TL_LANG']['MSC']['contact']; $objTemplate->txt_room = $GLOBALS['TL_LANG']['MSC']['room']; $objTemplate->txt_phone = $GLOBALS['TL_LANG']['MSC']['phone']; $objTemplate->txt_mobile = $GLOBALS['TL_LANG']['MSC']['mobile']; $objTemplate->txt_fax = $GLOBALS['TL_LANG']['MSC']['fax']; $objTemplate->txt_email = $GLOBALS['TL_LANG']['MSC']['email']; $objTemplate->txt_website = $GLOBALS['TL_LANG']['MSC']['website']; $objTemplate->txt_facebook = $GLOBALS['TL_LANG']['MSC']['facebook']; $objTemplate->txt_googleplus = $GLOBALS['TL_LANG']['MSC']['googleplus']; $objTemplate->txt_twitter = $GLOBALS['TL_LANG']['MSC']['twitter']; $objTemplate->txt_linkedin = $GLOBALS['TL_LANG']['MSC']['linkedin']; $objTemplate->count = $intCount; // see #5708 $objTemplate->addImage = false; // Add an image if ($objMember->singleSRC != '') { $objModel = \FilesModel::findByUuid($objMember->singleSRC); if ($objModel === null) { if (!\Validator::isUuid($objMember->singleSRC)) { $objTemplate->text = '<p class="error">'.$GLOBALS['TL_LANG']['ERR']['version2format'].'</p>'; } } elseif (is_file(TL_ROOT . '/' . $objModel->path)) { // Do not override the field now that we have a model registry (see #6303) $arrMember = $objMember->row(); // Override the default image size if ($this->imgSize != '') { $size = deserialize($this->imgSize); if ($size[0] > 0 || $size[1] > 0 || is_numeric($size[2])) { $arrMember['size'] = $this->imgSize; } } $arrMember['singleSRC'] = $objModel->path; $strLightboxId = 'lightbox[lb' . $this->id . ']'; $arrMember['fullsize'] = $this->fullsize; $this->addImageToTemplate($objTemplate, $arrMember,null, $strLightboxId); } } $objTemplate->enclosure = array(); // Add enclosures if ($objMember->addEnclosure) { $this->addEnclosuresToTemplate($objTemplate, $objMember->row()); } return $objTemplate->parse(); } /** * Parse one or more items and return them as array * @param object * @param boolean * @return array */ protected function parseMembers($objMembers, $blnAddStaff=false) { $limit = $objMembers->count(); if ($limit < 1) { return array(); } $count = 0; $arrMembers = array(); while ($objMembers->next()) { $arrMembers[] = $this->parseMember($objMembers, $blnAddStaff, ((++$count == 1) ? ' first' : '') . (($count == $limit) ? ' last' : '') . ((($count % $this->staff_member_perRow) == 0) ? ' last_col' : '') . ((($count % $this->staff_member_perRow) == 1) ? ' first_col' : ''), $count); } return $arrMembers; } /** * Generate a URL and return it as string * @param object * @param boolean * @return string */ protected function generateMemberUrl($objItem, $blnAddStaff=false) { $strCacheKey = 'id_' . $objItem->id; // Load the URL from cache if (isset(self::$arrUrlCache[$strCacheKey])) { return self::$arrUrlCache[$strCacheKey]; } // Initialize the cache self::$arrUrlCache[$strCacheKey] = null; // Link to the default page if (self::$arrUrlCache[$strCacheKey] === null) { $objPage = \PageModel::findByPk($objItem->getRelated('pid')->jumpTo); if ($objPage === null) { self::$arrUrlCache[$strCacheKey] = ampersand(\Environment::get('request'), true); } else { self::$arrUrlCache[$strCacheKey] = ampersand($this->generateFrontendUrl($objPage->row(), ((\Config::get('useAutoItem') && !\Config::get('disableAlias')) ? '/' : '/items/') . ((!\Config::get('disableAlias') && $objItem->alias != '') ? $objItem->alias : $objItem->id))); } } return self::$arrUrlCache[$strCacheKey]; } /** * Generate a link and return it as string * @param string * @param object * @param boolean * @param boolean * @return string */ protected function generateLink($strLink, $objMember, $blnAddStaff=false, $blnIsReadMore=false) { return sprintf('<a href="%s" title="%s">%s%s</a>', $this->generateMemberUrl($objMember, $blnAddStaff), specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['readMore'], $objMember->firstname . ' ' . $objMember->lastname), true), $strLink, ($blnIsReadMore ? ' <span class="invisible">'.$objMember->firstname . ' ' . $objMember->lastname.'</span>' : '')); } }
lgpl-3.0
hsnks100/LakingServer
LKCamelot/script/item/weapons/spear/ForkedSpear.cs
1327
using LKCamelot.library; using LKCamelot.model; namespace LKCamelot.script.item { public class ForkedSpear : BaseWeapon { public override string Name { get { return "Forked Spear"; } } public override int DamBase { get { return 106; } } public override int ACBase { get { return 99; } } public override int HitBonus { get { return 0; } } public override int MPBonus { get { return 102; } } public override int StrReq { get { return 169; } } public override int MenReq { get { return 381; } } public override int DexReq { get { return 243; } } public override int ReduceCast { get { return 1100; } } public override int InitMinHits { get { return 80; } } public override int InitMaxHits { get { return 80; } } public override ulong BuyPrice { get { return 5000; } } public override int LevelReq { get { return 74; } } public override int SellPrice { get { return 150000; } } public override Class ClassReq { get { return Class.Shaman; } } public override WeaponType WeaponType { get { return WeaponType.Spear; } } public ForkedSpear() : base(35) { } public ForkedSpear(Serial serial) : base(serial) { } } }
lgpl-3.0
Orav/kbengine
kbe/src/lib/python/Lib/idlelib/rpc.py
21557
"""RPC Implemention, originally written for the Python Idle IDE For security reasons, GvR requested that Idle's Python execution server process connect to the Idle process, which listens for the connection. Since Idle has only one client per server, this was not a limitation. +---------------------------------+ +-------------+ | socketserver.BaseRequestHandler | | SocketIO | +---------------------------------+ +-------------+ ^ | register() | | | unregister()| | +-------------+ | ^ ^ | | | | + -------------------+ | | | | +-------------------------+ +-----------------+ | RPCHandler | | RPCClient | | [attribute of RPCServer]| | | +-------------------------+ +-----------------+ The RPCServer handler class is expected to provide register/unregister methods. RPCHandler inherits the mix-in class SocketIO, which provides these methods. See the Idle run.main() docstring for further information on how this was accomplished in Idle. """ import sys import os import socket import select import socketserver import struct import pickle import threading import queue import traceback import copyreg import types import marshal import builtins def unpickle_code(ms): co = marshal.loads(ms) assert isinstance(co, types.CodeType) return co def pickle_code(co): assert isinstance(co, types.CodeType) ms = marshal.dumps(co) return unpickle_code, (ms,) # XXX KBK 24Aug02 function pickling capability not used in Idle # def unpickle_function(ms): # return ms # def pickle_function(fn): # assert isinstance(fn, type.FunctionType) # return repr(fn) copyreg.pickle(types.CodeType, pickle_code, unpickle_code) # copyreg.pickle(types.FunctionType, pickle_function, unpickle_function) BUFSIZE = 8*1024 LOCALHOST = '127.0.0.1' class RPCServer(socketserver.TCPServer): def __init__(self, addr, handlerclass=None): if handlerclass is None: handlerclass = RPCHandler socketserver.TCPServer.__init__(self, addr, handlerclass) def server_bind(self): "Override TCPServer method, no bind() phase for connecting entity" pass def server_activate(self): """Override TCPServer method, connect() instead of listen() Due to the reversed connection, self.server_address is actually the address of the Idle Client to which we are connecting. """ self.socket.connect(self.server_address) def get_request(self): "Override TCPServer method, return already connected socket" return self.socket, self.server_address def handle_error(self, request, client_address): """Override TCPServer method Error message goes to __stderr__. No error message if exiting normally or socket raised EOF. Other exceptions not handled in server code will cause os._exit. """ try: raise except SystemExit: raise except: erf = sys.__stderr__ print('\n' + '-'*40, file=erf) print('Unhandled server exception!', file=erf) print('Thread: %s' % threading.current_thread().name, file=erf) print('Client Address: ', client_address, file=erf) print('Request: ', repr(request), file=erf) traceback.print_exc(file=erf) print('\n*** Unrecoverable, server exiting!', file=erf) print('-'*40, file=erf) os._exit(0) #----------------- end class RPCServer -------------------- objecttable = {} request_queue = queue.Queue(0) response_queue = queue.Queue(0) class SocketIO(object): nextseq = 0 def __init__(self, sock, objtable=None, debugging=None): self.sockthread = threading.current_thread() if debugging is not None: self.debugging = debugging self.sock = sock if objtable is None: objtable = objecttable self.objtable = objtable self.responses = {} self.cvars = {} def close(self): sock = self.sock self.sock = None if sock is not None: sock.close() def exithook(self): "override for specific exit action" os._exit(0) def debug(self, *args): if not self.debugging: return s = self.location + " " + str(threading.current_thread().name) for a in args: s = s + " " + str(a) print(s, file=sys.__stderr__) def register(self, oid, object): self.objtable[oid] = object def unregister(self, oid): try: del self.objtable[oid] except KeyError: pass def localcall(self, seq, request): self.debug("localcall:", request) try: how, (oid, methodname, args, kwargs) = request except TypeError: return ("ERROR", "Bad request format") if oid not in self.objtable: return ("ERROR", "Unknown object id: %r" % (oid,)) obj = self.objtable[oid] if methodname == "__methods__": methods = {} _getmethods(obj, methods) return ("OK", methods) if methodname == "__attributes__": attributes = {} _getattributes(obj, attributes) return ("OK", attributes) if not hasattr(obj, methodname): return ("ERROR", "Unsupported method name: %r" % (methodname,)) method = getattr(obj, methodname) try: if how == 'CALL': ret = method(*args, **kwargs) if isinstance(ret, RemoteObject): ret = remoteref(ret) return ("OK", ret) elif how == 'QUEUE': request_queue.put((seq, (method, args, kwargs))) return("QUEUED", None) else: return ("ERROR", "Unsupported message type: %s" % how) except SystemExit: raise except KeyboardInterrupt: raise except OSError: raise except Exception as ex: return ("CALLEXC", ex) except: msg = "*** Internal Error: rpc.py:SocketIO.localcall()\n\n"\ " Object: %s \n Method: %s \n Args: %s\n" print(msg % (oid, method, args), file=sys.__stderr__) traceback.print_exc(file=sys.__stderr__) return ("EXCEPTION", None) def remotecall(self, oid, methodname, args, kwargs): self.debug("remotecall:asynccall: ", oid, methodname) seq = self.asynccall(oid, methodname, args, kwargs) return self.asyncreturn(seq) def remotequeue(self, oid, methodname, args, kwargs): self.debug("remotequeue:asyncqueue: ", oid, methodname) seq = self.asyncqueue(oid, methodname, args, kwargs) return self.asyncreturn(seq) def asynccall(self, oid, methodname, args, kwargs): request = ("CALL", (oid, methodname, args, kwargs)) seq = self.newseq() if threading.current_thread() != self.sockthread: cvar = threading.Condition() self.cvars[seq] = cvar self.debug(("asynccall:%d:" % seq), oid, methodname, args, kwargs) self.putmessage((seq, request)) return seq def asyncqueue(self, oid, methodname, args, kwargs): request = ("QUEUE", (oid, methodname, args, kwargs)) seq = self.newseq() if threading.current_thread() != self.sockthread: cvar = threading.Condition() self.cvars[seq] = cvar self.debug(("asyncqueue:%d:" % seq), oid, methodname, args, kwargs) self.putmessage((seq, request)) return seq def asyncreturn(self, seq): self.debug("asyncreturn:%d:call getresponse(): " % seq) response = self.getresponse(seq, wait=0.05) self.debug(("asyncreturn:%d:response: " % seq), response) return self.decoderesponse(response) def decoderesponse(self, response): how, what = response if how == "OK": return what if how == "QUEUED": return None if how == "EXCEPTION": self.debug("decoderesponse: EXCEPTION") return None if how == "EOF": self.debug("decoderesponse: EOF") self.decode_interrupthook() return None if how == "ERROR": self.debug("decoderesponse: Internal ERROR:", what) raise RuntimeError(what) if how == "CALLEXC": self.debug("decoderesponse: Call Exception:", what) raise what raise SystemError(how, what) def decode_interrupthook(self): "" raise EOFError def mainloop(self): """Listen on socket until I/O not ready or EOF pollresponse() will loop looking for seq number None, which never comes, and exit on EOFError. """ try: self.getresponse(myseq=None, wait=0.05) except EOFError: self.debug("mainloop:return") return def getresponse(self, myseq, wait): response = self._getresponse(myseq, wait) if response is not None: how, what = response if how == "OK": response = how, self._proxify(what) return response def _proxify(self, obj): if isinstance(obj, RemoteProxy): return RPCProxy(self, obj.oid) if isinstance(obj, list): return list(map(self._proxify, obj)) # XXX Check for other types -- not currently needed return obj def _getresponse(self, myseq, wait): self.debug("_getresponse:myseq:", myseq) if threading.current_thread() is self.sockthread: # this thread does all reading of requests or responses while 1: response = self.pollresponse(myseq, wait) if response is not None: return response else: # wait for notification from socket handling thread cvar = self.cvars[myseq] cvar.acquire() while myseq not in self.responses: cvar.wait() response = self.responses[myseq] self.debug("_getresponse:%s: thread woke up: response: %s" % (myseq, response)) del self.responses[myseq] del self.cvars[myseq] cvar.release() return response def newseq(self): self.nextseq = seq = self.nextseq + 2 return seq def putmessage(self, message): self.debug("putmessage:%d:" % message[0]) try: s = pickle.dumps(message) except pickle.PicklingError: print("Cannot pickle:", repr(message), file=sys.__stderr__) raise s = struct.pack("<i", len(s)) + s while len(s) > 0: try: r, w, x = select.select([], [self.sock], []) n = self.sock.send(s[:BUFSIZE]) except (AttributeError, TypeError): raise OSError("socket no longer exists") except OSError: raise else: s = s[n:] buff = b'' bufneed = 4 bufstate = 0 # meaning: 0 => reading count; 1 => reading data def pollpacket(self, wait): self._stage0() if len(self.buff) < self.bufneed: r, w, x = select.select([self.sock.fileno()], [], [], wait) if len(r) == 0: return None try: s = self.sock.recv(BUFSIZE) except OSError: raise EOFError if len(s) == 0: raise EOFError self.buff += s self._stage0() return self._stage1() def _stage0(self): if self.bufstate == 0 and len(self.buff) >= 4: s = self.buff[:4] self.buff = self.buff[4:] self.bufneed = struct.unpack("<i", s)[0] self.bufstate = 1 def _stage1(self): if self.bufstate == 1 and len(self.buff) >= self.bufneed: packet = self.buff[:self.bufneed] self.buff = self.buff[self.bufneed:] self.bufneed = 4 self.bufstate = 0 return packet def pollmessage(self, wait): packet = self.pollpacket(wait) if packet is None: return None try: message = pickle.loads(packet) except pickle.UnpicklingError: print("-----------------------", file=sys.__stderr__) print("cannot unpickle packet:", repr(packet), file=sys.__stderr__) traceback.print_stack(file=sys.__stderr__) print("-----------------------", file=sys.__stderr__) raise return message def pollresponse(self, myseq, wait): """Handle messages received on the socket. Some messages received may be asynchronous 'call' or 'queue' requests, and some may be responses for other threads. 'call' requests are passed to self.localcall() with the expectation of immediate execution, during which time the socket is not serviced. 'queue' requests are used for tasks (which may block or hang) to be processed in a different thread. These requests are fed into request_queue by self.localcall(). Responses to queued requests are taken from response_queue and sent across the link with the associated sequence numbers. Messages in the queues are (sequence_number, request/response) tuples and code using this module removing messages from the request_queue is responsible for returning the correct sequence number in the response_queue. pollresponse() will loop until a response message with the myseq sequence number is received, and will save other responses in self.responses and notify the owning thread. """ while 1: # send queued response if there is one available try: qmsg = response_queue.get(0) except queue.Empty: pass else: seq, response = qmsg message = (seq, ('OK', response)) self.putmessage(message) # poll for message on link try: message = self.pollmessage(wait) if message is None: # socket not ready return None except EOFError: self.handle_EOF() return None except AttributeError: return None seq, resq = message how = resq[0] self.debug("pollresponse:%d:myseq:%s" % (seq, myseq)) # process or queue a request if how in ("CALL", "QUEUE"): self.debug("pollresponse:%d:localcall:call:" % seq) response = self.localcall(seq, resq) self.debug("pollresponse:%d:localcall:response:%s" % (seq, response)) if how == "CALL": self.putmessage((seq, response)) elif how == "QUEUE": # don't acknowledge the 'queue' request! pass continue # return if completed message transaction elif seq == myseq: return resq # must be a response for a different thread: else: cv = self.cvars.get(seq, None) # response involving unknown sequence number is discarded, # probably intended for prior incarnation of server if cv is not None: cv.acquire() self.responses[seq] = resq cv.notify() cv.release() continue def handle_EOF(self): "action taken upon link being closed by peer" self.EOFhook() self.debug("handle_EOF") for key in self.cvars: cv = self.cvars[key] cv.acquire() self.responses[key] = ('EOF', None) cv.notify() cv.release() # call our (possibly overridden) exit function self.exithook() def EOFhook(self): "Classes using rpc client/server can override to augment EOF action" pass #----------------- end class SocketIO -------------------- class RemoteObject(object): # Token mix-in class pass def remoteref(obj): oid = id(obj) objecttable[oid] = obj return RemoteProxy(oid) class RemoteProxy(object): def __init__(self, oid): self.oid = oid class RPCHandler(socketserver.BaseRequestHandler, SocketIO): debugging = False location = "#S" # Server def __init__(self, sock, addr, svr): svr.current_handler = self ## cgt xxx SocketIO.__init__(self, sock) socketserver.BaseRequestHandler.__init__(self, sock, addr, svr) def handle(self): "handle() method required by socketserver" self.mainloop() def get_remote_proxy(self, oid): return RPCProxy(self, oid) class RPCClient(SocketIO): debugging = False location = "#C" # Client nextseq = 1 # Requests coming from the client are odd numbered def __init__(self, address, family=socket.AF_INET, type=socket.SOCK_STREAM): self.listening_sock = socket.socket(family, type) self.listening_sock.bind(address) self.listening_sock.listen(1) def accept(self): working_sock, address = self.listening_sock.accept() if self.debugging: print("****** Connection request from ", address, file=sys.__stderr__) if address[0] == LOCALHOST: SocketIO.__init__(self, working_sock) else: print("** Invalid host: ", address, file=sys.__stderr__) raise OSError def get_remote_proxy(self, oid): return RPCProxy(self, oid) class RPCProxy(object): __methods = None __attributes = None def __init__(self, sockio, oid): self.sockio = sockio self.oid = oid def __getattr__(self, name): if self.__methods is None: self.__getmethods() if self.__methods.get(name): return MethodProxy(self.sockio, self.oid, name) if self.__attributes is None: self.__getattributes() if name in self.__attributes: value = self.sockio.remotecall(self.oid, '__getattribute__', (name,), {}) return value else: raise AttributeError(name) def __getattributes(self): self.__attributes = self.sockio.remotecall(self.oid, "__attributes__", (), {}) def __getmethods(self): self.__methods = self.sockio.remotecall(self.oid, "__methods__", (), {}) def _getmethods(obj, methods): # Helper to get a list of methods from an object # Adds names to dictionary argument 'methods' for name in dir(obj): attr = getattr(obj, name) if callable(attr): methods[name] = 1 if isinstance(obj, type): for super in obj.__bases__: _getmethods(super, methods) def _getattributes(obj, attributes): for name in dir(obj): attr = getattr(obj, name) if not callable(attr): attributes[name] = 1 class MethodProxy(object): def __init__(self, sockio, oid, name): self.sockio = sockio self.oid = oid self.name = name def __call__(self, *args, **kwargs): value = self.sockio.remotecall(self.oid, self.name, args, kwargs) return value # XXX KBK 09Sep03 We need a proper unit test for this module. Previously # existing test code was removed at Rev 1.27 (r34098). def displayhook(value): """Override standard display hook to use non-locale encoding""" if value is None: return # Set '_' to None to avoid recursion builtins._ = None text = repr(value) try: sys.stdout.write(text) except UnicodeEncodeError: # let's use ascii while utf8-bmp codec doesn't present encoding = 'ascii' bytes = text.encode(encoding, 'backslashreplace') text = bytes.decode(encoding, 'strict') sys.stdout.write(text) sys.stdout.write("\n") builtins._ = value
lgpl-3.0
marissaDubbelaar/GOAD3.1.1
molgenis-data-mapper/src/main/java/org/molgenis/data/mapper/meta/MappingTargetMetaData.java
1580
package org.molgenis.data.mapper.meta; import org.molgenis.data.meta.SystemEntityType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import static java.util.Objects.requireNonNull; import static org.molgenis.data.mapper.meta.MapperPackage.PACKAGE_MAPPER; import static org.molgenis.data.meta.AttributeType.MREF; import static org.molgenis.data.meta.model.EntityType.AttributeRole.ROLE_ID; import static org.molgenis.data.meta.model.Package.PACKAGE_SEPARATOR; @Component public class MappingTargetMetaData extends SystemEntityType { private static final String SIMPLE_NAME = "MappingTarget"; public static final String MAPPING_TARGET = PACKAGE_MAPPER + PACKAGE_SEPARATOR + SIMPLE_NAME; public static final String IDENTIFIER = "identifier"; public static final String ENTITY_MAPPINGS = "entityMappings"; public static final String TARGET = "target"; private final MapperPackage mapperPackage; private final EntityMappingMetaData entityMappingMetaData; @Autowired public MappingTargetMetaData(MapperPackage mapperPackage, EntityMappingMetaData entityMappingMetaData) { super(SIMPLE_NAME, PACKAGE_MAPPER); this.mapperPackage = requireNonNull(mapperPackage); this.entityMappingMetaData = requireNonNull(entityMappingMetaData); } @Override public void init() { setLabel("Mapping target"); setPackage(mapperPackage); addAttribute(IDENTIFIER, ROLE_ID); addAttribute(ENTITY_MAPPINGS).setDataType(MREF).setRefEntity(entityMappingMetaData); addAttribute(TARGET).setNillable(false); } }
lgpl-3.0
igorshubovych/cloudmade-ruby-client
lib/client.rb
2265
# # Copyright 2009 CloudMade. # # Licensed under the GNU Lesser General Public License, Version 3.0; # You may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.gnu.org/licenses/lgpl-3.0.txt # # 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. # module CloudMade class Client attr_accessor :connection attr_accessor :base_url attr_writer :port attr_accessor :api_key #attr_reader :token #:nodoc: def url return "#{base_url}#{@port != nil ? ':' + port.to_s : ''}" end #:nodoc: def port return 80 if @port == nil @port end # Tiles service def tiles @tiles = TilesService.new(self.connection, 'tile') if @tiles == nil return @tiles end # Geocoding service def geocoding @geocoding = GeocodingService.new(self.connection, 'geocoding') if @geocoding == nil return @geocoding end # Routing service def routing @routing = RoutingService.new(self.connection, 'routes') if @routing == nil return @routing end # Locations service def locations @locations = LocationsService.new(self.connection, '') if @locations == nil return @locations end class << self def from_connection(connection) client = Client.new client.connection = connection return client end def from_parameters(api_key, base_url = nil, port = nil) client = Client.new client.connection = Connection.new(api_key, base_url, port) return client end # TODO: Create here methods to connect from XML and YAML configuration file end protected def initialize() end ### 2. Allow loads configuration from XML, YAML files #def initialize(api_key, base_url = 'cloudmade.com', port = nil) # @base_url = base_url # @port = port # @api_key = api_key # #@token = token #end end end
lgpl-3.0
chimpinano/MVVM-for-awesomium
MVVM.Awesomium/Binding/AwesomiumBinding/Mapping/JavascriptToCSharpMapper.cs
2108
using Awesomium.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MVVMAwesomium.AwesomiumBinding { public class JavascriptToCSharpMapper { private IWebView _IWebView; public JavascriptToCSharpMapper(IWebView iIWebView) { _IWebView = iIWebView; } public object GetSimpleValue(JSValue ijsvalue, Type iTargetType=null) { if (ijsvalue.IsString) return (string)ijsvalue; if (ijsvalue.IsBoolean) return (bool)ijsvalue; object res =null; if (ijsvalue.IsNumber) { if (ijsvalue.IsInteger) res = (int)ijsvalue; else if (ijsvalue.IsDouble) res = (double)ijsvalue; if (iTargetType == null) return res; else return Convert.ChangeType(res, iTargetType); } var resdate = GetDate(ijsvalue); if (resdate.HasValue) return resdate.Value; return null; } private DateTime? GetDate(JSValue iJSValue) { if (!iJSValue.IsObject) return null; JSObject ob = iJSValue; if (ob == null) return null; JSObject ko = _IWebView.ExecuteJavascriptWithResult("ko"); if ((bool)ko.Invoke("isDate", iJSValue) == false) return null; int year = (int)ob.Invoke("getFullYear", null); int month = (int)ob.Invoke("getMonth", null) + 1; int day = (int)ob.Invoke("getDate", null); int hour = (int)ob.Invoke("getHours",null); int minute = (int)ob.Invoke("getMinutes",null); int second = (int)ob.Invoke("getSeconds",null); int millisecond = (int)ob.Invoke("getMilliseconds",null); return new DateTime(year, month, day, hour, minute, second, millisecond); } } }
lgpl-3.0
websphere/jboss-el-impl
test/org/jboss/el/TestParsing.java
1519
package org.jboss.el; import junit.framework.TestCase; import org.jboss.el.parser.ELParser; import org.jboss.el.parser.SimpleNode; public class TestParsing extends TestCase { public void testParsing() throws Exception { parse("#{foo.a.b}"); parse("#{foo.a['b']}"); parse("#{3 * foo.a.b(e,c,d)}"); parse("#{'foo'.length().food}"); parse("#{foo}"); // parse("#{company.employees@name}"); // parse("#{company.employees@getName()}"); // parse("#{company.employees@each{x|x.salary}.salary}"); // parse("#{company.employees@each{x|x.hashCode()}}"); // parse("#{company.employees@each{x|x@max{y|y.salary}}} is complex"); parse("#{company.get(foo)}"); parse("#{company.employees.{x|x.name}}"); parse("#{company.employees.{x|x.getName()}}"); parse("#{company.employees.{x|x.salary}.salary}"); parse("#{company.employees.{x|x.hashCode()}}"); parse("#{company.employees.{x|x.{y|y.salary}}} is complex"); System.out.println("\n=============================\n"); parse("#{company.departments.{x|x.employees}.{x|x.lastName}}"); parse("#{company.departments.{x|x.employees.{x|x.lastName}}}"); parse("#{user.matchRole(1)}"); parse("#{user.matchRole(1,4,3)}"); } public static SimpleNode parse(String in) { System.out.println(in); SimpleNode node = (SimpleNode) ELParser.parse(in); node.dump(""); System.out.println(); return node; } }
lgpl-3.0
SoftwareEngineeringToolDemos/FSE-2011-EvoSuite
master/src/test/java/com/examples/with/different/packagename/DeleteFileProcess.java
1375
/** * Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser Public License as published by the * Free Software Foundation, either version 3.0 of the License, or (at your * option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License along * with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ /** * */ package com.examples.with.different.packagename; import java.io.File; import java.io.IOException; /** * @author Gordon Fraser * */ public class DeleteFileProcess { public void testMe() throws IOException { String tmpdir = System.getProperty("java.io.tmpdir"); String fileName = tmpdir + File.separator + "this_file_should_not_be_deleted_by_evosuite"; String[] cmdAttribs = new String[] { "/bin/rm", fileName }; Process proc = Runtime.getRuntime().exec(cmdAttribs); try { proc.waitFor(); } catch (InterruptedException e) { } finally { proc.destroy(); } } }
lgpl-3.0
Facsimile/facsimile
core/src/main/scala/org/facsim/anim/cell/CellColor.scala
6358
/* Facsimile: A Discrete-Event Simulation Library Copyright © 2004-2020, Michael J Allen. This file is part of Facsimile. Facsimile is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Facsimile 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 Facsimile. If not, see http://www.gnu.org/licenses/lgpl. The developers welcome all comments, suggestions and offers of assistance. For further information, please visit the project home page at: http://facsim.org/ Thank you for your interest in the Facsimile project! IMPORTANT NOTE: All patches (modifications to existing files and/or the addition of new files) submitted for inclusion as part of the official Facsimile code base, must comply with the published Facsimile Coding Standards. If your code fails to comply with the standard, then your patches will be rejected. For further information, please visit the coding standards at: http://facsim.org/Documentation/CodingStandards/ ======================================================================================================================== Scala source file from the org.facsim.anim.cell package. */ package org.facsim.anim.cell import org.facsim.{assertNonNull, LibResource} import scalafx.scene.paint.Color import scalafx.scene.paint.PhongMaterial /** Cell color name enumeration. Encodes ''[[http://www.automod.com/ AutoMod®]]'' color codes and maps them to the corresponding ''ScalaFX'' colors and materials. @see [[http://facsim.org/Documentation/Resources/AutoModCellFile/Colors.html Face & Edge Colors]] */ private[cell] object CellColor extends Enumeration { /** Vector associating each ''cell'' color with the corresponding ''ScalaFX'' color. */ private val cellToColor = Vector( Color.Black, Color.Red, Color.Green, Color.Yellow, Color.Blue, Color.Magenta, Color.Cyan, Color.White, Color.LightGray, Color.DarkGray, Color.Brown, Color.LightBlue, Color.Purple, Color.Orange, Color.LightGreen, Color.LightYellow ) /** Vector of materials that employ cell colors as ''diffuse'' colors. In each case the ''specular'' color is set to white. @note Use of this vector allows us to keep the number of materials used within cell files small. */ private val cellToMaterial: Vector[PhongMaterial] = cellToColor.map { color => new PhongMaterial { diffuseColor = color specularColor = Color.White specularPower = 1.0 } } /** Black, having the ''cell'' color code 0. */ val Black = Value /** Red, having the ''cell'' color code 1. */ val Red = Value /** Green, having the ''cell'' color code 2. */ val Green = Value /** Yellow, having the ''cell'' color code 3. */ val Yellow = Value /** Blue, having the ''cell'' color code 4. */ val Blue = Value /** Magenta, having the ''cell'' color code 5. */ val Magenta = Value /** Cyan, having the ''cell'' color code 6. */ val Cyan = Value /** White, having the ''cell'' color code 7. */ val White = Value /** Light gray, having the ''cell'' color code 8. */ val LightGray = Value /** Dark gray, having the ''cell'' color code 9. */ val DarkGray = Value /** Brown, having the ''cell'' color code 10. */ val Brown = Value /** Light blue, having the ''cell'' color code 11. */ val LightBlue = Value /** Purple, having the ''cell'' color code 12. */ val Purple = Value /** Orange, having the ''cell'' color code 13. */ val Orange = Value /** Light green, having the ''cell'' color code 14. */ val LightGreen = Value /** Light yellow, having the ''cell'' color code 15. */ val LightYellow = Value /** Default color, which is used if an explicit color is not specified. @note This is a material instance, not a color. */ val Default = Red /** Minimum color code value. */ private[cell] val minValue = 0 /** Maximum color code value. */ private[cell] val maxValue = maxId - 1 /** Conversion of ''cell'' color to ''ScalaFX'' color. @note This could be made an implicit function, but that might encourage the use of ''cell'' colors in regular code, when ideally we want to bury them. @param color ''Cell'' color value to be converted. @return Corresponding ''ScalaFX'' color. */ private[cell] def toColor(color: CellColor.Value) = { assertNonNull(color) cellToColor(color.id) } /** Conversion of ''cell'' color to ''ScalaFX'' material. @note This could be made an implicit function, but that might encourage the use of ''cell'' colors in regular code, when ideally we want to bury them. @param color ''Cell'' color value to be converted. @return Corresponding ''ScalaFX'' material. */ private[cell] def toMaterial(color: CellColor.Value) = { assertNonNull(color) cellToMaterial(color.id) } /** Verify a color code. @param colorCode Code for the color to be verified. @return `true` if the code maps to a valid color, `false` otherwise. */ private[cell] def verify(colorCode: Int) =(colorCode >= minValue && colorCode <= maxValue) /** Read color from ''cell'' data stream. @param scene Scene from which the color is to be read. @param colorType Type of color value to be read. @return Cell color read, if valid. @throws org.facsim.anim.cell.IncorrectFormatException if the file supplied is not an ''AutoMod® cell'' file. @throws org.facsim.anim.cell.ParsingErrorException if errors are encountered during parsing of the file. @see [[http://facsim.org/Documentation/Resources/AutoModCellFile/Colors.html Face & Edge Colors]] */ private[cell] def read(scene: CellScene, colorType: CellColorType.Value) = { /* Sanity checks. */ assertNonNull(scene) assertNonNull(colorType) /* Read the color code from the data stream. */ val code = scene.readInt(verify(_), LibResource ("anim.cell.CellColor.read", colorType.id, minValue, maxValue)) /* Convert to cell color and return. */ CellColor(code) } }
lgpl-3.0
ssangkong/NVRAM_KWU
qt-everywhere-opensource-src-4.7.4/src/corelib/plugin/quuid.cpp
18744
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "quuid.h" #include "qdatastream.h" QT_BEGIN_NAMESPACE /*! \class QUuid \brief The QUuid class stores a Universally Unique Identifier (UUID). \reentrant Using \e{U}niversally \e{U}nique \e{ID}entifiers (UUID) is a standard way to uniquely identify entities in a distributed computing environment. A UUID is a 16-byte (128-bit) number generated by some algorithm that is meant to guarantee that the UUID will be unique in the distributed computing environment where it is used. The acronym GUID is often used instead, \e{G}lobally \e{U}nique \e{ID}entifiers, but it refers to the same thing. \target Variant field Actually, the GUID is one \e{variant} of UUID. Multiple variants are in use. Each UUID contains a bit field that specifies which type (variant) of UUID it is. Call variant() to discover which type of UUID an instance of QUuid contains. It extracts the three most signifcant bits of byte 8 of the 16 bytes. In QUuid, byte 8 is \c{QUuid::data4[0]}. If you create instances of QUuid using the constructor that accepts all the numeric values as parameters, use the following table to set the three most significant bits of parameter \c{b1}, which becomes \c{QUuid::data4[0]} and contains the variant field in its three most significant bits. In the table, 'x' means \e {don't care}. \table \header \o msb0 \o msb1 \o msb2 \o Variant \row \o 0 \o x \o x \o NCS (Network Computing System) \row \o 1 \o 0 \o x \o DCE (Distributed Computing Environment) \row \o 1 \o 1 \o 0 \o Microsoft (GUID) \row \o 1 \o 1 \o 1 \o Reserved for future expansion \endtable \target Version field If variant() returns QUuid::DCE, the UUID also contains a \e{version} field in the four most significant bits of \c{QUuid::data3}, and you can call version() to discover which version your QUuid contains. If you create instances of QUuid using the constructor that accepts all the numeric values as parameters, use the following table to set the four most significant bits of parameter \c{w2}, which becomes \c{QUuid::data3} and contains the version field in its four most significant bits. \table \header \o msb0 \o msb1 \o msb2 \o msb3 \o Version \row \o 0 \o 0 \o 0 \o 1 \o Time \row \o 0 \o 0 \o 1 \o 0 \o Embedded POSIX \row \o 0 \o 0 \o 1 \o 1 \o Name \row \o 0 \o 1 \o 0 \o 0 \o Random \endtable The field layouts for the DCE versions listed in the table above are specified in the \l{http://www.ietf.org/rfc/rfc4122.txt} {Network Working Group UUID Specification}. Most platforms provide a tool for generating new UUIDs, e.g. \c uuidgen and \c guidgen. You can also use createUuid(). UUIDs generated by createUuid() are of the random type. Their QUuid::Version bits are set to QUuid::Random, and their QUuid::Variant bits are set to QUuid::DCE. The rest of the UUID is composed of random numbers. Theoretically, this means there is a small chance that a UUID generated by createUuid() will not be unique. But it is \l{http://en.wikipedia.org/wiki/Universally_Unique_Identifier#Random_UUID_probability_of_duplicates} {a \e{very} small chance}. UUIDs can be constructed from numeric values or from strings, or using the static createUuid() function. They can be converted to a string with toString(). UUIDs have a variant() and a version(), and null UUIDs return true from isNull(). */ /*! \fn QUuid::QUuid(const GUID &guid) Casts a Windows \a guid to a Qt QUuid. \warning This function is only for Windows platforms. */ /*! \fn QUuid &QUuid::operator=(const GUID &guid) Assigns a Windows \a guid to a Qt QUuid. \warning This function is only for Windows platforms. */ /*! \fn QUuid::operator GUID() const Returns a Windows GUID from a QUuid. \warning This function is only for Windows platforms. */ /*! \fn QUuid::QUuid() Creates the null UUID. toString() will output the null UUID as "{00000000-0000-0000-0000-000000000000}". */ /*! \fn QUuid::QUuid(uint l, ushort w1, ushort w2, uchar b1, uchar b2, uchar b3, uchar b4, uchar b5, uchar b6, uchar b7, uchar b8) Creates a UUID with the value specified by the parameters, \a l, \a w1, \a w2, \a b1, \a b2, \a b3, \a b4, \a b5, \a b6, \a b7, \a b8. Example: \snippet doc/src/snippets/code/src_corelib_plugin_quuid.cpp 0 */ #ifndef QT_NO_QUUID_STRING /*! Creates a QUuid object from the string \a text, which must be formatted as five hex fields separated by '-', e.g., "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where 'x' is a hex digit. The curly braces shown here are optional, but it is normal to include them. If the conversion fails, a null UUID is created. See toString() for an explanation of how the five hex fields map to the public data members in QUuid. \sa toString(), QUuid() */ QUuid::QUuid(const QString &text) { bool ok; if (text.isEmpty()) { *this = QUuid(); return; } QString temp = text.toUpper(); if (temp[0] != QLatin1Char('{')) temp = QLatin1Char('{') + text; if (text[(int)text.length()-1] != QLatin1Char('}')) temp += QLatin1Char('}'); data1 = temp.mid(1, 8).toULongLong(&ok, 16); if (!ok) { *this = QUuid(); return; } data2 = temp.mid(10, 4).toUInt(&ok, 16); if (!ok) { *this = QUuid(); return; } data3 = temp.mid(15, 4).toUInt(&ok, 16); if (!ok) { *this = QUuid(); return; } data4[0] = temp.mid(20, 2).toUInt(&ok, 16); if (!ok) { *this = QUuid(); return; } data4[1] = temp.mid(22, 2).toUInt(&ok, 16); if (!ok) { *this = QUuid(); return; } for (int i = 2; i<8; i++) { data4[i] = temp.mid(25 + (i-2)*2, 2).toUShort(&ok, 16); if (!ok) { *this = QUuid(); return; } } } /*! \internal */ QUuid::QUuid(const char *text) { *this = QUuid(QString::fromLatin1(text)); } #endif /*! \fn bool QUuid::operator==(const QUuid &other) const Returns true if this QUuid and the \a other QUuid are identical; otherwise returns false. */ /*! \fn bool QUuid::operator!=(const QUuid &other) const Returns true if this QUuid and the \a other QUuid are different; otherwise returns false. */ #ifndef QT_NO_QUUID_STRING /*! \fn QUuid::operator QString() const Returns the string representation of the uuid. \sa toString() */ static QString uuidhex(uint data, int digits) { return QString::number(data, 16).rightJustified(digits, QLatin1Char('0')); } /*! Returns the string representation of this QUuid. The string is formatted as five hex fields separated by '-' and enclosed in curly braces, i.e., "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where 'x' is a hex digit. From left to right, the five hex fields are obtained from the four public data members in QUuid as follows: \table \header \o Field # \o Source \row \o 1 \o data1 \row \o 2 \o data2 \row \o 3 \o data3 \row \o 4 \o data4[0] .. data4[1] \row \o 5 \o data4[2] .. data4[7] \endtable */ QString QUuid::toString() const { QString result; QChar dash = QLatin1Char('-'); result = QLatin1Char('{') + uuidhex(data1,8); result += dash; result += uuidhex(data2,4); result += dash; result += uuidhex(data3,4); result += dash; result += uuidhex(data4[0],2); result += uuidhex(data4[1],2); result += dash; for (int i = 2; i < 8; i++) result += uuidhex(data4[i],2); return result + QLatin1Char('}'); } #endif #ifndef QT_NO_DATASTREAM /*! \relates QUuid Writes the UUID \a id to the data stream \a s. */ QDataStream &operator<<(QDataStream &s, const QUuid &id) { s << (quint32)id.data1; s << (quint16)id.data2; s << (quint16)id.data3; for (int i = 0; i < 8; i++) s << (quint8)id.data4[i]; return s; } /*! \relates QUuid Reads a UUID from the stream \a s into \a id. */ QDataStream &operator>>(QDataStream &s, QUuid &id) { quint32 u32; quint16 u16; quint8 u8; s >> u32; id.data1 = u32; s >> u16; id.data2 = u16; s >> u16; id.data3 = u16; for (int i = 0; i < 8; i++) { s >> u8; id.data4[i] = u8; } return s; } #endif // QT_NO_DATASTREAM /*! Returns true if this is the null UUID {00000000-0000-0000-0000-000000000000}; otherwise returns false. */ bool QUuid::isNull() const { return data4[0] == 0 && data4[1] == 0 && data4[2] == 0 && data4[3] == 0 && data4[4] == 0 && data4[5] == 0 && data4[6] == 0 && data4[7] == 0 && data1 == 0 && data2 == 0 && data3 == 0; } /*! \enum QUuid::Variant This enum defines the values used in the \l{Variant field} {variant field} of the UUID. The value in the variant field determines the layout of the 128-bit value. \value VarUnknown Variant is unknown \value NCS Reserved for NCS (Network Computing System) backward compatibility \value DCE Distributed Computing Environment, the scheme used by QUuid \value Microsoft Reserved for Microsoft backward compatibility (GUID) \value Reserved Reserved for future definition */ /*! \enum QUuid::Version This enum defines the values used in the \l{Version field} {version field} of the UUID. The version field is meaningful only if the value in the \l{Variant field} {variant field} is QUuid::DCE. \value VerUnknown Version is unknown \value Time Time-based, by using timestamp, clock sequence, and MAC network card address (if available) for the node sections \value EmbeddedPOSIX DCE Security version, with embedded POSIX UUIDs \value Name Name-based, by using values from a name for all sections \value Random Random-based, by using random numbers for all sections */ /*! \fn QUuid::Variant QUuid::variant() const Returns the value in the \l{Variant field} {variant field} of the UUID. If the return value is QUuid::DCE, call version() to see which layout it uses. The null UUID is considered to be of an unknown variant. \sa version() */ QUuid::Variant QUuid::variant() const { if (isNull()) return VarUnknown; // Check the 3 MSB of data4[0] if ((data4[0] & 0x80) == 0x00) return NCS; else if ((data4[0] & 0xC0) == 0x80) return DCE; else if ((data4[0] & 0xE0) == 0xC0) return Microsoft; else if ((data4[0] & 0xE0) == 0xE0) return Reserved; return VarUnknown; } /*! \fn QUuid::Version QUuid::version() const Returns the \l{Version field} {version field} of the UUID, if the UUID's \l{Variant field} {variant field} is QUuid::DCE. Otherwise it returns QUuid::VerUnknown. \sa variant() */ QUuid::Version QUuid::version() const { // Check the 4 MSB of data3 Version ver = (Version)(data3>>12); if (isNull() || (variant() != DCE) || ver < Time || ver > Random) return VerUnknown; return ver; } /*! \fn bool QUuid::operator<(const QUuid &other) const Returns true if this QUuid has the same \l{Variant field} {variant field} as the \a other QUuid and is lexicographically \e{before} the \a other QUuid. If the \a other QUuid has a different variant field, the return value is determined by comparing the two \l{QUuid::Variant} {variants}. \sa variant() */ #define ISLESS(f1, f2) if (f1!=f2) return (f1<f2); bool QUuid::operator<(const QUuid &other) const { if (variant() != other.variant()) return variant() < other.variant(); ISLESS(data1, other.data1); ISLESS(data2, other.data2); ISLESS(data3, other.data3); for (int n = 0; n < 8; n++) { ISLESS(data4[n], other.data4[n]); } return false; } /*! \fn bool QUuid::operator>(const QUuid &other) const Returns true if this QUuid has the same \l{Variant field} {variant field} as the \a other QUuid and is lexicographically \e{after} the \a other QUuid. If the \a other QUuid has a different variant field, the return value is determined by comparing the two \l{QUuid::Variant} {variants}. \sa variant() */ #define ISMORE(f1, f2) if (f1!=f2) return (f1>f2); bool QUuid::operator>(const QUuid &other) const { if (variant() != other.variant()) return variant() > other.variant(); ISMORE(data1, other.data1); ISMORE(data2, other.data2); ISMORE(data3, other.data3); for (int n = 0; n < 8; n++) { ISMORE(data4[n], other.data4[n]); } return false; } /*! \fn QUuid QUuid::createUuid() On any platform other than Windows, this function returns a new UUID with variant QUuid::DCE and version QUuid::Random. If the /dev/urandom device exists, then the numbers used to construct the UUID will be of cryptographic quality, which will make the UUID unique. Otherwise, the numbers of the UUID will be obtained from the local pseudo-random number generator (qrand(), which is seeded by qsrand()) which is usually not of cryptograhic quality, which means that the UUID can't be guaranteed to be unique. On a Windows platform, a GUID is generated, which almost certainly \e{will} be unique, on this or any other system, networked or not. \sa variant(), version() */ #if defined(Q_OS_WIN32) && ! defined(Q_CC_MWERKS) QT_BEGIN_INCLUDE_NAMESPACE #include <objbase.h> // For CoCreateGuid QT_END_INCLUDE_NAMESPACE QUuid QUuid::createUuid() { GUID guid; CoCreateGuid(&guid); QUuid result = guid; return result; } #else // !Q_OS_WIN32 QT_BEGIN_INCLUDE_NAMESPACE #include "qdatetime.h" #include "qfile.h" #include "qthreadstorage.h" #include <stdlib.h> // for RAND_MAX QT_END_INCLUDE_NAMESPACE #if !defined(QT_BOOTSTRAPPED) && defined(Q_OS_UNIX) Q_GLOBAL_STATIC(QThreadStorage<QFile *>, devUrandomStorage); #endif QUuid QUuid::createUuid() { QUuid result; uint *data = &(result.data1); #if defined(Q_OS_UNIX) QFile *devUrandom; # if !defined(QT_BOOTSTRAPPED) devUrandom = devUrandomStorage()->localData(); if (!devUrandom) { devUrandom = new QFile(QLatin1String("/dev/urandom")); devUrandom->open(QIODevice::ReadOnly | QIODevice::Unbuffered); devUrandomStorage()->setLocalData(devUrandom); } # else QFile file(QLatin1String("/dev/urandom")); devUrandom = &file; devUrandom->open(QIODevice::ReadOnly | QIODevice::Unbuffered); # endif enum { AmountToRead = 4 * sizeof(uint) }; if (devUrandom->isOpen() && devUrandom->read((char *) data, AmountToRead) == AmountToRead) { // we got what we wanted, nothing more to do ; } else #endif { static const int intbits = sizeof(int)*8; static int randbits = 0; if (!randbits) { int r = 0; int max = RAND_MAX; do { ++r; } while ((max=max>>1)); randbits = r; } // Seed the PRNG once per thread with a combination of current time, a // stack address and a serial counter (since thread stack addresses are // re-used). #ifndef QT_BOOTSTRAPPED static QThreadStorage<int *> uuidseed; if (!uuidseed.hasLocalData()) { int *pseed = new int; static QBasicAtomicInt serial = Q_BASIC_ATOMIC_INITIALIZER(2); qsrand(*pseed = QDateTime::currentDateTime().toTime_t() + quintptr(&pseed) + serial.fetchAndAddRelaxed(1)); uuidseed.setLocalData(pseed); } #else static bool seeded = false; if (!seeded) qsrand(QDateTime::currentDateTime().toTime_t() + quintptr(&seeded)); #endif int chunks = 16 / sizeof(uint); while (chunks--) { uint randNumber = 0; for (int filled = 0; filled < intbits; filled += randbits) randNumber |= qrand()<<filled; *(data+chunks) = randNumber; } } result.data4[0] = (result.data4[0] & 0x3F) | 0x80; // UV_DCE result.data3 = (result.data3 & 0x0FFF) | 0x4000; // UV_Random return result; } #endif // !Q_OS_WIN32 /*! \fn bool QUuid::operator==(const GUID &guid) const Returns true if this UUID is equal to the Windows GUID \a guid; otherwise returns false. */ /*! \fn bool QUuid::operator!=(const GUID &guid) const Returns true if this UUID is not equal to the Windows GUID \a guid; otherwise returns false. */ QT_END_NAMESPACE
lgpl-3.0
sporekj/svobodnitest
vendor/venne/cms-module/CmsModule/Pages/Rss/RssPresenter.php
1692
<?php /** * This file is part of the Venne:CMS (https://github.com/Venne) * * Copyright (c) 2011, 2012 Josef Kříž (http://www.josef-kriz.cz) * * For the full copyright and license information, please view * the file license.txt that was distributed with this source code. */ namespace CmsModule\Pages\Rss; use CmsModule\Content\Presenters\ItemsPresenter; use CmsModule\Content\Repositories\RouteRepository; /** * @author Josef Kříž <pepakriz@gmail.com> */ class RssPresenter extends ItemsPresenter { /** @var RouteRepository */ protected $repository; /** * @param RouteRepository $repository */ public function injectRepository(RouteRepository $repository) { $this->repository = $repository; } public function renderDefault() { $this->template->host = $this->getHttpRequest()->getUrl()->host; $this->template->scheme = $this->getHttpRequest()->getUrl()->scheme; } /** * @return RssRepository */ protected function getRepository() { return $this->repository; } protected function getItemsPerPage() { return $this->extendedRoute->items; } protected function getQueryBuilder() { $qb = parent::getQueryBuilder(); if ($this->extendedRoute->class) { $qb = $qb->andWhere('a.class = :class')->setParameter('class', $this->extendedRoute->class); } if (count($this->extendedRoute->targetPages)) { $ids = array(); foreach ($this->extendedRoute->targetPages as $page) { $ids[] = $page->id; } $qb = $qb->andWhere('a.page IN (:page)')->setParameter('page', $ids); } $qb->orderBy('a.released', 'DESC'); return $qb; } }
lgpl-3.0
LinJiarui/Mccs
MCCS/ChaseCameraMode.cs
6355
/* *********************************************** * author : LinJiarui/exAt/ex@ * file : ChaseCameraMode * history: created by LinJiarui 2013/10/20 星期日 9:09:01 * modified by * ***********************************************/ using System; using System.Collections.Generic; using Mogre; namespace Mccs { /// <summary> /// In this mode the camera follows the target. The second parameter is the relative position /// to the target. The orientation of the camera is fixed by a yaw axis (UNIT_Y by default). /// </summary> public class ChaseCameraMode : CameraModeWithTightness, ICollidableCamera { private List<MovableObject> _ignoreList; private Vector3 _fixedAxis; private Vector3 _relativePositionToCameraTarget; private bool _fixedStep; private float _delta; private float _remainingTime; public ChaseCameraMode(CameraControlSystem cam, Vector3 relativePositionToCameraTarget, Vector3 fixedAxis, float margin = 0.1f, bool fixedStep = false, float delta = 0.001f) : base(cam) { Margin = margin; CameraCS = cam; _fixedAxis = fixedAxis; _relativePositionToCameraTarget = relativePositionToCameraTarget; _fixedStep = fixedStep; _delta = delta; CameraTightness = 0.01f; _remainingTime = 0; } public override bool Init() { //todo Init() should use CameraMode.Init() //CameraMode.Init(); CameraPosition = ((CameraMode)this).CameraCS.CameraPosition; CameraOrientation = ((CameraMode)this).CameraCS.CameraOrientation; _delta = 0; _remainingTime = 0; SetFixedYawAxis(true, _fixedAxis); ((CameraMode) this).CameraCS.AutoTrackingTarget = true; this.CollisionFunc = this.DefaultCollisionDetectionFunction; InstantUpdate(); return true; } public override void Update(float timeSinceLastFrame) { if (((CameraMode) this).CameraCS.HasCameraTarget) { var cameraCurrentPosition = ((CameraMode) this).CameraCS.CameraPosition; var cameraFinalPositionIfNoTightness = ((CameraMode) this).CameraCS.CameraTargetPosition + ((CameraMode) this).CameraCS.CameraTargetOrientation * _relativePositionToCameraTarget; if (!_fixedStep) { var diff = (cameraFinalPositionIfNoTightness - cameraCurrentPosition) * CameraTightness; CameraPosition += diff; //! @todo CameraPos += diff * timeSinceLastFrame; this makes the camera mode time independent but it also make impossible to get a completely rigid link (tightness = 1) } else { _remainingTime += timeSinceLastFrame; int steps = (int)(_remainingTime / _delta); var mFinalTime = steps * _delta; var cameraCurrentOrientation = ((CameraMode) this).CameraCS.CameraOrientation; var finalPercentage = mFinalTime / _remainingTime; var cameraFinalPosition = cameraCurrentPosition + ((cameraFinalPositionIfNoTightness - cameraCurrentPosition) * finalPercentage); var cameraFinalOrientation = Quaternion.Slerp(finalPercentage, cameraCurrentOrientation , ((CameraMode) this).CameraCS.CameraTargetOrientation); var cameraIntermediatePosition = cameraCurrentPosition; var cameraIntermediateOrientation = cameraCurrentOrientation; for (int i = 0; i < steps; i++) { var percentage = ((i + 1) / (float)steps); var intermediatePositionIfNoTightness = cameraCurrentPosition + ((cameraFinalPositionIfNoTightness - cameraCurrentPosition) * percentage); var diff = (intermediatePositionIfNoTightness - cameraCurrentPosition) * CameraTightness; CameraPosition += diff; } } if (CollisionsEnabled) { CameraPosition = CollisionFunc(((CameraMode)this).CameraCS.CameraTargetPosition, CameraPosition); } } } public override void InstantUpdate() { if ( ((CameraMode) this).CameraCS.HasCameraTarget) { CameraPosition = ((CameraMode)this).CameraCS.CameraTargetPosition + ((CameraMode) this).CameraCS.CameraTargetOrientation * _relativePositionToCameraTarget; if (CollisionsEnabled) { CameraPosition = CollisionFunc(((CameraMode)this).CameraCS.CameraTargetPosition, CameraPosition); } } } public virtual void SetCameraRelativePosition(Vector3 posRelativeToCameraTarget) { _relativePositionToCameraTarget = posRelativeToCameraTarget; InstantUpdate(); } public virtual void SetFixedYawAxis(bool useFixedAxis, Vector3 fixedAxis) { _fixedAxis = fixedAxis; ((CameraMode) this).CameraCS.SetFixedYawAxis(true, _fixedAxis); } #region Implementation of ICollidableCamera public float Margin { get; set; } public bool CollisionsEnabled { get; set; } public CameraControlSystem CameraCS { get; set; } public List<MovableObject> IgnoreList { get { return _ignoreList; } } public void AddToIgnoreList(MovableObject obj) { _ignoreList.Add(obj); } public Func<Vector3, Vector3, Vector3> CollisionFunc { get; set; } #endregion public Vector3 RelativePosToTarget { get { return _relativePositionToCameraTarget; }internal set { _relativePositionToCameraTarget = value; }} public Vector3 FixedAxis { get { return _fixedAxis; }internal set { _fixedAxis = value; }} } }
lgpl-3.0
felixge/goamz
s3/s3.go
12529
// // goamz - Go packages to interact with the Amazon Web Services. // // https://wiki.ubuntu.com/goamz // // Copyright (c) 2011 Canonical Ltd. // // Written by Gustavo Niemeyer <gustavo.niemeyer@canonical.com> // package s3 import ( "bytes" "encoding/xml" "fmt" "io" "io/ioutil" "launchpad.net/goamz/aws" "log" "net/http" "net/http/httputil" "net/url" "strconv" "strings" "time" ) const debug = false // The S3 type encapsulates operations with an S3 region. type S3 struct { aws.Auth aws.Region private byte // Reserve the right of using private data. } // The Bucket type encapsulates operations with an S3 bucket. type Bucket struct { *S3 Name string } // The Owner type represents the owner of the object in an S3 bucket. type Owner struct { ID string DisplayName string } // New creates a new S3. func New(auth aws.Auth, region aws.Region) *S3 { return &S3{auth, region, 0} } // Bucket returns a Bucket with the given name. func (s3 *S3) Bucket(name string) *Bucket { if s3.Region.S3BucketEndpoint != "" || s3.Region.S3LowercaseBucket { name = strings.ToLower(name) } return &Bucket{s3, name} } var createBucketConfiguration = `<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <LocationConstraint>%s</LocationConstraint> </CreateBucketConfiguration>` // locationConstraint returns an io.Reader specifying a LocationConstraint if // required for the region. // // See http://goo.gl/bh9Kq for more details. func (s3 *S3) locationConstraint() io.Reader { constraint := "" if s3.Region.S3LocationConstraint { constraint = fmt.Sprintf(createBucketConfiguration, s3.Region.Name) } return strings.NewReader(constraint) } type ACL string const ( Private = ACL("private") PublicRead = ACL("public-read") PublicReadWrite = ACL("public-read-write") AuthenticatedRead = ACL("authenticated-read") BucketOwnerRead = ACL("bucket-owner-read") BucketOwnerFull = ACL("bucket-owner-full-control") ) // PutBucket creates a new bucket. // // See http://goo.gl/ndjnR for more details. func (b *Bucket) PutBucket(perm ACL) error { headers := map[string][]string{ "x-amz-acl": {string(perm)}, } req := &request{ method: "PUT", bucket: b.Name, path: "/", headers: headers, payload: b.locationConstraint(), } return b.S3.query(req, nil) } // DelBucket removes an existing S3 bucket. All objects in the bucket must // be removed before the bucket itself can be removed. // // See http://goo.gl/GoBrY for more details. func (b *Bucket) DelBucket() error { req := &request{ method: "DELETE", bucket: b.Name, path: "/", } return b.S3.query(req, nil) } // Get retrieves an object from an S3 bucket. // // See http://goo.gl/isCO7 for more details. func (b *Bucket) Get(path string) (data []byte, err error) { body, err := b.GetReader(path) if err != nil { return nil, err } data, err = ioutil.ReadAll(body) body.Close() return data, err } // GetReader retrieves an object from an S3 bucket. // It is the caller's responsibility to call Close on rc when // finished reading. func (b *Bucket) GetReader(path string) (rc io.ReadCloser, err error) { req := &request{ bucket: b.Name, path: path, } err = b.S3.prepare(req) if err != nil { return nil, err } resp, err := b.S3.run(req, nil) if err != nil { return nil, err } return resp.Body, nil } // Put inserts an object into the S3 bucket. // // See http://goo.gl/FEBPD for more details. func (b *Bucket) Put(path string, data []byte, contType string, perm ACL) error { body := bytes.NewBuffer(data) return b.PutReader(path, body, int64(len(data)), contType, perm) } // PutReader inserts an object into the S3 bucket by consuming data // from r until EOF. func (b *Bucket) PutReader(path string, r io.Reader, length int64, contType string, perm ACL) error { headers := map[string][]string{ "Content-Length": {strconv.FormatInt(length, 10)}, "Content-Type": {contType}, "x-amz-acl": {string(perm)}, } req := &request{ method: "PUT", bucket: b.Name, path: path, headers: headers, payload: r, } return b.S3.query(req, nil) } // Del removes an object from the S3 bucket. // // See http://goo.gl/APeTt for more details. func (b *Bucket) Del(path string) error { req := &request{ method: "DELETE", bucket: b.Name, path: path, } return b.S3.query(req, nil) } // The ListResp type holds the results of a List bucket operation. type ListResp struct { Name string Prefix string Delimiter string Marker string MaxKeys int // IsTruncated is true if the results have been truncated because // there are more keys and prefixes than can fit in MaxKeys. // N.B. this is the opposite sense to that documented (incorrectly) in // http://goo.gl/YjQTc IsTruncated bool Contents []Key CommonPrefixes []string `xml:">Prefix"` } // The Key type represents an item stored in an S3 bucket. type Key struct { Key string LastModified string Size int64 // ETag gives the hex-encoded MD5 sum of the contents, // surrounded with double-quotes. ETag string StorageClass string Owner Owner } // List returns a information about objects in an S3 bucket. // // The prefix parameter limits the response to keys that begin with the // specified prefix. You can use prefixes to separate a bucket into different // groupings of keys (e.g. to get a feeling of folders). // // The delimited parameter causes the response to group all of the keys that // share a common prefix up to the next delimiter to be grouped in a single // entry within the CommonPrefixes field. // // The marker parameter specifies the key to start with when listing objects // in a bucket. Amazon S3 lists objects in alphabetical order and // will return keys alphabetically greater than the marker. // // The max parameter specifies how many keys + common prefixes to return in // the response. The default is 1000. // // For example, given these keys in a bucket: // // index.html // index2.html // photos/2006/January/sample.jpg // photos/2006/February/sample2.jpg // photos/2006/February/sample3.jpg // photos/2006/February/sample4.jpg // // Listing this bucket with delimiter set to "/" would yield the // following result: // // &ListResp{ // Name: "sample-bucket", // MaxKeys: 1000, // Delimiter: "/", // Contents: []Key{ // {Key: "index.html", "index2.html"}, // }, // CommonPrefixes: []string{ // "photos/", // }, // } // // Listing the same bucket with delimiter set to "/" and prefix set to // "photos/2006/" would yield the following result: // // &ListResp{ // Name: "sample-bucket", // MaxKeys: 1000, // Delimiter: "/", // Prefix: "photos/2006/", // CommonPrefixes: []string{ // "photos/2006/February/", // "photos/2006/January/", // }, // } // // See http://goo.gl/YjQTc for more details. func (b *Bucket) List(prefix, delim, marker string, max int) (result *ListResp, err error) { params := map[string][]string{ "prefix": {prefix}, "delimiter": {delim}, "marker": {marker}, } if max != 0 { params["max-keys"] = []string{strconv.FormatInt(int64(max), 10)} } req := &request{ bucket: b.Name, params: params, } result = &ListResp{} err = b.S3.query(req, result) if err != nil { return nil, err } return result, nil } // URL returns a non-signed URL that allows retriving the // object at path. It only works if the object is publicly // readable (see SignedURL). func (b *Bucket) URL(path string) string { req := &request{ bucket: b.Name, path: path, } err := b.S3.prepare(req) if err != nil { panic(err) } u, err := req.url() if err != nil { panic(err) } u.RawQuery = "" return u.String() } // SignedURL returns a signed URL that allows anyone holding the URL // to retrieve the object at path. The signature is valid until expires. func (b *Bucket) SignedURL(path string, expires time.Time) string { req := &request{ bucket: b.Name, path: path, params: url.Values{"Expires": {strconv.FormatInt(expires.Unix(), 10)}}, } err := b.S3.prepare(req) if err != nil { panic(err) } u, err := req.url() if err != nil { panic(err) } return u.String() } type request struct { method string bucket string path string params url.Values headers http.Header baseurl string payload io.Reader } func (req *request) url() (*url.URL, error) { u, err := url.Parse(req.baseurl) if err != nil { return nil, fmt.Errorf("bad S3 endpoint URL %q: %v", req.baseurl, err) } u.RawQuery = req.params.Encode() u.Path = req.path return u, nil } // query prepares and runs the req request. // If resp is not nil, the XML data contained in the response // body will be unmarshalled on it. func (s3 *S3) query(req *request, resp interface{}) error { err := s3.prepare(req) if err == nil { _, err = s3.run(req, resp) } return err } // prepare sets up req to be delivered to S3. func (s3 *S3) prepare(req *request) error { if req.method == "" { req.method = "GET" } if req.params == nil { req.params = make(url.Values) } if req.headers == nil { req.headers = make(http.Header) } if !strings.HasPrefix(req.path, "/") { req.path = "/" + req.path } canonicalPath := req.path if req.bucket != "" { req.baseurl = s3.Region.S3BucketEndpoint if req.baseurl == "" { // Use the path method to address the bucket. req.baseurl = s3.Region.S3Endpoint req.path = "/" + req.bucket + req.path } else { // Just in case, prevent injection. if strings.IndexAny(req.bucket, "/:@") >= 0 { return fmt.Errorf("bad S3 bucket: %q", req.bucket) } req.baseurl = strings.Replace(req.baseurl, "${bucket}", req.bucket, -1) } canonicalPath = "/" + req.bucket + canonicalPath } u, err := url.Parse(req.baseurl) if err != nil { return fmt.Errorf("bad S3 endpoint URL %q: %v", req.baseurl, err) } req.headers["Host"] = []string{u.Host} req.headers["Date"] = []string{time.Now().In(time.UTC).Format(time.RFC1123)} sign(s3.Auth, req.method, canonicalPath, req.params, req.headers) return nil } // run sends req and returns the http response from the server. // If resp is not nil, the XML data contained in the response // body will be unmarshalled on it. func (s3 *S3) run(req *request, resp interface{}) (*http.Response, error) { if debug { log.Printf("Running S3 request: %#v", req) } u, err := req.url() if err != nil { return nil, err } // Copy since headers may be mutated and we should be able to // call this function twice with the same request. headers := make(http.Header, len(req.headers)) for k, v := range req.headers { headers[k] = v } hreq := http.Request{ URL: u, Method: req.method, ProtoMajor: 1, ProtoMinor: 1, Close: true, Header: headers, } if v, ok := headers["Content-Length"]; ok { hreq.ContentLength, _ = strconv.ParseInt(v[0], 10, 64) delete(headers, "Content-Length") } if req.payload != nil { hreq.Body = ioutil.NopCloser(req.payload) } hresp, err := http.DefaultClient.Do(&hreq) if err != nil { return nil, err } if debug { dump, _ := httputil.DumpResponse(hresp, true) log.Printf("} -> %s\n", dump) } if hresp.StatusCode != 200 && hresp.StatusCode != 204 { return nil, buildError(hresp) } if resp != nil { err = xml.NewDecoder(hresp.Body).Decode(resp) hresp.Body.Close() } return hresp, err } // Error represents an error in an operation with S3. type Error struct { StatusCode int // HTTP status code (200, 403, ...) Code string // EC2 error code ("UnsupportedOperation", ...) Message string // The human-oriented error message BucketName string RequestId string HostId string } func (e *Error) Error() string { return e.Message } func buildError(r *http.Response) error { if debug { log.Printf("got error (status code %v)", r.StatusCode) data, err := ioutil.ReadAll(r.Body) if err != nil { log.Printf("\tread error: %v", err) } else { log.Printf("\tdata:\n%s\n\n", data) } r.Body = ioutil.NopCloser(bytes.NewBuffer(data)) } err := Error{} // TODO return error if Unmarshal fails? xml.NewDecoder(r.Body).Decode(&err) r.Body.Close() err.StatusCode = r.StatusCode if err.Message == "" { err.Message = r.Status } if debug { log.Printf("err: %#v\n", err) } return &err }
lgpl-3.0
jandom/plumed2
src/tools/MolDataClass.cpp
32576
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copyright (c) 2013-2020 The plumed team (see the PEOPLE file at the root of the distribution for a list of names) See http://www.plumed.org for more information. This file is part of plumed, version 2. plumed is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. plumed 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 plumed. If not, see <http://www.gnu.org/licenses/>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #include "MolDataClass.h" #include "Exception.h" #include "Tools.h" #include "PDB.h" namespace PLMD { unsigned MolDataClass::numberOfAtomsPerResidueInBackbone( const std::string& type ) { if( type=="protein" ) return 5; else if( type=="dna" ) return 6; else if( type=="rna" ) return 6; else return 0; } bool MolDataClass::allowedResidue( const std::string& type, const std::string& residuename ) { if( type=="protein" ) { if(residuename=="ALA") return true; else if(residuename=="ARG") return true; else if(residuename=="ASN") return true; else if(residuename=="ASP") return true; else if(residuename=="CYS") return true; else if(residuename=="GLN") return true; else if(residuename=="GLU") return true; else if(residuename=="GLY") return true; else if(residuename=="HIS") return true; else if(residuename=="ILE") return true; else if(residuename=="LEU") return true; else if(residuename=="LYS") return true; else if(residuename=="MET") return true; else if(residuename=="PHE") return true; else if(residuename=="PRO") return true; else if(residuename=="SER") return true; else if(residuename=="THR") return true; else if(residuename=="TRP") return true; else if(residuename=="TYR") return true; else if(residuename=="VAL") return true; // Terminal groups else if(residuename=="ACE") return true; else if(residuename=="NME") return true; else if(residuename=="NH2") return true; // Alternative residue names in common force fields else if(residuename=="GLH") return true; // neutral GLU else if(residuename=="ASH") return true; // neutral ASP else if(residuename=="HID") return true; // HIS-D amber else if(residuename=="HSD") return true; // HIS-D charmm else if(residuename=="HIE") return true; // HIS-E amber else if(residuename=="HSE") return true; // HIS-E charmm else if(residuename=="HIP") return true; // HIS-P amber else if(residuename=="HSP") return true; // HIS-P charmm // Weird amino acids else if(residuename=="NLE") return true; else if(residuename=="SFO") return true; else return false; } else if( type=="dna" ) { if(residuename=="A") return true; else if(residuename=="A5") return true; else if(residuename=="A3") return true; else if(residuename=="AN") return true; else if(residuename=="G") return true; else if(residuename=="G5") return true; else if(residuename=="G3") return true; else if(residuename=="GN") return true; else if(residuename=="T") return true; else if(residuename=="T5") return true; else if(residuename=="T3") return true; else if(residuename=="TN") return true; else if(residuename=="C") return true; else if(residuename=="C5") return true; else if(residuename=="C3") return true; else if(residuename=="CN") return true; else if(residuename=="DA") return true; else if(residuename=="DA5") return true; else if(residuename=="DA3") return true; else if(residuename=="DAN") return true; else if(residuename=="DG") return true; else if(residuename=="DG5") return true; else if(residuename=="DG3") return true; else if(residuename=="DGN") return true; else if(residuename=="DT") return true; else if(residuename=="DT5") return true; else if(residuename=="DT3") return true; else if(residuename=="DTN") return true; else if(residuename=="DC") return true; else if(residuename=="DC5") return true; else if(residuename=="DC3") return true; else if(residuename=="DCN") return true; else return false; } else if( type=="rna" ) { if(residuename=="A") return true; else if(residuename=="A5") return true; else if(residuename=="A3") return true; else if(residuename=="AN") return true; else if(residuename=="G") return true; else if(residuename=="G5") return true; else if(residuename=="G3") return true; else if(residuename=="GN") return true; else if(residuename=="U") return true; else if(residuename=="U5") return true; else if(residuename=="U3") return true; else if(residuename=="UN") return true; else if(residuename=="C") return true; else if(residuename=="C5") return true; else if(residuename=="C3") return true; else if(residuename=="CN") return true; else if(residuename=="RA") return true; else if(residuename=="RA5") return true; else if(residuename=="RA3") return true; else if(residuename=="RAN") return true; else if(residuename=="RG") return true; else if(residuename=="RG5") return true; else if(residuename=="RG3") return true; else if(residuename=="RGN") return true; else if(residuename=="RU") return true; else if(residuename=="RU5") return true; else if(residuename=="RU3") return true; else if(residuename=="RUN") return true; else if(residuename=="RC") return true; else if(residuename=="RC5") return true; else if(residuename=="RC3") return true; else if(residuename=="RCN") return true; else return false; } else if( type=="water" ) { if(residuename=="SOL") return true; if(residuename=="WAT") return true; return false; } else if( type=="ion" ) { if(residuename=="IB+") return true; if(residuename=="CA") return true; if(residuename=="CL") return true; if(residuename=="NA") return true; if(residuename=="MG") return true; if(residuename=="K") return true; if(residuename=="RB") return true; if(residuename=="CS") return true; if(residuename=="LI") return true; if(residuename=="ZN") return true; return false; } return false; } void MolDataClass::getBackboneForResidue( const std::string& type, const unsigned& residuenum, const PDB& mypdb, std::vector<AtomNumber>& atoms ) { std::string residuename=mypdb.getResidueName( residuenum ); plumed_massert( MolDataClass::allowedResidue( type, residuename ), "residue " + residuename + " unrecognized for molecule type " + type ); if( type=="protein" ) { if( residuename=="GLY") { atoms.resize(5); atoms[0]=mypdb.getNamedAtomFromResidue("N",residuenum); atoms[1]=mypdb.getNamedAtomFromResidue("CA",residuenum); atoms[2]=mypdb.getNamedAtomFromResidue("HA2",residuenum); atoms[3]=mypdb.getNamedAtomFromResidue("C",residuenum); atoms[4]=mypdb.getNamedAtomFromResidue("O",residuenum); } else if( residuename=="ACE") { atoms.resize(1); atoms[0]=mypdb.getNamedAtomFromResidue("C",residuenum); } else if( residuename=="NME"||residuename=="NH2") { atoms.resize(1); atoms[0]=mypdb.getNamedAtomFromResidue("N",residuenum); } else { atoms.resize(5); atoms[0]=mypdb.getNamedAtomFromResidue("N",residuenum); atoms[1]=mypdb.getNamedAtomFromResidue("CA",residuenum); atoms[2]=mypdb.getNamedAtomFromResidue("CB",residuenum); atoms[3]=mypdb.getNamedAtomFromResidue("C",residuenum); atoms[4]=mypdb.getNamedAtomFromResidue("O",residuenum); } } else if( type=="dna" || type=="rna" ) { atoms.resize(6); atoms[0]=mypdb.getNamedAtomFromResidue("P",residuenum); atoms[1]=mypdb.getNamedAtomFromResidue("O5\'",residuenum); atoms[2]=mypdb.getNamedAtomFromResidue("C5\'",residuenum); atoms[3]=mypdb.getNamedAtomFromResidue("C4\'",residuenum); atoms[4]=mypdb.getNamedAtomFromResidue("C3\'",residuenum); atoms[5]=mypdb.getNamedAtomFromResidue("O3\'",residuenum); } else { plumed_merror(type + " is not a valid molecule type"); } } bool MolDataClass::isTerminalGroup( const std::string& type, const std::string& residuename ) { if( type=="protein" ) { if( residuename=="ACE" ) return true; else if( residuename=="NME" ) return true; else if( residuename=="NH2" ) return true; else return false; } else { plumed_merror(type + " is not a valid molecule type"); } return false; } void MolDataClass::specialSymbol( const std::string& type, const std::string& symbol, const PDB& mypdb, std::vector<AtomNumber>& numbers ) { if(type=="protein" || type=="rna" || type=="dna") { // symbol should be something like // phi-123 i.e. phi torsion of residue 123 of first chain // psi-A321 i.e. psi torsion of residue 321 of chain A // psi-4_321 is psi torsion of residue 321 of chain 4 // psi-A_321 is equivalent to psi-A321 numbers.resize(0); // special cases: if(symbol=="protein") { const auto & all = mypdb.getAtomNumbers(); for(auto a : all) { auto resname=mypdb.getResidueName(a); Tools::stripLeadingAndTrailingBlanks(resname); if(allowedResidue("protein",resname)) numbers.push_back(a); } return; } if(symbol=="nucleic") { const auto & all = mypdb.getAtomNumbers(); for(auto a : all) { auto resname=mypdb.getResidueName(a); Tools::stripLeadingAndTrailingBlanks(resname); if(allowedResidue("dna",resname) || allowedResidue("rna",resname)) numbers.push_back(a); } return; } if(symbol=="ions") { const auto & all = mypdb.getAtomNumbers(); for(auto a : all) { auto resname=mypdb.getResidueName(a); Tools::stripLeadingAndTrailingBlanks(resname); if(allowedResidue("ion",resname)) numbers.push_back(a); } return; } if(symbol=="water") { const auto & all = mypdb.getAtomNumbers(); for(auto a : all) { auto resname=mypdb.getResidueName(a); Tools::stripLeadingAndTrailingBlanks(resname); if(allowedResidue("water",resname)) numbers.push_back(a); } return; } if(symbol=="hydrogens") { const auto & all = mypdb.getAtomNumbers(); for(auto a : all) { auto atomname=mypdb.getAtomName(a); Tools::stripLeadingAndTrailingBlanks(atomname); auto notnumber=atomname.find_first_not_of("0123456789"); if(notnumber!=std::string::npos && atomname[notnumber]=='H') numbers.push_back(a); } return; } if(symbol=="nonhydrogens") { const auto & all = mypdb.getAtomNumbers(); for(auto a : all) { auto atomname=mypdb.getAtomName(a); Tools::stripLeadingAndTrailingBlanks(atomname); auto notnumber=atomname.find_first_not_of("0123456789"); if(!(notnumber!=std::string::npos && atomname[notnumber]=='H')) numbers.push_back(a); } return; } std::size_t dash=symbol.find_first_of('-'); if(dash==std::string::npos) plumed_error() << "Unrecognized symbol "<<symbol; std::size_t firstunderscore=symbol.find_first_of('_',dash+1); std::size_t firstnum=symbol.find_first_of("0123456789",dash+1); std::string name=symbol.substr(0,dash); unsigned resnum; std::string resname; std::string chainid; if(firstunderscore != std::string::npos) { Tools::convert( symbol.substr(firstunderscore+1), resnum ); chainid=symbol.substr(dash+1,firstunderscore-(dash+1)); } else if(firstnum==dash+1) { Tools::convert( symbol.substr(dash+1), resnum ); chainid="*"; // this is going to match the first chain } else { // if chain id is provided: Tools::convert( symbol.substr(firstnum), resnum ); chainid=symbol.substr(dash+1,firstnum-(dash+1)); // this is going to match the proper chain } resname= mypdb.getResidueName(resnum,chainid); Tools::stripLeadingAndTrailingBlanks(resname); if(allowedResidue("protein",resname)) { if( name=="phi" && !isTerminalGroup("protein",resname) ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C",resnum-1,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CA",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C",resnum,chainid)); } else if( name=="psi" && !isTerminalGroup("protein",resname) ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CA",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N",resnum+1,chainid)); } else if( name=="omega" && !isTerminalGroup("protein",resname) ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CA",resnum-1,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C",resnum-1,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CA",resnum,chainid)); } else if( name=="chi1" && !isTerminalGroup("protein",resname) ) { if ( resname=="GLY" || resname=="ALA" || resname=="SFO" ) plumed_merror("chi-1 is not defined for ALA, GLY and SFO"); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CA",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CB",resnum,chainid)); if(resname=="ILE"||resname=="VAL") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CG1",resnum,chainid)); } else if(resname=="CYS") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("SG",resnum,chainid)); } else if(resname=="THR") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("OG1",resnum,chainid)); } else if(resname=="SER") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("OG",resnum,chainid)); } else { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CG",resnum,chainid)); } } else if( name=="chi2" && !isTerminalGroup("protein",resname) ) { if ( resname=="GLY" || resname=="ALA" || resname=="SFO" || resname=="CYS" || resname=="SER" || resname=="THR" || resname=="VAL" ) plumed_merror("chi-2 is not defined for ALA, GLY, CYS, SER, THR, VAL and SFO"); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CA",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CB",resnum,chainid)); if(resname=="ILE") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CG1",resnum,chainid)); } else { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CG",resnum,chainid)); } if(resname=="ASN" || resname=="ASP") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("OD1",resnum,chainid)); } else if(resname=="HIS") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("ND1",resnum,chainid)); } else if(resname=="LEU" || resname=="PHE" || resname=="TRP" || resname=="TYR") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CD1",resnum,chainid)); } else if(resname=="MET") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("SD",resnum,chainid)); } else { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CD",resnum,chainid)); } } else if( name=="chi3" && !isTerminalGroup("protein",resname) ) { if (!( resname=="ARG" || resname=="GLN" || resname=="GLU" || resname=="LYS" || resname=="MET" )) plumed_merror("chi-3 is defined only for ARG, GLN, GLU, LYS and MET"); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CB",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CG",resnum,chainid)); if(resname=="MET") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("SD",resnum,chainid)); } else { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CD",resnum,chainid)); } if(resname=="GLN" || resname=="GLU") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("OE1",resnum,chainid)); } else if(resname=="LYS" || resname=="MET") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CE",resnum,chainid)); } else { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("NE",resnum,chainid)); } } else if( name=="chi4" && !isTerminalGroup("protein",resname) ) { if (!( resname=="ARG" || resname=="LYS" )) plumed_merror("chi-4 is defined only for ARG and LYS"); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CG",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CD",resnum,chainid)); if(resname=="ARG") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("NE",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CZ",resnum,chainid)); } else { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CE",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("NZ",resnum,chainid)); } } else if( name=="chi5" && !isTerminalGroup("protein",resname) ) { if (!( resname=="ARG" )) plumed_merror("chi-5 is defined only for ARG"); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CD",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("NE",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("CZ",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("NH1",resnum,chainid)); } else if( name=="sidechain" && !isTerminalGroup("protein",resname) ) { if(resname=="GLY") plumed_merror("sidechain is not defined for GLY"); std::vector<AtomNumber> tmpnum1(mypdb.getAtomsInResidue(resnum,chainid)); for(unsigned i=0; i<tmpnum1.size(); i++) { if(mypdb.getAtomName(tmpnum1[i])!="N"&&mypdb.getAtomName(tmpnum1[i])!="CA"&& mypdb.getAtomName(tmpnum1[i])!="C"&&mypdb.getAtomName(tmpnum1[i])!="O"&& mypdb.getAtomName(tmpnum1[i])!="HA"&&mypdb.getAtomName(tmpnum1[i])!="H"&& mypdb.getAtomName(tmpnum1[i])!="HN"&&mypdb.getAtomName(tmpnum1[i])!="H1"&& mypdb.getAtomName(tmpnum1[i])!="H2"&&mypdb.getAtomName(tmpnum1[i])!="H3"&& mypdb.getAtomName(tmpnum1[i])!="OXT"&&mypdb.getAtomName(tmpnum1[i])!="OT1"&& mypdb.getAtomName(tmpnum1[i])!="OT2"&&mypdb.getAtomName(tmpnum1[i])!="OC1"&& mypdb.getAtomName(tmpnum1[i])!="OC2") { numbers.push_back( tmpnum1[i] ); } } } else if( name=="back" && !isTerminalGroup("protein",resname) ) { std::vector<AtomNumber> tmpnum1(mypdb.getAtomsInResidue(resnum,chainid)); for(unsigned i=0; i<tmpnum1.size(); i++) { if(mypdb.getAtomName(tmpnum1[i])=="N"||mypdb.getAtomName(tmpnum1[i])=="CA"|| mypdb.getAtomName(tmpnum1[i])=="C"||mypdb.getAtomName(tmpnum1[i])=="O"|| mypdb.getAtomName(tmpnum1[i])=="HA"||mypdb.getAtomName(tmpnum1[i])=="H"|| mypdb.getAtomName(tmpnum1[i])=="HN"||mypdb.getAtomName(tmpnum1[i])=="H1"|| mypdb.getAtomName(tmpnum1[i])=="H2"||mypdb.getAtomName(tmpnum1[i])=="H3"|| mypdb.getAtomName(tmpnum1[i])=="OXT"||mypdb.getAtomName(tmpnum1[i])=="OT1"|| mypdb.getAtomName(tmpnum1[i])=="OT2"||mypdb.getAtomName(tmpnum1[i])=="OC1"|| mypdb.getAtomName(tmpnum1[i])=="OC2"||mypdb.getAtomName(tmpnum1[i])=="HA1"|| mypdb.getAtomName(tmpnum1[i])=="HA2"||mypdb.getAtomName(tmpnum1[i])=="HA3") { numbers.push_back( tmpnum1[i] ); } } } else numbers.push_back(mypdb.getNamedAtomFromResidueAndChain(name,resnum,chainid)); } else if( allowedResidue("rna",resname) || allowedResidue("dna",resname)) { std::string basetype; if(resname.find_first_of("A")!=std::string::npos) basetype+="A"; if(resname.find_first_of("U")!=std::string::npos) basetype+="U"; if(resname.find_first_of("T")!=std::string::npos) basetype+="T"; if(resname.find_first_of("C")!=std::string::npos) basetype+="C"; if(resname.find_first_of("G")!=std::string::npos) basetype+="G"; plumed_massert(basetype.length()==1,"cannot find type of rna/dna residue "+resname+" "+basetype); if( name=="chi" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C1\'",resnum,chainid)); if(basetype=="T" || basetype=="U" || basetype=="C") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N1",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2",resnum,chainid)); } else if(basetype=="G" || basetype=="A") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N9",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4",resnum,chainid)); } else plumed_error(); } else if( name=="alpha" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O3\'",resnum-1,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("P",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O5\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5\'",resnum,chainid)); } else if( name=="beta" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("P",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O5\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); } else if( name=="gamma" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O5\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); } else if( name=="delta" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O3\'",resnum,chainid)); } else if( name=="epsilon" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O3\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("P",resnum+1,chainid)); } else if( name=="zeta" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O3\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("P",resnum+1,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O5\'",resnum+1,chainid)); } else if( name=="v0" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C1\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2\'",resnum,chainid)); } else if( name=="v1" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C1\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); } else if( name=="v2" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C1\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); } else if( name=="v3" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O4\'",resnum,chainid)); } else if( name=="v4" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C1\'",resnum,chainid)); } else if( name=="back" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("P",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O5\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O3\'",resnum,chainid)); } else if( name=="sugar" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O4\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C1\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2\'",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C3\'",resnum,chainid)); } else if( name=="base" ) { if(basetype=="C") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N1",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O2",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N3",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N4",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C6",resnum,chainid)); } else if(basetype=="U") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N1",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O2",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N3",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O4",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C6",resnum,chainid)); } else if(basetype=="T") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N1",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O2",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N3",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O4",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C7",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C6",resnum,chainid)); } else if(basetype=="G") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N9",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N3",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N2",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N1",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C6",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("O6",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N7",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C8",resnum,chainid)); } else if(basetype=="A") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N9",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N1",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N3",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C6",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N6",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C5",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("N7",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C8",resnum,chainid)); } else plumed_error(); } else if( name=="lcs" ) { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C2",resnum,chainid)); if(basetype=="T" || basetype=="U" || basetype=="C") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C6",resnum,chainid)); } else if(basetype=="G" || basetype=="A") { numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C6",resnum,chainid)); numbers.push_back(mypdb.getNamedAtomFromResidueAndChain("C4",resnum,chainid)); } else plumed_error(); } else numbers.push_back(mypdb.getNamedAtomFromResidueAndChain(name,resnum,chainid)); } else numbers.push_back(mypdb.getNamedAtomFromResidueAndChain(name,resnum,chainid)); } else { plumed_merror(type + " is not a valid molecule type"); } } }
lgpl-3.0
project2you/students-attendance
mobile/js/jquery.easy-confirm-dialog.js
5831
/** * jQuery Easy Confirm Dialog plugin 1.4 * * Copyright (c) 2010 Emil Janitzek (http://projectshadowlight.org) * Based on Confirm 1.3 by Nadia Alramli (http://nadiana.com/) * * Samples and instructions at: * http://projectshadowlight.org/jquery-easy-confirm-dialog/ * * This script 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. */ (function($) { $.easyconfirm = {}; $.easyconfirm.locales = {}; $.easyconfirm.locales.enUS = { title: 'Are you sure?', text: 'Are you sure that you want to perform this action?', button: ['Cancel', 'OK'], closeText: 'close' }; $.easyconfirm.locales.svSE = { title: 'Är du säker?', text: 'Är du säker på att du vill genomföra denna åtgärden?', button: ['Avbryt', 'OK'], closeText: 'stäng' }; $.easyconfirm.locales.itIT = { title: 'Sei sicuro?', text: 'Sei sicuro di voler compiere questa azione?', button: ['Annulla', 'Conferma'], closeText: 'chiudi' }; $.fn.easyconfirm = function(options) { var _attr = $.fn.attr; $.fn.attr = function(attr, value) { // Let the original attr() do its work. var returned = _attr.apply(this, arguments); // Fix for jQuery 1.6+ if (attr == 'title' && returned === undefined) returned = ''; return returned; }; var options = jQuery.extend({ eventType: 'click', icon: 'help', minHeight: 120, maxHeight: 200 }, options); var locale = jQuery.extend({}, $.easyconfirm.locales.enUS, options.locale); // Shortcut to eventType. var type = options.eventType; return this.each(function() { var target = this; var $target = jQuery(target); // If no events present then and if there is a valid url, then trigger url change var urlClick = function() { if (hasValidUrl(target.href)) { document.location = target.href; } }, hasValidUrl = function(href) { if (href) { var length = String(href).length; if (href.substring(length - 1, length) != '#') return true; } return false; }, // If any handlers where bind before triggering, lets save them and add them later saveHandlers = function() { var events = $._data(target, 'events'); if (events) { target._handlers = new Array(); for (var i in events[type]) { target._handlers.push(events[type][i]); } $target.unbind(type); } }, // Re-bind old events rebindHandlers = function() { if (target._handlers !== undefined) { for (var i in target._handlers) { $target.bind(type, target._handlers[i]); } } }; if ($target.attr('title') !== null && $target.attr('title').length > 0) locale.text = $target.attr('title'); var dialog = (options.dialog === undefined || typeof(options.dialog) != 'object') ? $('<div class="dialog confirm">' + locale.text + '</div>') : options.dialog; var buttons = {}; buttons[locale.button[0]] = function() { $(dialog).dialog('close'); }; buttons[locale.button[1]] = function() { // Unbind overriding handler and let default actions pass through $target.unbind(type, handler); // Close dialog $(dialog).dialog('close'); // Check if there is any events on the target var anyEvents = $._data(target, 'events'); if (anyEvents || !hasValidUrl(target.href)) { // Trigger click event. $target.trigger(type); } else { // No event trigger new url urlClick(); } init(); }; $(dialog).dialog({ autoOpen: false, resizable: false, draggable: true, closeOnEscape: true, width: 'auto', minHeight: options.minHeight, maxHeight: options.maxHeight, buttons: buttons, title: locale.title, closeText: locale.closeText, modal: true, open: function() { $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:eq(1)').focus() } }); // Handler that will override all other actions var handler = function(event) { event.stopImmediatePropagation(); event.preventDefault(); $(dialog).dialog('open'); }, init = function() { saveHandlers(); $target.bind(type, handler); rebindHandlers(); }; init(); }); }; })(jQuery);
lgpl-3.0
edwinspire/VSharp
class/System.Web/Test/System.Web.UI.WebControls/CompositeDataBoundControlTest.cs
5426
// // Tests for System.Web.UI.WebControls.CompositeDataBoundControl.cs // // Author: // Igor Zelmanovich (igorz@mainsoft.com) // // // Copyright (C) 2006 Mainsoft, Inc (http://www.mainsoft.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using NUnit.Framework; using System; using System.IO; using System.Globalization; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections; namespace MonoTests.System.Web.UI.WebControls { [TestFixture] public class CompositeDataBoundControlTest { class MyCompositeDataBoundControl : CompositeDataBoundControl { public bool ensureDataBound = false; public bool ensureCreateChildControls = false; public bool createChildControls1 = false; public bool createChildControls2 = false; public bool dataBind = false; public bool CreateChildControls_ChildControlsCreated; public int CreateChildControls_Controls_Count; protected override int CreateChildControls (IEnumerable dataSource, bool dataBinding) { createChildControls2 = true; CreateChildControls_ChildControlsCreated = ChildControlsCreated; CreateChildControls_Controls_Count = Controls.Count; return 10; } public void DoEnsureChildControls () { EnsureChildControls (); } public void DoCreateChildControls () { CreateChildControls (); } public override void DataBind () { base.DataBind (); dataBind = true; } protected override void EnsureDataBound () { base.EnsureDataBound (); ensureDataBound = true; } protected override void EnsureChildControls () { base.EnsureChildControls (); ensureCreateChildControls = true; } protected internal override void CreateChildControls () { base.CreateChildControls (); createChildControls1 = true; } public bool GetRequiresDataBinding () { return RequiresDataBinding; } public void SetRequiresDataBinding (bool value) { RequiresDataBinding = value; } public bool GetChildControlsCreated () { return ChildControlsCreated; } } [Test] public void DetailsView_EnsureChildControlsFlow () { MyCompositeDataBoundControl c = new MyCompositeDataBoundControl (); Assert.IsFalse (c.GetRequiresDataBinding()); c.DoEnsureChildControls (); Assert.IsTrue (c.ensureCreateChildControls); Assert.IsFalse (c.ensureDataBound); Assert.IsFalse (c.dataBind); Assert.IsTrue (c.createChildControls1); Assert.IsFalse (c.createChildControls2); } [Test] public void DetailsView_EnsureChildControlsFlow2 () { MyCompositeDataBoundControl c = new MyCompositeDataBoundControl (); c.SetRequiresDataBinding (true); Assert.IsTrue (c.GetRequiresDataBinding ()); c.DoEnsureChildControls (); Assert.IsTrue (c.ensureCreateChildControls); Assert.IsTrue (c.ensureDataBound); Assert.IsFalse (c.dataBind); Assert.IsTrue (c.createChildControls1); Assert.IsFalse (c.createChildControls2); } [Test] public void DetailsView_CreateChildControls_Clear () { MyCompositeDataBoundControl c = new MyCompositeDataBoundControl (); c.Controls.Add (new WebControl (HtmlTextWriterTag.A)); Assert.AreEqual (1, c.Controls.Count); c.DoCreateChildControls (); Assert.AreEqual (0, c.Controls.Count); } [Test] public void DetailsView_CreateChildControls_Clear2 () { MyCompositeDataBoundControl c = new MyCompositeDataBoundControl (); c.Controls.Add (new WebControl (HtmlTextWriterTag.A)); Assert.AreEqual (1, c.Controls.Count, "Controls.Count before DataBind"); c.DataBind (); Assert.AreEqual (0, c.CreateChildControls_Controls_Count, "Controls.Count in CreateChildControls"); Assert.AreEqual (0, c.Controls.Count, "Controls.Count after DataBind"); } [Test] public void DataBind_ChildControlsCreated () { Page p = new Page (); MyCompositeDataBoundControl c = new MyCompositeDataBoundControl (); p.Controls.Add (c); Assert.IsFalse (c.GetChildControlsCreated (), "ChildControlsCreated before DataBind"); c.DataBind (); Assert.IsTrue (c.ensureCreateChildControls); Assert.IsTrue (c.createChildControls1); Assert.IsTrue (c.createChildControls2); Assert.IsTrue (c.CreateChildControls_ChildControlsCreated, "ChildControlsCreated in CreateChildControls"); Assert.IsTrue (c.GetChildControlsCreated (), "ChildControlsCreated after DataBind"); } } } #endif
lgpl-3.0
sebastianbk/Firefly
AR.Drone.Data/Navigation/Native/Options/navdata_magneto_t.cs
829
using System.Runtime.InteropServices; using AR.Drone.Data.Navigation.Native.Math; namespace AR.Drone.Data.Navigation.Native.Options { [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct navdata_magneto_t { public ushort tag; public ushort size; public short mx; public short my; public short mz; public vector31_t magneto_raw; public vector31_t magneto_rectified; public vector31_t magneto_offset; public float heading_unwrapped; public float heading_gyro_unwrapped; public float heading_fusion_unwrapped; public byte magneto_calibration_ok; public uint magneto_state; public float magneto_radius; public float error_mean; public float error_var; } }
lgpl-3.0
Sebazzz/EntityProfiler
src/UI/EntityProfiler.Viewer/Modules/Connection/SessionDataCommandProvider.cs
1504
using System.ComponentModel.Composition; using System.Windows.Input; using Caliburn.Micro; using EntityProfiler.Viewer.Modules.Connection.ViewModels; namespace EntityProfiler.Viewer.Modules.Connection { [Export("SessionDataCommandProvider", typeof (SessionDataCommandProvider))] [PartCreationPolicy(CreationPolicy.Shared)] public class SessionDataCommandProvider { public void ShowAllDataContexts() { SessionData.Current.ShowAllDataContexts(); } public void ShowDataContext(DataContextViewModel dataContextViewModel) { SessionData.Current.ShowDataContext(dataContextViewModel); } public void HideDataContext(DataContextViewModel dataContextViewModel) { SessionData.Current.HideDataContext(dataContextViewModel); } public void OnPreviewKeyDown(ActionExecutionContext context) { var keyArgs = context.EventArgs as KeyEventArgs; var dataContextViewModel = SessionData.Current.SelectedDataContext; if (keyArgs != null && dataContextViewModel != null) { /*if (keyArgs.Key == Key.Space || keyArgs.Key == Key.Enter) { return; }*/ if (keyArgs.Key == Key.Delete) { SessionData.Current.HideDataContext(dataContextViewModel); return; } } } } }
lgpl-3.0
ericomattos/javaforce
projects/jffile/src/jffile/JFileBrowser.java
44570
package jffile; /** * Created : Aug 11, 2012 * * @author pquiring */ import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javaforce.*; import javaforce.jbus.*; import javaforce.linux.*; import javaforce.utils.*; public class JFileBrowser extends javax.swing.JComponent implements MouseListener, MouseMotionListener, KeyListener, monitordir.Listener { /** * Creates new form JFileBrowser * @param view - any of the VIEW_... types * @param path - initial path to view (local system only) * @param desktopMenu - popup menu for unused areas of panel * @param fileMenu - popup menu for files * @param wallPaperFile - PNG file to wallpaper panel (optional) * @param wallPaperView - WALLPAPER_VIEW_... types * @param saveConfig - saves layout to .desktop file * @param openFolder - program to open folders with (else just navigates to them) (optional) * @param openFile - program to open files * @param backClr - background color (selections) and (if no wallpaper) * @param foreClr - text color * @param useScrolling - use scroll bars? * @param arrangeIconsVertical - arrange icons vertical (else horizontal) * @param showHidden - show hidden files (files that begin with a period) * @param autoArrange - auto arrange by name * @param jbusClient - a JBusClient client * @param desktopMode - desktopMode (always use openFile for files) * @param fileClipboard - file selection storage */ public JFileBrowser(int view, String path, JPopupMenu desktopMenu, JPopupMenu fileMenu , String wallPaperFile, int wallPaperView, boolean saveConfig , String openFolder, String openFile, Color backClr, Color foreClr , boolean useScrolling, boolean arrangeIconsVertical, boolean showHidden, boolean autoArrange , JBusClient jbusClient, boolean desktopMode, FileClipboard fileClipboard) { setView(view); this.desktopMenu = desktopMenu; this.fileMenu = fileMenu; this.wallPaperFile = wallPaperFile; this.wallPaperView = wallPaperView; this.saveConfig = saveConfig; this.openFolder = openFolder; this.openFile = openFile; this.backClr = backClr; this.foreClr = foreClr; this.useScrolling = useScrolling; this.arrangeIconsVertical = arrangeIconsVertical; this.showHidden = showHidden; this.autoArrange = autoArrange; this.jbusClient = jbusClient; this.desktopMode = desktopMode; this.fileClipboard = fileClipboard; filterRegex = ".*"; filter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.matches(filterRegex); } }; loadWallPaper(); setLayout(null); setFocusable(true); setPath(path); //must do last since it calls refresh() addKeyListener(this); } public static final int VIEW_ICONS = 1; public static final int VIEW_LIST = 2; public static final int VIEW_DETAILS = 3; public static final int WALLPAPER_VIEW_CENTER = 0; public static final int WALLPAPER_VIEW_TILE = 1; public static final int WALLPAPER_VIEW_FULL = 2; public static final int WALLPAPER_VIEW_FILL = 3; private int view; private String path; private String mount; private JPopupMenu desktopMenu, fileMenu; private String wallPaperFile; private int wallPaperView; private boolean saveConfig; private String openFolder, openFile; public Color backClr, foreClr; private boolean useScrolling, arrangeIconsVertical; private boolean showHidden; private boolean autoArrange; private boolean desktopMode; private JFileBrowserListener listener; private JBusClient jbusClient; private FilenameFilter filter; private String filterRegex; private FileClipboard fileClipboard; private JFImage wallPaper; //icon view dimensions public static int ix, iy; //icon image size public static int bx, by; //icon size private int nx, ny; //next position private int mx, my; //last mouse pressed private ArrayList<FileEntry> entries = new ArrayList<FileEntry>(); private JScrollPane scroll; private JPanel panel; private boolean iconsVisible = true; public void setBounds(int x,int y,int w,int h) { super.setBounds(x,y,w,h); // JFLog.log("setBounds:" + getWidth() + "," + getHeight()); if (scroll != null) { scroll.setBounds(0,0,getWidth(),getHeight()); calcPanelSize(); } else if (panel != null) { panel.setBounds(0,0,getWidth(),getHeight()); } if (listener != null) listener.browserResized(this); update(); } public void setListener(JFileBrowserListener listener) { this.listener = listener; } private void initGUI() { // JFLog.log("initGUI:" + getWidth() + "," + getHeight()); panel = new JPanel() { public Dimension getPreferredSize() { return getSize(); } public void paintChildren(Graphics g) { if (!iconsVisible) return; super.paintChildren(g); } public void paintComponent(Graphics g) { // JFLog.log("JFB:paint"); g.setColor(backClr); int px = getWidth(); int py = getHeight(); g.fillRect(0,0,px,py); if (wallPaper != null) { //paint wallpaper int wx = wallPaper.getWidth(); int wy = wallPaper.getHeight(); switch (wallPaperView) { case WALLPAPER_VIEW_CENTER: g.drawImage(wallPaper.getImage(), (px - wx) / 2, (py - wy) / 2, null); break; case WALLPAPER_VIEW_TILE: Image img = wallPaper.getImage(); for(int x=0;x<px;x+=wx) { for(int y=0;y<py;y+=wy) { g.drawImage(img, x, y, null); } } break; case WALLPAPER_VIEW_FULL: //maintains aspect ratio int dx = px - wx; int dy = py - wy; if (dx > dy) { //image touches top/bottom (bars left/right) g.drawImage(wallPaper.getImage(), dx/2, 0, null); } else { //image touches left/right (bars top/bottom) g.drawImage(wallPaper.getImage(), 0, dy/2, null); } break; case WALLPAPER_VIEW_FILL: //ignore aspect ration : can distort image g.drawImage(wallPaper.getImage(), 0, 0, px, py, null); break; } } if (dragselection) { g.setColor(new Color(0x77003377, true)); int x1, y1, x2, y2; if (dragX < selX) { x1 = dragX; x2 = selX; } else { x2 = dragX; x1 = selX; } if (dragY < selY) { y1 = dragY; y2 = selY; } else { y2 = dragY; y1 = selY; } g.fillRect(x1,y1,x2-x1,y2-y1); } } }; panel.addMouseListener(this); panel.addMouseMotionListener(this); panel.addKeyListener(this); panel.setLayout(null); panel.setBounds(0,0,getWidth(),getHeight()); if (useScrolling) { scroll = new JScrollPane(panel); scroll.setBounds(0,0,getWidth(),getHeight()); add(scroll); } else { add(panel); } } private void listFiles() { // JFLog.log("path=" + path); // JFLog.log("JFileBrowser:listFiles():size=" + getWidth() + "," + getHeight()); File file = new File(path); File files[] = file.listFiles(filter); if (files == null) return; Arrays.sort(files); if (view != VIEW_ICONS) { bx = 0; by = 18; JFImage tmp = new JFImage(1,1); for(int a=0;a<files.length;a++) { int w = ix + tmp.getGraphics().getFontMetrics().stringWidth(files[a].getName()); if (w > bx) bx = w; } } for(int a=0;a<files.length;a++) { String fullfile = files[a].getAbsolutePath(); if (fullfile.endsWith("/.desktop")) continue; int idx = fullfile.lastIndexOf(File.separatorChar); if (fullfile.substring(idx+1).startsWith(".")) { if (!showHidden) continue; } if (files[a].isDirectory()) { addFolder(fullfile); } else { if (fullfile.endsWith(".desktop")) { addDesktopFile(fullfile); } else { addFile(fullfile); } } } } private void nextPosition(FileEntry entry, boolean check) { switch (view) { case VIEW_ICONS: nextPositionIcons(entry, check); break; case VIEW_LIST: nextPositionList(entry); break; case VIEW_DETAILS: nextPositionDetails(entry); break; } } private void nextPositionIcons(FileEntry entry, boolean check) { boolean noRoom = false; boolean tooClose; int px = getWidth(); int py = getHeight(); do { entry.x = nx; entry.y = ny; if (arrangeIconsVertical) { ny += by + 5; if (ny + by > py) { nx += bx + 5; ny = 5; } if (nx + bx > px && !useScrolling) { if (noRoom) { entry.x = 5; entry.y = 5; return; } nx = 5; noRoom = true; } } else { nx += bx + 5; if (nx + bx > px) { ny += by + 5; nx = 5; } if (ny + by > py && !useScrolling) { if (noRoom) { entry.x = 5; entry.y = 5; return; } ny = 5; noRoom = true; } } tooClose = false; if (check) { tooClose = checkProximity(entry); } } while(tooClose); } private void nextPositionList(FileEntry entry) { entry.x = nx; entry.y = ny; int px = getWidth(); int py = getHeight(); if ((arrangeIconsVertical) || (true)) { ny += by; if (ny + by > py) { nx += bx; ny = 0; } } else { //doesn't make sense to use this ever nx += bx; if (nx + bx > px) { ny += by; nx = 0; } } } private void nextPositionDetails(FileEntry entry) { entry.x = nx; entry.y = ny; ny += by; } public boolean checkProximity(FileEntry entry) { for(int a=0;a<entries.size();a++) { FileEntry otherEntry = entries.get(a); if (otherEntry == entry) continue; int dx = entry.x - otherEntry.x; int dy = entry.y - otherEntry.y; int len = (int)Math.sqrt(dx * dx + dy * dy); if (len < bx) return true; } return false; } private void addDetails(FileEntry entry) { File file = new File(entry.file); Calendar c = Calendar.getInstance(); c.setTimeInMillis(file.lastModified()); String date = String.format("%d-%d-%d", c.get(Calendar.YEAR), c.get(Calendar.MONTH)+1, c.get(Calendar.DAY_OF_MONTH)); String time = String.format("%02d:%02d", c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE)); String size = "" + file.length(); entry.details_date = new JLabel(date); entry.details_date.setForeground(foreClr); panel.add(entry.details_date); Dimension dim = entry.details_date.getPreferredSize(); entry.details_date.setBounds(entry.x + bx, entry.y, dim.width, dim.height); entry.details_time = new JLabel(time); entry.details_time.setForeground(foreClr); panel.add(entry.details_time); dim = entry.details_time.getPreferredSize(); entry.details_time.setBounds(entry.x + bx + 96, entry.y, dim.width, dim.height); entry.details_size = new JLabel(size); entry.details_size.setForeground(foreClr); panel.add(entry.details_size); dim = entry.details_size.getPreferredSize(); entry.details_size.setBounds(entry.x + bx + 96 + 64, entry.y, dim.width, dim.height); } private JFileIcon addIcon(FileEntry entry) { for(int a=0;a<entries.size();a++) { if (entries.get(a).file.equals(entry.file)) { return entries.get(a).button; } } if (!new File(entry.file).exists()) { JFLog.log("Error:File not found:" + entry.file); return null; } int px = getWidth(); int py = getHeight(); JFImage buttonImage = IconCache.loadIcon(entry.icon); buttonImage = IconCache.scaleIcon(buttonImage, ix, iy); entry.button = new JFileIcon(this, buttonImage, entry, view == VIEW_ICONS); entry.button.setToolTipText(entry.name); entry.button.addKeyListener(this); entry.button.addMouseListener(this); entry.button.addMouseMotionListener(this); if ((!useScrolling) && (view == VIEW_ICONS)) { if ((entry.x + bx > px) || (entry.y + by > py)) { nextPosition(entry, true); } } panel.add(entry.button); entry.button.setLocation(entry.x, entry.y); entries.add(entry); if (view == VIEW_DETAILS) { addDetails(entry); } return entry.button; } private JFileIcon addNewIcon(String icon, String name, String file) { FileEntry entry = new FileEntry(); nextPosition(entry, false); entry.icon = icon; entry.name = name; entry.file = file; return addIcon(entry); } private JFileIcon addNewIconDesktop(String fn) { String name = null, icon = null; try { FileInputStream fis = new FileInputStream(fn); byte data[] = JF.readAll(fis); fis.close(); String str = new String(data); String lns[] = str.split("\n"); boolean desktopEntry = false; for(int a=0;a<lns.length;a++) { if (lns[a].startsWith("[Desktop Entry]")) { desktopEntry = true; continue; } if (lns[a].startsWith("[")) desktopEntry = false; if (!desktopEntry) continue; if (lns[a].startsWith("Name=")) { name = lns[a].substring(5); } if (lns[a].startsWith("Icon=")) { icon = lns[a].substring(5); } } if (name == null) JFLog.log("Warning:No NAME field for icon:" + fn); if (icon == null) icon = "jfile-404"; int i1 = fn.lastIndexOf(File.separatorChar); name = fn.substring(i1+1, fn.length() - 8); //.desktop return addNewIcon(icon, name, fn); } catch (FileNotFoundException e) { JFLog.log("File not found:" + fn); return null; } catch (Exception e) { JFLog.log(e); return null; } } private String getFileName(String fn) { int idx; idx = fn.lastIndexOf(File.separatorChar); if (idx != -1) fn = fn.substring(idx+1); if (!fn.endsWith(".desktop")) return fn; //remove .desktop extension idx = fn.lastIndexOf("."); if (idx == -1) return fn; return fn.substring(0, idx); } private String getFolderName(String fn) { int idx = fn.lastIndexOf(File.separatorChar); if (idx == -1) return fn; return fn.substring(idx+1); } private void addFile(String fn) { switch (view) { case VIEW_ICONS: case VIEW_LIST: case VIEW_DETAILS: addNewIcon(IconCache.findIcon(fn), getFileName(fn), fn); break; } } private void addDesktopFile(String fn) { switch (view) { case VIEW_ICONS: case VIEW_LIST: case VIEW_DETAILS: addNewIconDesktop(fn); break; } } private void addFolder(String fn) { JFileIcon fi = null; String icon = NetworkShares.isShared(fn) ? "jfile-folder-shared" : "jfile-folder"; switch (view) { case VIEW_ICONS: case VIEW_LIST: case VIEW_DETAILS: fi = addNewIcon(icon, getFolderName(fn), fn); break; } if (fi == null) return; fi.entry.isDir = true; } private void loadWallPaper() { if (wallPaperFile == null) return; wallPaper = new JFImage(); if (!wallPaper.load(wallPaperFile)) { wallPaper = null; } } public void setWallPaper(String file, int mode) { wallPaperFile = file; wallPaperView = mode; loadWallPaper(); repaint(); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { int keycode = e.getKeyCode(); int mods = e.getModifiers(); // JFLog.log("keyPressed:" + mods + "," + (char)keycode); if (mods == KeyEvent.CTRL_MASK) { switch (keycode) { case KeyEvent.VK_C: copy(); break; case KeyEvent.VK_X: cut(); break; case KeyEvent.VK_V: paste(); break; } } if (mods == 0) { switch (keycode) { case KeyEvent.VK_DELETE: delete(); break; } } } public void keyReleased(KeyEvent e) { } public class Config { public FileEntry file[]; } private void loadConfig() { if (!saveConfig) return; try { String fn = path + "/.desktop"; Config config = new Config(); if (!new File(fn).exists()) { JFLog.log("Error:File not found:" + fn); return; } FileInputStream fis = new FileInputStream(fn); XML xml = new XML(); xml.read(fis); xml.writeClass(config); fis.close(); for(int a=0;a<config.file.length;a++) { addIcon(config.file[a]); } } catch (Exception e) { JFLog.log(e); } } private void saveConfig() { if (!saveConfig) return; //save Entries to .desktop file try { Config config = new Config(); config.file = entries.toArray(new FileEntry[0]); FileOutputStream fos = new FileOutputStream(path + "/.desktop"); XML xml = new XML(); xml.readClass("desktop", config); xml.write(fos); fos.close(); } catch (Exception e) { JFLog.log(e); } } @SuppressWarnings("unchecked") public void arrangeByName() { if (view != VIEW_ICONS) return; try { nx = 5; ny = 5; //place Home first FileEntry entry; Object list[] = panel.getComponents(); Arrays.sort(list, new Comparator() { public int compare(Object t1, Object t2) { if (!(t1 instanceof JFileIcon)) return 1; if (!(t2 instanceof JFileIcon)) return -1; JFileIcon b1 = (JFileIcon)t1; JFileIcon b2 = (JFileIcon)t2; String s1 = b1.getText(); if (s1.equals("Home")) return -1; String s2 = b2.getText(); if (s2.equals("Home")) return 1; return s1.compareTo(s2); } }); for(int a=0;a<list.length;a++) { if (!(list[a] instanceof JFileIcon)) continue; JFileIcon button = (JFileIcon)list[a]; entry = button.entry; if (entry == null) continue; nextPosition(entry, false); button.setLocation(entry.x, entry.y); } saveConfig(); update(); } catch (Exception e) { JFLog.log(e); } } public void arrangeByGrid() { if (view != VIEW_ICONS) return; try { FileEntry entry; Object list[] = panel.getComponents(); int xx = 5 + bx; int yy = 5 + by; for(int a=0;a<list.length;a++) { if (!(list[a] instanceof JFileIcon)) continue; JFileIcon button = (JFileIcon)list[a]; entry = button.entry; if (entry == null) continue; entry.x = ((((entry.x-5) + (xx/2)) / xx) * xx) + 5; entry.y = ((((entry.y-5) + (yy/2)) / yy) * yy) + 5; if (checkProximity(entry)) { nx = entry.x; ny = entry.y; nextPosition(entry, true); } button.setLocation(entry.x, entry.y); } saveConfig(); update(); } catch (Exception e) { JFLog.log(e); } } private void calcPanelSize() { int px = 0, py = 0; int w = bx; if (view == VIEW_DETAILS) { w += 256; //details columns } for(int a=0;a<entries.size();a++) { FileEntry entry = entries.get(a); int x = entry.x + w; if (x > px) px = x; int y = entry.y + by; if (y > py) py = y; } panel.setSize(px, py); } public void refresh() { if (path == null) return; // JFLog.log("JFileBrowser:refresh"); try { stopFolderListener(); removeAll(); entries.clear(); switch (view) { case VIEW_ICONS: nx = 5; ny = 5; break; case VIEW_LIST: nx = 0; ny = 0; break; case VIEW_DETAILS: nx = 0; ny = 0; break; } initGUI(); initDND(); loadConfig(); listFiles(); if (useScrolling) calcPanelSize(); update(); startFolderListener(); } catch (Exception e) { JFLog.log(e); } } public void setFilter(String regex) { filterRegex = regex; refresh(); } private void clearSelection() { int cnt = panel.getComponentCount(); for(int a=0;a<cnt;a++) { JComponent c = (JComponent)panel.getComponent(a); if (!(c instanceof JFileIcon)) continue; JFileIcon b = (JFileIcon)c; b.setSelected(false); b.setTransparent(false); } repaint(); } private void selectIcons() { //select icons from dragX/Y to selX/Y int x1, y1, x2, y2; if (dragX < selX) { x1 = dragX; x2 = selX; } else { x2 = dragX; x1 = selX; } if (dragY < selY) { y1 = dragY; y2 = selY; } else { y2 = dragY; y1 = selY; } int cnt = panel.getComponentCount(); for(int a=0;a<cnt;a++) { JComponent c = (JComponent)panel.getComponent(a); if (!(c instanceof JFileIcon)) continue; JFileIcon b = (JFileIcon)c; Point p = b.getLocation(); p.x += b.getWidth()/2; p.y += b.getHeight()/2; if ((p.x >= x1) && (p.x <= x2) && (p.y >= y1) && (p.y <= y2)) { b.setSelected(true); } else { b.setSelected(false); } } } public void setPath(String newpath) { if (newpath == null) return; try { if (mount != null) { if (!newpath.startsWith(mount)) { closeFile(); } } if (new File(newpath).isDirectory()) { path = newpath; } else { openFile(newpath); } refresh(); if (listener != null) listener.browserChangedPath(this, newpath); } catch (Exception e) { JFLog.log(e); } } public String getPath() { return path; } private void execute(String cmd[], boolean wait) { try { if (wait) { ProcessBuilder pb = new ProcessBuilder(); pb.command(cmd); Process p = pb.start(); p.waitFor(); } else { Runtime.getRuntime().exec(cmd); } } catch (Exception e) { JFLog.log(e); } } private void openEntry(FileEntry entry) { File file = new File(entry.file); if (!file.exists()) return; if (file.isDirectory()) { if (openFolder == null) { setPath(entry.file); } else { execute(new String[] {openFolder, entry.file}, false); } } else { if (entry.file.endsWith(".desktop")) { //execute desktop file try { Linux.executeDesktop(entry.file, null); } catch (Exception e) { JFLog.log(e); } } else if (!desktopMode && entry.file.toLowerCase().endsWith(".iso")) { openFile(entry.file); } else if (!desktopMode && entry.file.toLowerCase().endsWith(".zip")) { openFile(entry.file); } else { if (openFile == null) return; execute(new String[] {openFile, entry.file}, false); } } } public void invoke(JFileIcon b) { openEntry(b.entry); } private java.util.Timer refreshTimer; private Vector<String> newFiles = new Vector<String>(); private Vector<String> removeFiles = new Vector<String>(); private final Object lock = new Object(); public void folderChangeEvent(String event, String file) { // JFLog.log("folderChangeEvent:" + event + ":" + file); try { if (event.equals("CREATED") || event.equals("MOVED_TO")) { if ((file.startsWith(".")) && (!showHidden)) return; newFiles.add(file); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { while (newFiles.size() > 0) { String fn = path + "/" + newFiles.remove(0); File file = new File(fn); if (file.isDirectory()) { addFolder(fn); } else { if (fn.endsWith(".desktop")) { addDesktopFile(fn); } else { addFile(fn); } } } saveConfig(); update(); } }); } else if (event.equals("DELETED") || event.equals("MOVED_FROM")) { if (/*view == VIEW_LIST ||*/ view == VIEW_DETAILS) { //need to do a refresh in 100ms (just removing the icon would look bad) synchronized(lock) { if (refreshTimer == null) { refreshTimer = new java.util.Timer(); refreshTimer.schedule(new TimerTask() { public void run() { synchronized(lock) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { refreshTimer = null; refresh(); } }); } } }, 100); } } } else { //just remove the icon removeFiles.add(file); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Component list[] = panel.getComponents(); while (removeFiles.size() > 0) { String fn = removeFiles.remove(0); for(int a=0;a<list.length;a++) { if (!(list[a] instanceof JFileIcon)) continue; JFileIcon icon = (JFileIcon)list[a]; if (icon.entry.name.equals(fn)) { panel.remove(list[a]); break; } } for(int a=0;a<entries.size();a++) { if (entries.get(a).name.equals(fn)) { entries.remove(a); break; } } } saveConfig(); update(); } }); } } else if (event.equals("DELETE_SELF") || event.equals("MOVED_SELF")) { if (!desktopMode) { System.exit(0); } } } catch (Exception e) { JFLog.log(e); } } private int monitor = -1; private void startFolderListener() { monitor = monitordir.add(path); monitordir.setListener(monitor, this); } private void stopFolderListener() { if (monitor == -1) return; monitordir.remove(monitor); monitor = -1; } public void setIconsVisible(boolean state) { iconsVisible = state; repaint(); } public FileEntry createIcon(String name, String exec, String icon, String fn, boolean nextPos) { try { FileOutputStream fos = new FileOutputStream(fn); fos.write("[Desktop Entry]\n".getBytes()); fos.write(("Name=" + name + "\n").getBytes()); fos.write(("Exec=" + exec + "\n").getBytes()); fos.write(("Icon=" + icon + "\n").getBytes()); fos.close(); FileEntry entry = new FileEntry(); if (nextPos) { nextPosition(entry, true); } else { entry.x = mx; entry.y = my; } entry.file = fn; entry.name = name; entry.icon = icon; addIcon(entry); saveConfig(); update(); return entry; } catch (Exception e) { JFLog.log(e); } return null; } public static void runCmd(final JFileBrowser browser,final String cmd[]) { new Thread() { public void run() { try { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); if (browser != null) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { browser.refresh(); } }); } } catch (Exception e) { JFLog.log(e); } } }.start(); } public static int cntFiles(String fn) { File file = new File(fn); int cnt = 1; if (file.isDirectory()) { File files[] = file.listFiles(); for(int a=0;a<files.length;a++) { if (files[a].isDirectory()) { cnt += cntFiles(files[a].getAbsolutePath()); } else { cnt++; } } } return cnt; } private JFileIcon dragTarget; private void initDND() { panel.setTransferHandler(new TransferHandler() { public boolean canImport(TransferHandler.TransferSupport info) { // we only import Files if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { return false; } DropLocation dl = (DropLocation) info.getDropLocation(); Point pt = dl.getDropPoint(); JComponent c = (JComponent)panel.getComponentAt(pt); if (dragTarget != null) { dragTarget.setSelected(false); dragTarget = null; } if (c != null) { if (c instanceof JFileIcon) { JFileIcon fi = (JFileIcon)c; if (!fi.isTransparent()) { fi.setSelected(true); dragTarget = fi; } } } return true; } public boolean importData(TransferHandler.TransferSupport info) { if (!info.isDrop()) { return false; } // Check for file flavor if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { return false; } DropLocation dl = info.getDropLocation(); Point pt = dl.getDropPoint(); JComponent c = (JComponent)panel.getComponentAt(pt); if (dragTarget != null) { dragTarget.setSelected(false); dragTarget = null; } if (c != null) { if (c instanceof JFileIcon) { JFileIcon fi = (JFileIcon)c; if (!fi.isTransparent()) { fi.setSelected(true); dragTarget = fi; } } } String folder = path; if (dragTarget != null) { FileEntry entry = dragTarget.entry; if (entry.isLink) return false; if (entry.isDir) { folder += File.separatorChar; folder += entry.name; } } // Get the file(s) that are being dropped. Transferable t = info.getTransferable(); java.util.List<File> data; try { data = (java.util.List<File>) t.getTransferData(DataFlavor.javaFileListFlavor); } catch (Exception e) { return false; } // Perform the actual import. ArrayList<String> cmd = new ArrayList<String>(); boolean move = false; boolean copy = false; String fn; for(int a=0;a<data.size();a++) { switch (info.getDropAction()) { case COPY: if (move) return false; //Can that happen? copy = true; fn = ((File)data.get(a)).getAbsolutePath(); cmd.add(fn); break; case MOVE: if (copy) return false; //Can that happen? move = true; cmd.add(((File)data.get(a)).getAbsolutePath()); break; case LINK: return false; //BUG : not supported : ??? } } if (cmd.isEmpty()) return false; if (copy) { cmd.add(0, "jcp"); } else if (move) { cmd.add(0, "jmv"); } else { return false; } cmd.add(folder); runCmd(JFileBrowser.this, cmd.toArray(new String[0])); return true; } public int getSourceActions(JComponent c) { return COPY_OR_MOVE; } protected Transferable createTransferable(JComponent c) { FileEntry fefiles[] = getSelected(); final ArrayList<File> files = new ArrayList<File>(); for (int i = 0; i < fefiles.length; i++) { files.add(new File(fefiles[i].file)); } return new Transferable() { public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] {DataFlavor.javaFileListFlavor}; } public boolean isDataFlavorSupported(DataFlavor df) { return (df == DataFlavor.javaFileListFlavor); } public Object getTransferData(DataFlavor df) throws UnsupportedFlavorException, IOException { return files; } }; } protected void exportDone(JComponent source, Transferable data, int action) { clearSelection(); } }); } public void deleteFile(String filename) { for(int a=0;a<entries.size();a++) { if (entries.get(a).file.equals(filename)) { FileEntry entry = entries.get(a); File file = new File(filename); file.delete(); if (file.exists()) { //access denied if (file.isDirectory()) { JF.showError("Error", "Can not delete folder"); } else { JF.showError("Error", "Can not delete file"); } return; } panel.remove(entry.button); if (view == VIEW_DETAILS) { panel.remove(entry.details_date); panel.remove(entry.details_time); panel.remove(entry.details_size); } entries.remove(a); saveConfig(); update(); return; } } } public FileEntry[] getSelected() { ArrayList<FileEntry> list = new ArrayList<FileEntry>(); int cnt = panel.getComponentCount(); for(int a=0;a<cnt;a++) { JComponent c = (JComponent)panel.getComponent(a); if (!(c instanceof JFileIcon)) continue; JFileIcon b = (JFileIcon)c; if (b.isSelected()) { list.add(b.entry); } } return list.toArray(new FileEntry[0]); } public FileEntry[] getFolders() { ArrayList<FileEntry> list = new ArrayList<FileEntry>(); int cnt = panel.getComponentCount(); for(int a=0;a<cnt;a++) { JComponent c = (JComponent)panel.getComponent(a); if (!(c instanceof JFileIcon)) continue; JFileIcon b = (JFileIcon)c; if (b.entry.isDir) { list.add(b.entry); } } return list.toArray(new FileEntry[0]); } //also returns to org position from drag private void setSelectedTransparent(boolean undrag) { int cnt = panel.getComponentCount(); for(int a=0;a<cnt;a++) { JComponent c = (JComponent)panel.getComponent(a); if (!(c instanceof JFileIcon)) continue; JFileIcon b = (JFileIcon)c; if (b.isSelected()) { b.setTransparent(true); if (undrag) b.setLocation(b.dragX, b.dragY); } } } public void setSelectedTransparent() { setSelectedTransparent(false); } public void trash() { if (JF.isWindows()) { //TODO return; } else { FileEntry list[] = getSelected(); if ((list == null) || (list.length == 0)) return; ArrayList<String> cmd = new ArrayList<String>(); cmd.add("jmv"); for(int a=0;a<list.length;a++) cmd.add(list[a].file); cmd.add(JF.getUserPath() + "/.local/share/Trash"); runCmd(this, cmd.toArray(new String[0])); } } public void delete() { FileEntry list[] = getSelected(); if ((list == null) || (list.length == 0)) return; ArrayList<String> cmd = new ArrayList<String>(); cmd.add("jrm"); for(int a=0;a<list.length;a++) cmd.add(list[a].file); runCmd(this, cmd.toArray(new String[0])); } public int getCount() { return entries.size(); } public int getSelectedCount() { return getSelected().length; } public FileEntry[] getAll() { return entries.toArray(new FileEntry[0]); } public void selectFile(FileEntry entry) { clearSelection(); entry.button.setSelected(true); entry.button.repaint(); } public void setView(int newview) { view = newview; switch (view) { case VIEW_ICONS: ix = 48; iy = 48; bx = ix + 32; by = iy + 32; break; case VIEW_LIST: case VIEW_DETAILS: ix = 18; iy = 18; //bx,by calc later in listFiles() break; } } public void setShowHidden(boolean state) { showHidden = state; } public void setAutoArrange(boolean state) { autoArrange = state; } private boolean dragselection, dragicon; private int dragX, dragY; private int selX, selY; private boolean iconMoved; // private JComponent dragOverlay; public void mouseClicked(MouseEvent me) { JComponent c = (JComponent)me.getSource(); int mod = me.getModifiers(); if (c == panel) { if ((me.getButton() == me.BUTTON3) && (me.getClickCount() == 1)) { if (desktopMenu == null) return; mx = me.getX(); my = me.getY(); desktopMenu.show(panel, me.getX(), me.getY()); //TODO : make desktopMenu on top - how ??? } if ((mod & KeyEvent.CTRL_MASK) == 0) clearSelection(); return; } if (c instanceof JFileIcon) { JFileIcon b = (JFileIcon)c; switch (me.getClickCount()) { case 1: if ((mod & KeyEvent.CTRL_MASK) == 0) clearSelection(); b.setSelected(true); break; case 2: clearSelection(); openEntry(b.entry); break; } } } public void mousePressed(MouseEvent me) { int mod = me.getModifiers(); requestFocus(); dragicon = false; dragselection = false; JComponent c = (JComponent)me.getSource(); if (c instanceof JFileIcon) { JFileIcon b = (JFileIcon)c; if (!b.isSelected()) { if ((mod & KeyEvent.CTRL_MASK) == 0) clearSelection(); b.setSelected(true); } if (me.getButton() == MouseEvent.BUTTON3) { if (fileMenu != null) { mx = me.getX(); my = me.getY(); fileMenu.show(b, me.getX(), me.getY()); } return; } if (me.getButton() != MouseEvent.BUTTON1) return; dragicon = true; dragX = me.getXOnScreen(); dragY = me.getYOnScreen(); int cnt = panel.getComponentCount(); for(int a=0;a<cnt;a++) { c = (JComponent)panel.getComponent(a); if (!(c instanceof JFileIcon)) continue; b = (JFileIcon)c; if (!b.isSelected()) continue; b.dragX = b.getX(); b.dragY = b.getY(); } } else { if (me.getButton() != MouseEvent.BUTTON1) return; dragX = me.getX(); dragY = me.getY(); selX = dragX; selY = dragY; dragselection = true; } } public void mouseReleased(MouseEvent me) { if (iconMoved) { if (autoArrange) { arrangeByGrid(); } else { if (useScrolling) calcPanelSize(); } saveConfig(); iconMoved = false; /* if (dragOverlay != null) { panel.remove(dragOverlay); dragOverlay = null; }*/ } dragselection = false; dragicon = false; repaint(); } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { if (dragicon) { panel.getTransferHandler().exportAsDrag(panel, me, TransferHandler.MOVE); setSelectedTransparent(true); dragicon = false; repaint(); jbusClient.call("org.jflinux.jdesktop." + System.getenv("JID"), "show", ""); /* if (dragOverlay != null) { panel.remove(dragOverlay); dragOverlay = null; }*/ } } public void mouseDragged(MouseEvent me) { if (dragicon) { iconMoved = true; int x = me.getXOnScreen(); int y = me.getYOnScreen(); Point pt1 = null; if (useScrolling) { pt1 = scroll.getLocationOnScreen(); } else { pt1 = panel.getLocationOnScreen(); } Point pt2 = new Point(); pt2.x = pt1.x + getWidth(); pt2.y = pt1.y + getHeight(); if ((x < pt1.x) || (y < pt1.y) || (x > pt2.x) || (y > pt2.y) || (view != VIEW_ICONS) || (!desktopMode)) { panel.getTransferHandler().exportAsDrag(panel, me, TransferHandler.MOVE); setSelectedTransparent(true); dragicon = false; repaint(); jbusClient.call("org.jflinux.jdesktop." + System.getenv("JID"), "show", ""); /* if (dragOverlay != null) { panel.remove(dragOverlay); dragOverlay = null; }*/ return; } int dx = x - dragX; int dy = y - dragY; int cnt = panel.getComponentCount(); for(int a=0;a<cnt;a++) { JComponent c = (JComponent)panel.getComponent(a); if (!(c instanceof JFileIcon)) continue; JFileIcon b = (JFileIcon)c; if (!b.isSelected()) continue; FileEntry entry = b.entry; entry.x = b.dragX + dx; entry.y = b.dragY + dy; b.setLocation(entry.x, entry.y); panel.setComponentZOrder(b, 0); //or getComponentCount() } /* dragOverlay = new JComponent() {}; // panel.add(dragOverlay); panel.setComponentZOrder(dragOverlay, 0); dragOverlay.setBounds(0,0,getWidth(),getHeight());*/ } else if (dragselection) { selX = me.getX(); selY = me.getY(); selectIcons(); repaint(); } } public void mouseMoved(MouseEvent me) { } jfuseiso iso; jfusezip zip; private void openFile(String file) { //file = .iso or .zip if (mount != null) return; //can not open a file in a file (!recursive) String name; int idx = file.lastIndexOf("/"); if (idx == -1) { name = file; } else { name = file.substring(idx+1); } String mount = JF.getUserPath() + "/.fuse/" + name; String fullmount = mount; int cnt = 1; while (new File(fullmount).exists()) { fullmount = mount + "(" + cnt++ + ")"; } new File(fullmount).mkdirs(); final String args[] = new String[] {file, fullmount, "-f"}; if (file.toLowerCase().endsWith(".iso")) { iso = new jfuseiso(); if (!iso.auth(args, null)) { JF.showError("Error", "Failed to open file"); return; } new Thread() { public void run() { iso.start(args); } }.start(); } else if (file.toLowerCase().endsWith(".zip")) { zip = new jfusezip(); if (!zip.auth(args, null)) { JF.showError("Error", "Failed to open file"); return; } new Thread() { public void run() { zip.start(args); } }.start(); } else { JFLog.log("Error:Can not open:" + file); setPath(JF.getUserPath()); return; } this.mount = fullmount; JF.sleep(100); //wait for thread to start setPath(fullmount); } public void closeFile() { if (mount == null) return; execute(new String[] {"fusermount", "-u", mount}, true); new File(mount).delete(); mount = null; } private void update() { if (panel == null) return; //refresh not called yet repaint(); panel.repaint(); } //use clipboard or jdesktop public void cut() { FileEntry list[] = getSelected(); if ((list == null) || (list.length == 0)) return; String fs = "cut"; for(int a=0;a<list.length;a++) { fs += ":" + list[a].file; } fileClipboard.set(fs); setSelectedTransparent(); } public void copy() { FileEntry list[] = getSelected(); if ((list == null) || (list.length == 0)) return; String fs = "copy"; for(int a=0;a<list.length;a++) { fs += ":" + list[a].file; } fileClipboard.set(fs); } public void paste() { fileClipboard.get(); } public void paste(String fileSelection) { if (fileSelection == null) return; String f[] = fileSelection.split(":"); ArrayList<String> cmd = new ArrayList<String>(); if (f[0].equals("cut")) { //cut cmd.add("jmv"); } else if (f[0].equals("copy")) { //copy cmd.add("jcp"); } else { JFLog.log("Error:unknown clipboard operation=" + f[0]); } for(int a=1;a<f.length;a++) { cmd.add(f[a]); } cmd.add(path); runCmd(this, cmd.toArray(new String[0])); } public void close() { stopFolderListener(); } }
lgpl-3.0
simeshev/parabuild-ci
src/org/parabuild/ci/build/SystemVariableConfigurationManager.java
4001
/* * Parabuild CI licenses this file to You under the LGPL 2.1 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.gnu.org/licenses/lgpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.parabuild.ci.build; import net.sf.hibernate.Query; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.parabuild.ci.common.StringUtils; import org.parabuild.ci.configuration.BuilderConfigurationManager; import org.parabuild.ci.configuration.ConfigurationManager; import org.parabuild.ci.configuration.TransactionCallback; import org.parabuild.ci.object.AgentConfig; import org.parabuild.ci.object.ProjectBuild; import org.parabuild.ci.object.StartParameter; import org.parabuild.ci.object.StartParameterType; import org.parabuild.ci.project.ProjectManager; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class SystemVariableConfigurationManager { /** * @noinspection UNUSED_SYMBOL,UnusedDeclaration */ private static final Log LOG = LogFactory.getLog(SystemVariableConfigurationManager.class); // NOPMD private static final SystemVariableConfigurationManager instance = new SystemVariableConfigurationManager(); public static SystemVariableConfigurationManager getInstance() { return instance; } /** * Returns a map of objects {@link StartParameter} with variable name as a key. * * @param buildID * @param agentHostName * @return a map of objects {@link StartParameter} with variable name as a key. */ public Map getCommonVariableMap(final int buildID, final String agentHostName) { // Put parameters - order is important final ConfigurationManager cm = ConfigurationManager.getInstance(); // Get active build final int activeBuildID = cm.getActiveIDFromBuildID(buildID); final Map result = new LinkedHashMap(11); // First - system final List systemStartParameters = cm.getStartParameters(StartParameterType.SYSTEM, -1); addToMap(result, systemStartParameters); // Second - project final ProjectBuild projectBuild = ProjectManager.getInstance().getProjectBuild(activeBuildID); final int projectID = projectBuild.getProjectID(); final List projectStartParameters = cm.getStartParameters(StartParameterType.PROJECT, projectID); addToMap(result, projectStartParameters); // Third - agent if (!StringUtils.isBlank(agentHostName)) { final AgentConfig agentConfig = BuilderConfigurationManager.getInstance().findAgentByHost(agentHostName); if (agentConfig != null) { addToMap(result, cm.getStartParameters(StartParameterType.AGENT, agentConfig.getID())); } } return result; } private void addToMap(final Map parameters, final List systemParameters) { for (int i = 0; i < systemParameters.size(); i++) { final StartParameter startParameter = (StartParameter) systemParameters.get(i); parameters.put(startParameter.getName(), startParameter); } } public int getVariableCount(final byte variableType, final int variableOwner) { return ((Number) ConfigurationManager.runInHibernate(new TransactionCallback() { public Object runInTransaction() throws Exception { final Query q = session.createQuery( "select count(mrp) from StartParameter as mrp " + " where mrp.buildID = ? " + " and mrp.type = ?"); q.setInteger(0, variableOwner); q.setByte(1, variableType); q.setCacheable(true); return q.uniqueResult(); } })).intValue(); } }
lgpl-3.0
wingleess/EZOne-server
app/structure/Manufacture.scala
6798
package structure import play.api.db.DB import play.api.Play.current import anorm._ import anorm.SqlParser._ import spray.json._ import util.db._ /** * Project IntelliJ IDEA * Module structure * User: Gyuhyeon * Date: 2014. 1. 8. * Time: 오전 1:05 */ case class Manufacture (manufacture_srl:Pk[Int] = NotAssigned, manufacture_name:String, manufacture_type:String, manufacture_address:String, manufacture_phone:String, manufacture_charger:String, manufacture_mobile:String, manufacture_created:Int, manufacture_updated:Int) object Manufacture { val parser = { get[Pk[Int]]("manufacture_srl") ~ get[String]("manufacture_name") ~ get[String]("manufacture_type") ~ get[String]("manufacture_address") ~ get[String]("manufacture_phone") ~ get[String]("manufacture_charger") ~ get[String]("manufacture_mobile") ~ get[Int]("manufacture_created") ~ get[Int]("manufacture_updated") map { case manufacture_srl ~ manufacture_name ~ manufacture_type ~ manufacture_address ~ manufacture_phone ~ manufacture_charger ~ manufacture_mobile ~ manufacture_created ~ manufacture_updated => Manufacture(manufacture_srl, manufacture_name, manufacture_type, manufacture_address, manufacture_phone, manufacture_charger, manufacture_mobile, manufacture_created, manufacture_updated) } } def findAll(page:Int, count:Int, orderBy:String, orderType:String) = DB.withConnection { implicit connection => try { SQL("SELECT * from manufacture order by {orderBy} " + validateOrderType(orderType) + " limit {page}, {count}") .on("orderBy"->toParameterValue("manufacture_" + orderBy), "page"->getPageIndex(page, count), "count"->count).as(this.parser *) } catch { case e => null } } def findById(srl:Pk[Int]):Manufacture = DB.withConnection { implicit connection => try { SQL("SELECT * from manufacture where manufacture_srl = {srl};") .on("srl"->srl.get) .using(this.parser).single() } catch { case e=> null } } def findByOption(target:String, keyword:String, option:String):List[Manufacture] = DB.withConnection { implicit connection => try { val keywordType:String = target match { case "srl" => "Int" case "created" => "Int" case "updated" => "Int" case _ => "String" } val query = SQL("SELECT * from manufacture where " + target + " " + option + " {keyword}") if(keywordType == "String") query.on("keyword"->keyword).as(this.parser *) else if(keywordType == "Int") query.on("keyword"->keyword.toInt).as(this.parser *) else null } catch { case e => null } } def create(m:Manufacture):Manufacture = DB.withConnection { implicit connection => val insertRow = SQL("INSERT INTO manufacture(manufacture_name, manufacture_type, manufacture_address, manufacture_phone, manufacture_charger, manufacture_mobile, manufacture_created, manufacture_updated) " + "values ({name}, {type}, {address}, {phone}, {charger}, {mobile}, {created}, {updated}); ") .on("name"->m.manufacture_name, "type"->m.manufacture_type, "address"->m.manufacture_address, "phone"->m.manufacture_phone, "charger"->m.manufacture_charger, "mobile"->m.manufacture_mobile, "created"->m.manufacture_created, "updated"->m.manufacture_updated).executeInsert(scalar[Long].single).toInt findById(new Id(insertRow)) } def update(m:Manufacture):Manufacture = DB.withConnection { implicit connection => val updateRow = SQL("UPDATE manufacture set manufacture_name = {name}, " + "manufacture_type = {type}, " + "manufacture_address = {address}, " + "manufacture_phone = {phone}, " + "manufacture_charger = {charger}, " + "manufacture_mobile = {mobile}, " + "manufacture_updated = {updated} " + "where manufacture_srl = {id};") .on("name"->m.manufacture_name, "type"->m.manufacture_type, "address"->m.manufacture_address, "phone"->m.manufacture_phone, "charger"->m.manufacture_charger, "mobile"->m.manufacture_mobile, "updated"->m.manufacture_updated, "id"->m.manufacture_srl.get).executeUpdate() findById(m.manufacture_srl) } def delete(id:Pk[Int]):Manufacture = DB.withConnection { implicit connection => val row = findById(id) SQL("DELETE FROM manufacture " + "WHERE manufacture_srl = {srl};") .on("srl"->id.get) .execute() row } } object ManufactureFormatter extends DefaultJsonProtocol { implicit object ManufactureJsonFormat extends RootJsonFormat[Manufacture] { def write(m:Manufacture) = JsObject( "manufacture_srl" -> JsNumber(m.manufacture_srl.get), "manufacture_name" -> JsString(m.manufacture_name), "manufacture_type" -> JsString(m.manufacture_type), "manufacture_address" -> JsString(m.manufacture_address), "manufacture_phone" -> JsString(m.manufacture_phone), "manufacture_charger" -> JsString(m.manufacture_charger), "manufacture_mobile" -> JsString(m.manufacture_mobile), "manufacture_created" -> JsNumber(m.manufacture_created), "manufacture_updated" -> JsNumber(m.manufacture_updated) ) def read(v:JsValue) = { v.asJsObject.getFields("manufacture_srl", "manufacture_name", "manufacture_type", "manufacture_address", "manufacture_phone", "manufacture_charger", "manufacture_mobile", "manufacture_created", "manufacture_updated") match { case Seq(JsNumber(manufacture_srl), JsString(manufacture_name), JsString(manufacture_type), JsString(manufacture_address), JsString(manufacture_phone), JsString(manufacture_charger), JsString(manufacture_mobile), JsNumber(manufacture_created), JsNumber(manufacture_updated)) => new Manufacture(new Id(manufacture_srl.toInt), manufacture_name, manufacture_type, manufacture_address, manufacture_phone, manufacture_charger, manufacture_mobile, manufacture_created.toInt, manufacture_updated.toInt) } } } }
lgpl-3.0
kidaa/Awakening-Core3
bin/scripts/object/tangible/loot/quest/lance_nightsister_schematic.lua
2579
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --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 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 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_loot_quest_lance_nightsister_schematic = object_tangible_loot_quest_shared_lance_nightsister_schematic:new { templateType = LOOTSCHEMATIC, objectMenuComponent = {"cpp", "LootSchematicMenuComponent"}, attributeListComponent = "LootSchematicAttributeListComponent", requiredSkill = "crafting_weaponsmith_master", targetDraftSchematic = "object/draft_schematic/weapon/lance_nightsister.iff", targetUseCount = 5 } ObjectTemplates:addTemplate(object_tangible_loot_quest_lance_nightsister_schematic, "object/tangible/loot/quest/lance_nightsister_schematic.iff")
lgpl-3.0
magenta-aps/db-preservation-toolkit
dbptk-modules/dbptk-module-oracle/src/main/java/com/databasepreservation/modules/oracle/Oracle12cModuleFactory.java
6882
package com.databasepreservation.modules.oracle; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import com.databasepreservation.model.Reporter; import com.databasepreservation.model.exception.LicenseNotAcceptedException; import com.databasepreservation.model.exception.UnsupportedModuleException; import com.databasepreservation.model.modules.DatabaseExportModule; import com.databasepreservation.model.modules.DatabaseImportModule; import com.databasepreservation.model.modules.DatabaseModuleFactory; import com.databasepreservation.model.parameters.Parameter; import com.databasepreservation.model.parameters.Parameters; import com.databasepreservation.modules.oracle.in.Oracle12cJDBCImportModule; import com.databasepreservation.modules.oracle.out.Oracle12cJDBCExportModule; /** * @author Bruno Ferreira <bferreira@keep.pt> */ public class Oracle12cModuleFactory implements DatabaseModuleFactory { private static final String licenseURL = "http://www.oracle.com/technetwork/licenses/distribution-license-152002.html"; private static final Parameter serverName = new Parameter().shortName("s").longName("server-name") .description("the name (or IP address) of the Oracle server").hasArgument(true).setOptionalArgument(false) .required(true); private static final Parameter portNumber = new Parameter().shortName("pn").longName("port-number") .description("the server port number").hasArgument(true).setOptionalArgument(false).required(true); private static final Parameter database = new Parameter().shortName("db").longName("database") .description("the name of the database to use in the connection").hasArgument(true).setOptionalArgument(false) .required(true); private static final Parameter username = new Parameter().shortName("u").longName("username") .description("the name of the user to use in connection").hasArgument(true).setOptionalArgument(false) .required(true); private static final Parameter password = new Parameter().shortName("p").longName("password") .description("the password of the user to use in connection").hasArgument(true).setOptionalArgument(false) .required(true); private static final Parameter sourceSchema = new Parameter() .shortName("sc") .longName("source-schema") .hasArgument(true) .setOptionalArgument(false) .required(false) .description( "the name of the source schema to export to the Oracle database. A schema with this name must exist in" + " the Oracle database and it must be the default tablespace for the specified user. If omitted, the name of" + " the first schema will be used"); private static final Parameter acceptLicense = new Parameter().shortName("al").longName("accept-license") .description("declare that you accept OTN License Agreement, which is necessary to use this module") .hasArgument(false).valueIfSet("true").valueIfNotSet("false").required(false); private Reporter reporter; private Oracle12cModuleFactory() { } public Oracle12cModuleFactory(Reporter reporter) { this.reporter = reporter; } @Override public boolean producesImportModules() { return true; } @Override public boolean producesExportModules() { return true; } @Override public String getModuleName() { return "oracle"; } @Override public Map<String, Parameter> getAllParameters() { HashMap<String, Parameter> parameterHashMap = new HashMap<String, Parameter>(); parameterHashMap.put(serverName.longName(), serverName); parameterHashMap.put(database.longName(), database); parameterHashMap.put(username.longName(), username); parameterHashMap.put(password.longName(), password); parameterHashMap.put(portNumber.longName(), portNumber); parameterHashMap.put(acceptLicense.longName(), acceptLicense); parameterHashMap.put(sourceSchema.longName(), sourceSchema); return parameterHashMap; } @Override public Parameters getImportModuleParameters() throws UnsupportedModuleException { return new Parameters(Arrays.asList(serverName, database, username, password, portNumber, acceptLicense), null); } @Override public Parameters getExportModuleParameters() throws UnsupportedModuleException { return new Parameters(Arrays.asList(serverName, database, username, password, portNumber, acceptLicense, sourceSchema), null); } @Override public DatabaseImportModule buildImportModule(Map<Parameter, String> parameters) throws UnsupportedModuleException, LicenseNotAcceptedException { String pServerName = parameters.get(serverName); String pDatabase = parameters.get(database); String pUsername = parameters.get(username); String pPassword = parameters.get(password); boolean pAcceptLicense = Boolean.parseBoolean(parameters.get(acceptLicense)); if (!pAcceptLicense) { throw new LicenseNotAcceptedException(getLicenseText("--import-" + acceptLicense.longName())); } Integer pPortNumber = Integer.parseInt(parameters.get(portNumber)); reporter.importModuleParameters(getModuleName(), "server name", pServerName, "database", pDatabase, "username", pUsername, "password", reporter.MESSAGE_FILTERED, "port number", pPortNumber.toString()); return new Oracle12cJDBCImportModule(pServerName, pPortNumber, pDatabase, pUsername, pPassword); } @Override public DatabaseExportModule buildExportModule(Map<Parameter, String> parameters) throws UnsupportedModuleException, LicenseNotAcceptedException { String pServerName = parameters.get(serverName); String pDatabase = parameters.get(database); String pUsername = parameters.get(username); String pPassword = parameters.get(password); String pSourceSchema = parameters.get(sourceSchema); boolean pAcceptLicense = Boolean.parseBoolean(parameters.get(acceptLicense)); if (!pAcceptLicense) { throw new LicenseNotAcceptedException(getLicenseText("--export-" + acceptLicense.longName())); } Integer pPortNumber = Integer.parseInt(parameters.get(portNumber)); reporter.exportModuleParameters(getModuleName(), "server name", pServerName, "database", pDatabase, "username", pUsername, "password", reporter.MESSAGE_FILTERED, "port number", pPortNumber.toString(), "source schema", pSourceSchema); return new Oracle12cJDBCExportModule(pServerName, pPortNumber, pDatabase, pUsername, pPassword, pSourceSchema); } private String getLicenseText(String parameter) { return "Please agree to the Oracle Technology Network Development and Distribution License Terms before using this module.\n" + "The Oracle Technology Network Development and Distribution License Terms are available at\n" + licenseURL + "\nTo agree you must specify the additional parameter " + parameter + " in your command."; } }
lgpl-3.0
tvsonar/sonarlint-roslyn-analyzer
src/Tests/SonarAnalyzer.UnitTest/Rules/PublicFieldNameTest.cs
1245
/* * SonarAnalyzer for .NET * Copyright (C) 2015-2016 SonarSource SA * mailto:contact@sonarsource.com * * 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 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 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ using Microsoft.VisualStudio.TestTools.UnitTesting; using SonarAnalyzer.Rules.VisualBasic; namespace SonarAnalyzer.UnitTest.Rules { [TestClass] public class PublicFieldNameTest { [TestMethod] [TestCategory("Rule")] public void PublicFieldName() { Verifier.VerifyAnalyzer(@"TestCases\PublicFieldName.vb", new PublicFieldName()); } } }
lgpl-3.0
mikeyjk/tavernSimulator
Includes/boost/interprocess/sync/lock_options.hpp
1850
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTERPROCESS_LOCK_OPTIONS_HPP #define BOOST_INTERPROCESS_LOCK_OPTIONS_HPP #if defined(_MSC_VER) # pragma once #endif #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/detail/workaround.hpp> //!\file //!Describes the lock options with associated with interprocess_mutex lock constructors. namespace boost { namespace posix_time { class ptime; } namespace interprocess { //!Type to indicate to a mutex lock constructor that must not lock the mutex. struct defer_lock_type{}; //!Type to indicate to a mutex lock constructor that must try to lock the mutex. struct try_to_lock_type {}; //!Type to indicate to a mutex lock constructor that the mutex is already locked. struct accept_ownership_type{}; //!An object indicating that the locking //!must be deferred. static const defer_lock_type defer_lock = defer_lock_type(); //!An object indicating that a try_lock() //!operation must be executed. static const try_to_lock_type try_to_lock = try_to_lock_type(); //!An object indicating that the ownership of lockable //!object must be accepted by the new owner. static const accept_ownership_type accept_ownership = accept_ownership_type(); } // namespace interprocess { } // namespace boost{ #include <boost/interprocess/detail/config_end.hpp> #endif // BOOST_INTERPROCESS_LOCK_OPTIONS_HPP
lgpl-3.0
jakobharlan/avango
avango-gua/src/avango/gua/scenegraph/GeometryNode.cpp
1443
#include <avango/gua/scenegraph/GeometryNode.hpp> #include <avango/Base.h> #include <boost/bind.hpp> AV_FC_DEFINE_ABSTRACT(av::gua::GeometryNode); AV_FIELD_DEFINE(av::gua::SFGeometryNode); AV_FIELD_DEFINE(av::gua::MFGeometryNode); av::gua::GeometryNode::GeometryNode(std::shared_ptr< ::gua::node::GeometryNode> guanode) : Node(guanode), m_guaNode(std::dynamic_pointer_cast< ::gua::node::GeometryNode>(Node::getGuaNode())) { AV_FC_ADD_ADAPTOR_FIELD(ShadowMode, boost::bind(&GeometryNode::getShadowModeCB, this, _1), boost::bind(&GeometryNode::setShadowModeCB, this, _1)); } void av::gua::GeometryNode::initClass() { if (!isTypeInitialized()) { av::gua::Node::initClass(); AV_FC_INIT_ABSTRACT(av::gua::Node, av::gua::GeometryNode, true); SFGeometryNode::initClass("av::gua::SFGeometryNode", "av::Field"); MFGeometryNode::initClass("av::gua::MFGeometryNode", "av::Field"); //sClassTypeId.setDistributable(true); } } std::shared_ptr< ::gua::node::GeometryNode> av::gua::GeometryNode::getGuaNode() const { return m_guaNode; } void av::gua::GeometryNode::getShadowModeCB(const SFUInt::GetValueEvent& event) { *(event.getValuePtr()) = static_cast<unsigned>(m_guaNode->get_shadow_mode()); } void av::gua::GeometryNode::setShadowModeCB(const SFUInt::SetValueEvent& event) { m_guaNode->set_shadow_mode(static_cast< ::gua::ShadowMode>(event.getValue())); }
lgpl-3.0
Apeksha14/AngularAppExample
.history/server_20170501161949.js
1615
/* Scrape and Display (18.3.8) * (If you can do this, you should be set for your hw) * ================================================== */ // STUDENTS: // Please complete the routes with TODOs inside. // Your specific instructions lie there // Good luck! // Dependencies var express = require("express"); var bodyParser = require("body-parser"); var logger = require("morgan"); var mongoose = require("mongoose"); // Requiring our Note and Article models // Our scraping tools var request = require("request"); var cheerio = require("cheerio"); // Set mongoose to leverage built in JavaScript ES6 Promises mongoose.Promise = Promise; // Initialize Express var app = express(); // Use morgan and body parser with our app app.use(logger("dev")); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static("public")); app.get("/", function(req, res) { res.sendFile(__dirname + "/public/index.html"); }); app.post('/view1', function(req, res) { console.log(res.body.desc); res.end(); }); // Make public a static dir // Database configuration with mongoose //var uristring = process.env.MONGOLAB_URI || process.env.MONGODB_URI || process.env.MONGOHQ_URL || 'mongodb://heroku_z49hw4k5:jg8j247rul3ho8c8gb5qndited@ds111791.mlab.com:11791/heroku_z49hw4k5'; //var uristring = 'mongodb://heroku_z49hw4k5:jg8j247rul3ho8c8gb5qndited@ds111791.mlab.com:11791/heroku_z49hw4k5' //var uristring = 'mongodb://localhost/timesnowdb'; var PORT = process.env.PORT || 3000; // Listen on port 3000 app.listen(PORT, function() { console.log("App running on port 3000!"); });
unlicense
cksharma/codelibrary
java/src/experimental/LinkCutTreeLcaArray.java
2233
package experimental; public class LinkCutTreeLcaArray { static int[] left; static int[] right; static int[] parent; static void init(int n) { left = new int[n]; right = new int[n]; parent = new int[n]; } // Whether x is a root of a splay tree static boolean isRoot(int x) { return parent[x] == 0 || (left[parent[x]] != x && right[parent[x]] != x); } static void connect(int ch, int p, boolean leftChild) { if (leftChild) left[p] = ch; else right[p] = ch; if (ch != 0) parent[ch] = p; } static void rotate(int x) { int p = parent[x]; int g = parent[p]; boolean isRootP = isRoot(p); boolean leftChildX = (x == left[p]); connect(leftChildX ? right[x] : left[x], p, leftChildX); connect(p, x, !leftChildX); if (!isRootP) connect(x, g, p == left[g]); else parent[x] = g; } static void splay(int x) { while (!isRoot(x)) { int p = parent[x]; if (!isRoot(p)) rotate((x == left[p]) == (p == left[parent[p]]) ? p : x); rotate(x); } } // Makes node x the root of the virtual tree, and also x is the leftmost node in its splay tree static int expose(int x) { int last = 0; for (int y = x; y != 0; y = parent[y]) { splay(y); left[y] = last; last = y; } splay(x); return last; } public static int findRoot(int x) { expose(x); while (right[x] != 0) x = right[x]; return x; } // prerequisite: x is a root node, y is in another tree public static void link(int x, int y) { expose(x); if (right[x] != 0) throw new RuntimeException("error: x is not a root node"); parent[x] = y; } public static void cut(int x) { expose(x); if (right[x] == 0) throw new RuntimeException("error: x is a root node"); parent[right[x]] = 0; right[x] = 0; } public static int lca(int x, int y) { if (findRoot(x) != findRoot(y)) return 0; expose(x); return expose(y); } // Usage example public static void main(String[] args) { init(10); int n1 = 1; int n2 = 2; int n3 = 3; int n4 = 4; int n5 = 5; link(n1, n2); link(n3, n2); link(n4, n3); System.out.println(n2 == lca(n1, n4)); cut(n4); System.out.println(0 == lca(n1, n4)); link(n5, n3); System.out.println(n2 == lca(n1, n5)); } }
unlicense
diegopacheco/scala-playground
caliban-graphql-fun/src/main/resources/gateway/node_modules/graphql-extensions/dist/index.d.ts
3229
import { GraphQLSchema, GraphQLField, GraphQLFieldResolver, GraphQLResolveInfo, ExecutionArgs, DocumentNode, GraphQLError } from 'graphql'; import { Request } from 'apollo-server-env'; import { GraphQLResponse, GraphQLRequestContext } from 'apollo-server-types'; export { GraphQLResponse }; export declare type EndHandler = (...errors: Array<Error>) => void; export declare class GraphQLExtension<TContext = any> { requestDidStart?(o: { request: Pick<Request, 'url' | 'method' | 'headers'>; queryString?: string; parsedQuery?: DocumentNode; operationName?: string; variables?: { [key: string]: any; }; persistedQueryHit?: boolean; persistedQueryRegister?: boolean; context: TContext; requestContext: GraphQLRequestContext<TContext>; }): EndHandler | void; parsingDidStart?(o: { queryString: string; }): EndHandler | void; validationDidStart?(): EndHandler | void; executionDidStart?(o: { executionArgs: ExecutionArgs; }): EndHandler | void; didEncounterErrors?(errors: ReadonlyArray<GraphQLError>): void; willSendResponse?(o: { graphqlResponse: GraphQLResponse; context: TContext; }): void | { graphqlResponse: GraphQLResponse; context: TContext; }; willResolveField?(source: any, args: { [argName: string]: any; }, context: TContext, info: GraphQLResolveInfo): ((error: Error | null, result?: any) => void) | void; format?(): [string, any] | undefined; } export declare class GraphQLExtensionStack<TContext = any> { fieldResolver?: GraphQLFieldResolver<any, any>; private extensions; constructor(extensions: GraphQLExtension<TContext>[]); requestDidStart(o: { request: Pick<Request, 'url' | 'method' | 'headers'>; queryString?: string; parsedQuery?: DocumentNode; operationName?: string; variables?: { [key: string]: any; }; persistedQueryHit?: boolean; persistedQueryRegister?: boolean; context: TContext; extensions?: Record<string, any>; requestContext: GraphQLRequestContext<TContext>; }): EndHandler; parsingDidStart(o: { queryString: string; }): EndHandler; validationDidStart(): EndHandler; executionDidStart(o: { executionArgs: ExecutionArgs; }): EndHandler; didEncounterErrors(errors: ReadonlyArray<GraphQLError>): void; willSendResponse(o: { graphqlResponse: GraphQLResponse; context: TContext; }): { graphqlResponse: GraphQLResponse; context: TContext; }; willResolveField(source: any, args: { [argName: string]: any; }, context: TContext, info: GraphQLResolveInfo): (error: Error | null, result?: any) => void; format(): {}; private handleDidStart; } export declare function enableGraphQLExtensions(schema: GraphQLSchema & { _extensionsEnabled?: boolean; }): GraphQLSchema & { _extensionsEnabled?: boolean | undefined; }; export declare type FieldIteratorFn = (fieldDef: GraphQLField<any, any>, typeName: string, fieldName: string) => void; //# sourceMappingURL=index.d.ts.map
unlicense
LogMANOriginal/rss-bridge
caches/FileCache.php
2698
<?php /** * Cache with file system */ class FileCache implements CacheInterface { protected $path; protected $param; public function loadData(){ return unserialize(file_get_contents($this->getCacheFile())); } public function saveData($datas){ // Notice: We use plain serialize() here to reduce memory footprint on // large input data. $writeStream = file_put_contents($this->getCacheFile(), serialize($datas)); if($writeStream === false) { throw new \Exception("Cannot write the cache... Do you have the right permissions ?"); } return $this; } public function getTime(){ $cacheFile = $this->getCacheFile(); if(file_exists($cacheFile)) { return filemtime($cacheFile); } return false; } public function purgeCache($duration){ $cachePath = $this->getPath(); if(file_exists($cachePath)) { $cacheIterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($cachePath), RecursiveIteratorIterator::CHILD_FIRST ); foreach($cacheIterator as $cacheFile) { if(in_array($cacheFile->getBasename(), array('.', '..', '.gitkeep'))) continue; elseif($cacheFile->isFile()) { if(filemtime($cacheFile->getPathname()) < time() - $duration) unlink($cacheFile->getPathname()); } } } } /** * Set cache path * @return self */ public function setPath($path){ if(is_null($path) || !is_string($path)) { throw new \Exception('The given path is invalid!'); } $this->path = $path; // Make sure path ends with '/' or '\' $lastchar = substr($this->path, -1, 1); if($lastchar !== '/' && $lastchar !== '\\') $this->path .= '/'; if(!is_dir($this->path)) mkdir($this->path, 0755, true); return $this; } /** * Set HTTP GET parameters * @return self */ public function setParameters(array $param){ $this->param = array_map('strtolower', $param); return $this; } /** * Return cache path (and create if not exist) * @return string Cache path */ protected function getPath(){ if(is_null($this->path)) { throw new \Exception('Call "setPath" first!'); } return $this->path; } /** * Get the file name use for cache store * @return string Path to the file cache */ protected function getCacheFile(){ return $this->getPath() . $this->getCacheName(); } /** * Determines file name for store the cache * return string */ protected function getCacheName(){ if(is_null($this->param)) { throw new \Exception('Call "setParameters" first!'); } // Change character when making incompatible changes to prevent loading // errors due to incompatible file contents \|/ return hash('md5', http_build_query($this->param) . 'A') . '.cache'; } }
unlicense
M4573R/pc-code
solved/o-q/power-transmission/lightoj/power.cpp
2950
#include <algorithm> #include <cstdio> #include <cstring> using namespace std; #define MAXN 100 #define Neg(v) memset((v), -1, sizeof(v)) const int MAX_V = 2*MAXN + 2; const int MAX_E = MAX_V * (MAX_V - 1); const int INF = MAX_E * 1000 + 100; struct Edge { int v, c, f, o; Edge() {} Edge(int V, int C, int O) : v(V), c(C), f(0), o(O) {} }; template <typename ET> struct Graph { ET edges[MAX_E]; int next[MAX_E], adj[MAX_V]; int n, m; void init(int N) { n=N; m=0; Neg(adj); } void add(int u, ET e) { next[m] = adj[u], edges[m] = e, adj[u] = m++; } void bi_add(int u, int v, int c) { add(u, Edge(v, c, m + 1)); add(v, Edge(u, 0, m - 1)); } // Ford-Fulkerson int dist[MAX_V], q[MAX_V], src, snk; bool find_aug_paths() { Neg(dist); int qfront = -1, qback = 0; q[++qfront] = src; dist[src] = 0; while (qback <= qfront) { int u = q[qback++]; if (u == snk) return true; for (int i = adj[u]; i >= 0; i = next[i]) { Edge &e = edges[i]; if (dist[e.v] >= 0 || e.f >= e.c) continue; q[++qfront] = e.v; dist[e.v] = dist[u] + 1; } } return false; } int dfs(int u, int f, int d) { if (u == snk) return f; int ans = 0; for (int i = adj[u]; f > 0 && i >= 0; i = next[i]) { Edge &e = edges[i]; if (e.f >= e.c || dist[e.v] != d + 1) continue; int r = dfs(e.v, min(f, e.c - e.f), d + 1); if (r > 0) e.f += r, edges[e.o].f -= r, ans += r, f -= r; } return ans; } int mod_paths() { int ans = 0; for (int f = dfs(src, INF, 0); f > 0; f = dfs(src,INF, 0)) ans += f; return ans; } int max_flow(int a, int b) { src = a, snk = b; int total = 0; while (find_aug_paths()) total += mod_paths(); return total; } }; int N, M, B, D; Graph<Edge> g; int main() { int T; scanf("%d", &T); int ncase = 0; while (T--) { scanf("%d", &N); g.init(2*N + 2); for (int i = 0; i < N; ++i) { int C; scanf("%d", &C); g.bi_add(2*i, 2*i + 1, C); } scanf("%d", &M); while (M--) { int i, j, C; scanf("%d%d%d", &i, &j, &C); --i, --j; g.bi_add(2*i + 1, 2*j, C); } int src = 2*N, snk = 2*N + 1; scanf("%d%d", &B, &D); while (B--) { int idx; scanf("%d", &idx); --idx; g.bi_add(src, 2*idx, INF); } while (D--) { int idx; scanf("%d", &idx); --idx; g.bi_add(2*idx + 1, snk, INF); } printf("Case %d: %d\n", ++ncase, g.max_flow(src, snk)); } return 0; }
unlicense
TheDenys/.NET
Lucene.Net/src/core/Store/BufferedIndexOutput.cs
5047
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ using System; namespace Lucene.Net.Store { /// <summary>Base implementation class for buffered <see cref="IndexOutput" />. </summary> public abstract class BufferedIndexOutput:IndexOutput { internal const int BUFFER_SIZE = 16384; private byte[] buffer = new byte[BUFFER_SIZE]; private long bufferStart = 0; // position in file of buffer private int bufferPosition = 0; // position in buffer private bool isDisposed; /// <summary>Writes a single byte.</summary> /// <seealso cref="IndexInput.ReadByte()"> /// </seealso> public override void WriteByte(byte b) { if (bufferPosition >= BUFFER_SIZE) Flush(); buffer[bufferPosition++] = b; } /// <summary>Writes an array of bytes.</summary> /// <param name="b">the bytes to write /// </param> /// <param name="length">the number of bytes to write /// </param> /// <seealso cref="IndexInput.ReadBytes(byte[],int,int)"> /// </seealso> public override void WriteBytes(byte[] b, int offset, int length) { int bytesLeft = BUFFER_SIZE - bufferPosition; // is there enough space in the buffer? if (bytesLeft >= length) { // we add the data to the end of the buffer Array.Copy(b, offset, buffer, bufferPosition, length); bufferPosition += length; // if the buffer is full, flush it if (BUFFER_SIZE - bufferPosition == 0) Flush(); } else { // is data larger then buffer? if (length > BUFFER_SIZE) { // we flush the buffer if (bufferPosition > 0) Flush(); // and write data at once FlushBuffer(b, offset, length); bufferStart += length; } else { // we fill/flush the buffer (until the input is written) int pos = 0; // position in the input data int pieceLength; while (pos < length) { pieceLength = (length - pos < bytesLeft)?length - pos:bytesLeft; Array.Copy(b, pos + offset, buffer, bufferPosition, pieceLength); pos += pieceLength; bufferPosition += pieceLength; // if the buffer is full, flush it bytesLeft = BUFFER_SIZE - bufferPosition; if (bytesLeft == 0) { Flush(); bytesLeft = BUFFER_SIZE; } } } } } /// <summary>Forces any buffered output to be written. </summary> public override void Flush() { FlushBuffer(buffer, bufferPosition); bufferStart += bufferPosition; bufferPosition = 0; } /// <summary>Expert: implements buffer write. Writes bytes at the current position in /// the output. /// </summary> /// <param name="b">the bytes to write /// </param> /// <param name="len">the number of bytes to write /// </param> private void FlushBuffer(byte[] b, int len) { FlushBuffer(b, 0, len); } /// <summary>Expert: implements buffer write. Writes bytes at the current position in /// the output. /// </summary> /// <param name="b">the bytes to write /// </param> /// <param name="offset">the offset in the byte array /// </param> /// <param name="len">the number of bytes to write /// </param> public abstract void FlushBuffer(byte[] b, int offset, int len); /// <summary>Closes this stream to further operations. </summary> protected override void Dispose(bool disposing) { if (isDisposed) return; if (disposing) { Flush(); } isDisposed = true; } /// <summary>Returns the current position in this file, where the next write will /// occur. /// </summary> /// <seealso cref="Seek(long)"> /// </seealso> public override long FilePointer { get { return bufferStart + bufferPosition; } } /// <summary>Sets current position in this file, where the next write will occur.</summary> /// <seealso cref="FilePointer"> /// </seealso> public override void Seek(long pos) { Flush(); bufferStart = pos; } /// <summary>The number of bytes in the file. </summary> public abstract override long Length { get; } } }
unlicense
fathi-hindi/oneplace
vendor/magento/module-catalog-inventory/Model/Quote/Item/QuantityValidator.php
8970
<?php /** * Product inventory data validator * * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\CatalogInventory\Model\Quote\Item; use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\CatalogInventory\Api\StockStateInterface; class QuantityValidator { /** * @var QuantityValidator\Initializer\Option */ protected $optionInitializer; /** * @var QuantityValidator\Initializer\StockItem */ protected $stockItemInitializer; /** * @var StockRegistryInterface */ protected $stockRegistry; /** * @var StockStateInterface */ protected $stockState; /** * @param QuantityValidator\Initializer\Option $optionInitializer * @param QuantityValidator\Initializer\StockItem $stockItemInitializer * @param StockRegistryInterface $stockRegistry * @param StockStateInterface $stockState */ public function __construct( QuantityValidator\Initializer\Option $optionInitializer, QuantityValidator\Initializer\StockItem $stockItemInitializer, StockRegistryInterface $stockRegistry, StockStateInterface $stockState ) { $this->optionInitializer = $optionInitializer; $this->stockItemInitializer = $stockItemInitializer; $this->stockRegistry = $stockRegistry; $this->stockState = $stockState; } /** * Check product inventory data when quote item quantity declaring * * @param \Magento\Framework\Event\Observer $observer * * @return void * @throws \Magento\Framework\Exception\LocalizedException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function validate(\Magento\Framework\Event\Observer $observer) { /* @var $quoteItem \Magento\Quote\Model\Quote\Item */ $quoteItem = $observer->getEvent()->getItem(); if (!$quoteItem || !$quoteItem->getProductId() || !$quoteItem->getQuote() || $quoteItem->getQuote()->getIsSuperMode() ) { return; } $qty = $quoteItem->getQty(); /** @var \Magento\CatalogInventory\Model\Stock\Item $stockItem */ $stockItem = $this->stockRegistry->getStockItem( $quoteItem->getProduct()->getId(), $quoteItem->getProduct()->getStore()->getWebsiteId() ); /* @var $stockItem \Magento\CatalogInventory\Api\Data\StockItemInterface */ if (!$stockItem instanceof \Magento\CatalogInventory\Api\Data\StockItemInterface) { throw new \Magento\Framework\Exception\LocalizedException(__('The stock item for Product is not valid.')); } $parentStockItem = false; /** * Check if product in stock. For composite products check base (parent) item stock status */ if ($quoteItem->getParentItem()) { $product = $quoteItem->getParentItem()->getProduct(); $parentStockItem = $this->stockRegistry->getStockItem( $product->getId(), $product->getStore()->getWebsiteId() ); } if ($stockItem) { if (!$stockItem->getIsInStock() || $parentStockItem && !$parentStockItem->getIsInStock()) { $quoteItem->addErrorInfo( 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, __('This product is out of stock.') ); $quoteItem->getQuote()->addErrorInfo( 'stock', 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, __('Some of the products are out of stock.') ); return; } else { // Delete error from item and its quote, if it was set due to item out of stock $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY); } } /** * Check item for options */ if (($options = $quoteItem->getQtyOptions()) && $qty > 0) { $qty = $quoteItem->getProduct()->getTypeInstance()->prepareQuoteItemQty($qty, $quoteItem->getProduct()); $quoteItem->setData('qty', $qty); if ($stockItem) { $result = $this->stockState->checkQtyIncrements( $quoteItem->getProduct()->getId(), $qty, $quoteItem->getProduct()->getStore()->getWebsiteId() ); if ($result->getHasError()) { $quoteItem->addErrorInfo( 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY_INCREMENTS, $result->getMessage() ); $quoteItem->getQuote()->addErrorInfo( $result->getQuoteMessageIndex(), 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY_INCREMENTS, $result->getQuoteMessage() ); } else { // Delete error from item and its quote, if it was set due to qty problems $this->_removeErrorsFromQuoteAndItem( $quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY_INCREMENTS ); } } foreach ($options as $option) { $result = $this->optionInitializer->initialize($option, $quoteItem, $qty); if ($result->getHasError()) { $option->setHasError(true); $quoteItem->addErrorInfo( 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, $result->getMessage() ); $quoteItem->getQuote()->addErrorInfo( $result->getQuoteMessageIndex(), 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, $result->getQuoteMessage() ); } else { // Delete error from item and its quote, if it was set due to qty lack $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY); } } } else { $result = $this->stockItemInitializer->initialize($stockItem, $quoteItem, $qty); if ($result->getHasError()) { $quoteItem->addErrorInfo( 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, $result->getMessage() ); $quoteItem->getQuote()->addErrorInfo( $result->getQuoteMessageIndex(), 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, $result->getQuoteMessage() ); } else { // Delete error from item and its quote, if it was set due to qty lack $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY); } } } /** * Removes error statuses from quote and item, set by this observer * * @param \Magento\Quote\Model\Quote\Item $item * @param int $code * @return void */ protected function _removeErrorsFromQuoteAndItem($item, $code) { if ($item->getHasError()) { $params = ['origin' => 'cataloginventory', 'code' => $code]; $item->removeErrorInfosByParams($params); } $quote = $item->getQuote(); $quoteItems = $quote->getItemsCollection(); $canRemoveErrorFromQuote = true; foreach ($quoteItems as $quoteItem) { if ($quoteItem->getItemId() == $item->getItemId()) { continue; } $errorInfos = $quoteItem->getErrorInfos(); foreach ($errorInfos as $errorInfo) { if ($errorInfo['code'] == $code) { $canRemoveErrorFromQuote = false; break; } } if (!$canRemoveErrorFromQuote) { break; } } if ($quote->getHasError() && $canRemoveErrorFromQuote) { $params = ['origin' => 'cataloginventory', 'code' => $code]; $quote->removeErrorInfosByParams(null, $params); } } }
unlicense
maikodaraine/EnlightenmentUbuntu
bindings/ruby/ffi-efl/spec/ecore_input_spec.rb
615
#! /usr/bin/env ruby # -*- coding: UTF-8 -*- # require 'efl/ecore_input' # describe 'Efl::EcoreInput' do # before(:all) do EcoreInput = Efl::EcoreInput @init = EcoreInput.init end after(:all) do EcoreInput.shutdown end # it "should init" do EcoreInput.init.should == @init+1 EcoreInput.init.should == @init+2 EcoreInput.init.should == @init+3 end # it "should shutdown" do EcoreInput.shutdown.should == @init+2 EcoreInput.shutdown.should == @init+1 EcoreInput.shutdown.should == @init end # end
unlicense
uruba/ETS2MP-Companion
app/src/main/java/cz/uruba/ets2mpcompanion/constants/GoogleAnalytics.java
223
package cz.uruba.ets2mpcompanion.constants; public class GoogleAnalytics { public static final String EVENT_CATEGORY_REFRESH = "Refresh"; public static final String EVENT_CATEGORY_THEME_SWITCH = "Theme switch"; }
unlicense
fathi-hindi/oneplace
vendor/magento/module-shipping/Model/Shipment/ReturnShipment.php
4199
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Shipping\Model\Shipment; /** * @method \Magento\Shipping\Model\Shipment\Request setOrderShipment(\Magento\Sales\Model\Order\Shipment $orderShipment) * @method \Magento\Sales\Model\Order\Shipment getOrderShipment() * @method \Magento\Shipping\Model\Shipment\Request setShipperContactPersonName(string $value) * @method string getShipperContactPersonName() * @method \Magento\Shipping\Model\Shipment\Request setShipperContactPersonFirstName(string $value) * @method string getShipperContactPersonFirstName() * @method \Magento\Shipping\Model\Shipment\Request setShipperContactPersonLastName(string $value) * @method string getShipperContactPersonLastName() * @method \Magento\Shipping\Model\Shipment\Request setShipperContactCompanyName(string $value) * @method string getShipperContactCompanyName() * @method \Magento\Shipping\Model\Shipment\Request setShipperContactPhoneNumber(int $value) * @method int getShipperContactPhoneNumber() * @method \Magento\Shipping\Model\Shipment\Request setShipperAddressStreet(string $value) * @method string getShipperAddressStreet() * @method \Magento\Shipping\Model\Shipment\Request setShipperAddressStreet1(string $value) * @method string getShipperAddressStreet1() * @method \Magento\Shipping\Model\Shipment\Request setShipperAddressStreet2(string $value) * @method string getShipperAddressStreet2() * @method \Magento\Shipping\Model\Shipment\Request setShipperAddressCity(string $value) * @method string getShipperAddressCity() * @method \Magento\Shipping\Model\Shipment\Request setShipperAddressStateOrProvinceCode(string $value) * @method string getShipperAddressStateOrProvinceCode() * @method \Magento\Shipping\Model\Shipment\Request setShipperAddressPostalCode(int $value) * @method int getShipperAddressPostalCode() * @method \Magento\Shipping\Model\Shipment\Request setShipperAddressCountryCode(string $value) * @method string getShipperAddressCountryCode() * @method \Magento\Shipping\Model\Shipment\Request setRecipientContactPersonName(string $value) * @method string getRecipientContactPersonName() * @method \Magento\Shipping\Model\Shipment\Request setRecipientContactPersonFirstName(string $value) * @method string getRecipientContactPersonFirstName() * @method \Magento\Shipping\Model\Shipment\Request setRecipientContactPersonLastName(string $value) * @method string getRecipientContactPersonLastName() * @method \Magento\Shipping\Model\Shipment\Request setRecipientContactCompanyName(string $value) * @method string getRecipientContactCompanyName() * @method \Magento\Shipping\Model\Shipment\Request setRecipientContactPhoneNumber(int $value) * @method int getRecipientContactPhoneNumber() * @method \Magento\Shipping\Model\Shipment\Request setRecipientAddressStreet(string $value) * @method string getRecipientAddressStreet() * @method \Magento\Shipping\Model\Shipment\Request setRecipientAddressStreet1(string $value) * @method string getRecipientAddressStreet1() * @method \Magento\Shipping\Model\Shipment\Request setRecipientAddressStreet2(string $value) * @method string getRecipientAddressStreet2() * @method \Magento\Shipping\Model\Shipment\Request setRecipientAddressCity(string $value) * @method string getRecipientAddressCity() * @method \Magento\Shipping\Model\Shipment\Request setRecipientAddressStateOrProvinceCode(string $value) * @method string getRecipientAddressStateOrProvinceCode() * @method \Magento\Shipping\Model\Shipment\Request setRecipientAddressPostalCode(int $value) * @method int getRecipientAddressPostalCode() * @method \Magento\Shipping\Model\Shipment\Request setRecipientAddressCountryCode(string $value) * @method string getRecipientAddressCountryCode() * @method \Magento\Shipping\Model\Shipment\Request setShippingMethod(string $value) * @method string getShippingMethod() * @method \Magento\Shipping\Model\Shipment\Request setPackageWeight(float $value) * @method float getPackageWeight() * * @author Magento Core Team <core@magentocommerce.com> */ class ReturnShipment extends \Magento\Framework\DataObject { }
unlicense
devboy/Substance
src/Substance.Collections.Generic/System/Collections/Generic/ISortKeyCollection.cs
761
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { /// <summary> /// Defined on a generic collection that sorts its contents using an <see cref="IComparer{TKey}"/>. /// </summary> /// <typeparam name="TKey">The type of element sorted in the collection.</typeparam> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal interface ISortKeyCollection</*in*/ TKey> { /// <summary> /// Gets the comparer used to sort keys. /// </summary> IComparer<TKey> KeyComparer { get; } } }
unlicense
emoreno911/pwa-training-labs
cache-api-lab/05-404-page/service-worker.js
2226
/* Copyright 2016 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var filesToCache = [ '.', 'style/main.css', 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700', 'images/still_life-1600_large_2x.jpg', 'images/still_life-800_large_1x.jpg', 'images/still_life_small.jpg', 'images/still_life_medium.jpg', 'index.html', 'pages/offline.html', 'pages/404.html' ]; var staticCacheName = 'pages-cache-v1'; self.addEventListener('install', function(event) { console.log('Attempting to install service worker and cache static assets'); event.waitUntil( caches.open(staticCacheName) .then(function(cache) { return cache.addAll(filesToCache); }) ); }); self.addEventListener('fetch', function(event) { console.log('Fetch event for ', event.request.url); event.respondWith( caches.match(event.request).then(function(response) { if (response) { console.log('Found ', event.request.url, ' in cache'); return response; } console.log('Network request for ', event.request.url); return fetch(event.request).then(function(response) { if (response.status === 404) { return caches.match('pages/404.html'); } return caches.open(staticCacheName).then(function(cache) { if (event.request.url.indexOf('test') < 0) { cache.put(event.request.url, response.clone()); } return response; }); }); }).catch(function(error) { // TODO 6 - Respond with custom offline page }) ); }); // TODO 7 - delete unused caches })();
apache-2.0
OHDSI/RcppBoostCompute
inst/include/boost.new/compute/algorithm/copy.hpp
12773
//---------------------------------------------------------------------------// // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://kylelutz.github.com/compute for more information. //---------------------------------------------------------------------------// #ifndef BOOST_COMPUTE_ALGORITHM_COPY_HPP #define BOOST_COMPUTE_ALGORITHM_COPY_HPP #include <algorithm> #include <iterator> #include <boost/utility/enable_if.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/not.hpp> #include <boost/compute/buffer.hpp> #include <boost/compute/system.hpp> #include <boost/compute/command_queue.hpp> #include <boost/compute/async/future.hpp> #include <boost/compute/iterator/buffer_iterator.hpp> #include <boost/compute/detail/is_device_iterator.hpp> #include <boost/compute/detail/is_contiguous_iterator.hpp> #include <boost/compute/detail/iterator_range_size.hpp> #include <boost/compute/algorithm/detail/copy_to_host.hpp> #include <boost/compute/algorithm/detail/copy_on_device.hpp> #include <boost/compute/algorithm/detail/copy_to_device.hpp> namespace boost { namespace compute { namespace detail { namespace mpl = boost::mpl; // meta-function returning true if copy() between InputIterator and // OutputIterator can be implemented with clEnqueueCopyBuffer(). template<class InputIterator, class OutputIterator> struct can_copy_with_copy_buffer : mpl::and_< boost::is_same< InputIterator, buffer_iterator<typename InputIterator::value_type> >, boost::is_same< OutputIterator, buffer_iterator<typename OutputIterator::value_type> >, boost::is_same< typename InputIterator::value_type, typename OutputIterator::value_type > >::type {}; // host -> device template<class InputIterator, class OutputIterator> inline OutputIterator dispatch_copy(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue, typename boost::enable_if_c< !is_device_iterator<InputIterator>::value && is_device_iterator<OutputIterator>::value >::type* = 0) { if(is_contiguous_iterator<InputIterator>::value){ return copy_to_device(first, last, result, queue); } else { // for non-contiguous input we first copy the values to // a temporary std::vector and then copy from there typedef typename std::iterator_traits<InputIterator>::value_type T; std::vector<T> vector(first, last); return copy_to_device(vector.begin(), vector.end(), result, queue); } } // host -> device (async) template<class InputIterator, class OutputIterator> inline future<OutputIterator> dispatch_copy_async(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue, typename boost::enable_if_c< !is_device_iterator<InputIterator>::value && is_device_iterator<OutputIterator>::value >::type* = 0) { if(is_contiguous_iterator<InputIterator>::value){ return copy_to_device_async(first, last, result, queue); } else { BOOST_ASSERT(false && "copy_async() is not supported for non-contiguous iterators"); return future<OutputIterator>(); } } // device -> host template<class InputIterator, class OutputIterator> inline OutputIterator dispatch_copy(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue, typename boost::enable_if_c< is_device_iterator<InputIterator>::value && !is_device_iterator<OutputIterator>::value >::type* = 0) { if(is_contiguous_iterator<OutputIterator>::value){ return copy_to_host(first, last, result, queue); } else { // for non-contiguous input we first copy the values to // a temporary std::vector and then copy from there typedef typename std::iterator_traits<InputIterator>::value_type T; std::vector<T> vector(iterator_range_size(first, last)); copy_to_host(first, last, vector.begin(), queue); return std::copy(vector.begin(), vector.end(), result); } } // device -> host (async) template<class InputIterator, class OutputIterator> inline future<OutputIterator> dispatch_copy_async(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue, typename boost::enable_if_c< is_device_iterator<InputIterator>::value && !is_device_iterator<OutputIterator>::value >::type* = 0) { if(is_contiguous_iterator<OutputIterator>::value){ return copy_to_host_async(first, last, result, queue); } else { BOOST_ASSERT(false && "copy_async() is not supported for non-contiguous iterators"); return future<OutputIterator>(); } } // device -> device template<class InputIterator, class OutputIterator> inline OutputIterator dispatch_copy(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue, typename boost::enable_if< mpl::and_< is_device_iterator<InputIterator>, is_device_iterator<OutputIterator>, mpl::not_< can_copy_with_copy_buffer< InputIterator, OutputIterator > > > >::type* = 0) { return copy_on_device(first, last, result, queue); } // device -> device (specialization for buffer iterators) template<class InputIterator, class OutputIterator> inline OutputIterator dispatch_copy(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue, typename boost::enable_if< mpl::and_< is_device_iterator<InputIterator>, is_device_iterator<OutputIterator>, can_copy_with_copy_buffer< InputIterator, OutputIterator > > >::type* = 0) { typedef typename std::iterator_traits<InputIterator>::value_type value_type; typedef typename std::iterator_traits<InputIterator>::difference_type difference_type; difference_type n = std::distance(first, last); if(n < 1){ // nothing to copy return result; } queue.enqueue_copy_buffer(first.get_buffer(), result.get_buffer(), first.get_index() * sizeof(value_type), result.get_index() * sizeof(value_type), static_cast<size_t>(n) * sizeof(value_type)); return result + n; } // device -> device (async) template<class InputIterator, class OutputIterator> inline future<OutputIterator> dispatch_copy_async(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue, typename boost::enable_if< mpl::and_< is_device_iterator<InputIterator>, is_device_iterator<OutputIterator>, mpl::not_< can_copy_with_copy_buffer< InputIterator, OutputIterator > > > >::type* = 0) { return copy_on_device_async(first, last, result, queue); } // device -> device (async, specialization for buffer iterators) template<class InputIterator, class OutputIterator> inline future<OutputIterator> dispatch_copy_async(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue, typename boost::enable_if< mpl::and_< is_device_iterator<InputIterator>, is_device_iterator<OutputIterator>, can_copy_with_copy_buffer< InputIterator, OutputIterator > > >::type* = 0) { typedef typename std::iterator_traits<InputIterator>::value_type value_type; typedef typename std::iterator_traits<InputIterator>::difference_type difference_type; difference_type n = std::distance(first, last); if(n < 1){ // nothing to copy return make_future(result, event()); } event event_ = queue.enqueue_copy_buffer( first.get_buffer(), result.get_buffer(), first.get_index() * sizeof(value_type), result.get_index() * sizeof(value_type), static_cast<size_t>(n) * sizeof(value_type) ); return make_future(result + n, event_); } // host -> host template<class InputIterator, class OutputIterator> inline OutputIterator dispatch_copy(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue, typename boost::enable_if_c< !is_device_iterator<InputIterator>::value && !is_device_iterator<OutputIterator>::value >::type* = 0) { (void) queue; return std::copy(first, last, result); } } // end detail namespace /// Copies the values in the range [\p first, \p last) to the range /// beginning at \p result. /// /// The generic copy() function can be used for a variety of data /// transfer tasks and provides a standard interface to the following /// OpenCL functions: /// /// \li \c clEnqueueReadBuffer() /// \li \c clEnqueueWriteBuffer() /// \li \c clEnqueueCopyBuffer() /// /// Unlike the aforementioned OpenCL functions, copy() will also work /// with non-contiguous data-structures (e.g. \c std::list<T>) as /// well as with "fancy" iterators (e.g. transform_iterator). /// /// \param first first element in the range to copy /// \param last last element in the range to copy /// \param result first element in the result range /// \param queue command queue to perform the operation /// /// \return \c OutputIterator to the end of the result range /// /// For example, to copy an array of \c int values on the host to a vector on /// the device: /// \code /// // array on the host /// int data[] = { 1, 2, 3, 4 }; /// /// // vector on the device /// boost::compute::vector<int> vec(4, context); /// /// // copy values to the device vector /// boost::compute::copy(data, data + 4, vec.begin(), queue); /// \endcode /// /// The copy algorithm can also be used with standard containers such as /// \c std::vector<T>: /// \code /// std::vector<int> host_vector = ... /// boost::compute::vector<int> device_vector = ... /// /// // copy from the host to the device /// boost::compute::copy( /// host_vector.begin(), host_vector.end(), device_vector.begin(), queue /// ); /// /// // copy from the device to the host /// boost::compute::copy( /// device_vector.begin(), device_vector.end(), host_vector.begin(), queue /// ); /// \endcode /// /// \see copy_n(), copy_if(), copy_async() template<class InputIterator, class OutputIterator> inline OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue = system::default_queue()) { return detail::dispatch_copy(first, last, result, queue); } /// Copies the values in the range [\p first, \p last) to the range /// beginning at \p result. The copy is performed asynchronously. /// /// \see copy() template<class InputIterator, class OutputIterator> inline future<OutputIterator> copy_async(InputIterator first, InputIterator last, OutputIterator result, command_queue &queue = system::default_queue()) { return detail::dispatch_copy_async(first, last, result, queue); } } // end compute namespace } // end boost namespace #endif // BOOST_COMPUTE_ALGORITHM_COPY_HPP
apache-2.0
jtransc/jtransc
jtransc-rt/src/java/math/MathContext.java
9324
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.math; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.io.StreamCorruptedException; /** * Immutable objects describing settings such as rounding mode and digit * precision for the numerical operations provided by class {@link BigDecimal}. */ public final class MathContext implements Serializable { /** * A {@code MathContext} which corresponds to the <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE 754</a> quadruple * decimal precision format: 34 digit precision and * {@link RoundingMode#HALF_EVEN} rounding. */ public static final MathContext DECIMAL128 = new MathContext(34, RoundingMode.HALF_EVEN); /** * A {@code MathContext} which corresponds to the <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE 754</a> single decimal * precision format: 7 digit precision and {@link RoundingMode#HALF_EVEN} * rounding. */ public static final MathContext DECIMAL32 = new MathContext(7, RoundingMode.HALF_EVEN); /** * A {@code MathContext} which corresponds to the <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE 754</a> double decimal * precision format: 16 digit precision and {@link RoundingMode#HALF_EVEN} * rounding. */ public static final MathContext DECIMAL64 = new MathContext(16, RoundingMode.HALF_EVEN); /** * A {@code MathContext} for unlimited precision with * {@link RoundingMode#HALF_UP} rounding. */ public static final MathContext UNLIMITED = new MathContext(0, RoundingMode.HALF_UP); /** * The number of digits to be used for an operation; results are rounded to * this precision. */ private final int precision; /** * A {@code RoundingMode} object which specifies the algorithm to be used * for rounding. */ private final RoundingMode roundingMode; /** * Constructs a new {@code MathContext} with the specified precision and * with the rounding mode {@link RoundingMode#HALF_UP HALF_UP}. If the * precision passed is zero, then this implies that the computations have to * be performed exact, the rounding mode in this case is irrelevant. * * @param precision * the precision for the new {@code MathContext}. * @throws IllegalArgumentException * if {@code precision < 0}. */ public MathContext(int precision) { this(precision, RoundingMode.HALF_UP); } /** * Constructs a new {@code MathContext} with the specified precision and * with the specified rounding mode. If the precision passed is zero, then * this implies that the computations have to be performed exact, the * rounding mode in this case is irrelevant. * * @param precision * the precision for the new {@code MathContext}. * @param roundingMode * the rounding mode for the new {@code MathContext}. * @throws IllegalArgumentException * if {@code precision < 0}. * @throws NullPointerException * if {@code roundingMode} is {@code null}. */ public MathContext(int precision, RoundingMode roundingMode) { this.precision = precision; this.roundingMode = roundingMode; checkValid(); } /** * Constructs a new {@code MathContext} from a string. The string has to * specify the precision and the rounding mode to be used and has to follow * the following syntax: "precision=&lt;precision&gt; roundingMode=&lt;roundingMode&gt;" * This is the same form as the one returned by the {@link #toString} * method. * * @throws IllegalArgumentException * if the string is not in the correct format or if the * precision specified is < 0. */ public MathContext(String s) { int precisionLength = "precision=".length(); int roundingModeLength = "roundingMode=".length(); int spaceIndex; if (!s.startsWith("precision=") || (spaceIndex = s.indexOf(' ', precisionLength)) == -1) { throw invalidMathContext("Missing precision", s); } String precisionString = s.substring(precisionLength, spaceIndex); try { this.precision = Integer.parseInt(precisionString); } catch (NumberFormatException nfe) { throw invalidMathContext("Bad precision", s); } int roundingModeStart = spaceIndex + 1; if (!s.regionMatches(roundingModeStart, "roundingMode=", 0, roundingModeLength)) { throw invalidMathContext("Missing rounding mode", s); } roundingModeStart += roundingModeLength; this.roundingMode = RoundingMode.valueOf(s.substring(roundingModeStart)); checkValid(); } private IllegalArgumentException invalidMathContext(String reason, String s) { throw new IllegalArgumentException(reason + ": " + s); } private void checkValid() { if (precision < 0) { throw new IllegalArgumentException("Negative precision: " + precision); } if (roundingMode == null) { throw new NullPointerException("roundingMode == null"); } } /** * Returns the precision. The precision is the number of digits used for an * operation. Results are rounded to this precision. The precision is * guaranteed to be non negative. If the precision is zero, then the * computations have to be performed exact, results are not rounded in this * case. * * @return the precision. */ public int getPrecision() { return precision; } /** * Returns the rounding mode. The rounding mode is the strategy to be used * to round results. * <p> * The rounding mode is one of * {@link RoundingMode#UP}, * {@link RoundingMode#DOWN}, * {@link RoundingMode#CEILING}, * {@link RoundingMode#FLOOR}, * {@link RoundingMode#HALF_UP}, * {@link RoundingMode#HALF_DOWN}, * {@link RoundingMode#HALF_EVEN}, or * {@link RoundingMode#UNNECESSARY}. * * @return the rounding mode. */ public RoundingMode getRoundingMode() { return roundingMode; } /** * Returns true if x is a {@code MathContext} with the same precision * setting and the same rounding mode as this {@code MathContext} instance. * * @param x * object to be compared. * @return {@code true} if this {@code MathContext} instance is equal to the * {@code x} argument; {@code false} otherwise. */ @Override public boolean equals(Object x) { return ((x instanceof MathContext) && (((MathContext) x).getPrecision() == precision) && (((MathContext) x) .getRoundingMode() == roundingMode)); } /** * Returns the hash code for this {@code MathContext} instance. * * @return the hash code for this {@code MathContext}. */ @Override public int hashCode() { // Make place for the necessary bits to represent 8 rounding modes return ((precision << 3) | roundingMode.ordinal()); } /** * Returns the string representation for this {@code MathContext} instance. * The string has the form * {@code * "precision=<precision> roundingMode=<roundingMode>" * } where {@code <precision>} is an integer describing the number * of digits used for operations and {@code <roundingMode>} is the * string representation of the rounding mode. * * @return a string representation for this {@code MathContext} instance */ @Override public String toString() { return "precision=" + precision + " roundingMode=" + roundingMode; } /** * Makes checks upon deserialization of a {@code MathContext} instance. * Checks whether {@code precision >= 0} and {@code roundingMode != null} * * @throws StreamCorruptedException * if {@code precision < 0} * @throws StreamCorruptedException * if {@code roundingMode == null} */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); try { checkValid(); } catch (Exception ex) { throw new StreamCorruptedException(ex.getMessage()); } } }
apache-2.0
dzxdzx1987/GoogleCharts
GoogleChartsSource/com/google/visualization/datasource/query/scalarfunction/Sum.java
3856
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.visualization.datasource.query.scalarfunction; import com.google.visualization.datasource.base.InvalidQueryException; import com.google.visualization.datasource.datatable.value.NumberValue; import com.google.visualization.datasource.datatable.value.Value; import com.google.visualization.datasource.datatable.value.ValueType; import java.util.List; /** * The binary scalar function sum(). * Returns the sum of two number values. * * @author Liron L. */ public class Sum implements ScalarFunction { /** * The name of this function. */ private static final String FUNCTION_NAME = "sum"; /** * A singleton instance of this class. */ private static final Sum INSTANCE = new Sum(); /** * A private constructor, to prevent instantiation other than by the singleton. */ private Sum() {} /** * Returns the singleton instance of this class. * * @return The singleton instance of this class. */ public static Sum getInstance() { return INSTANCE; } /** * {@inheritDoc} */ public String getFunctionName() { return FUNCTION_NAME; } /** * Executes the scalar function sum() on the given values. Returns the sum of * the given values. All values are number values. * The method does not validate the parameters, the user must check the * parameters before calling this method. * * @param values A list of values on which the scalar function is performed. * * @return Value with the sum of all given values, or number null value if one * of the values is null. */ public Value evaluate(List<Value> values) { if (values.get(0).isNull() || values.get(1).isNull()) { return NumberValue.getNullValue(); } double sum = ((NumberValue) values.get(0)).getValue() + ((NumberValue) values.get(1)).getValue(); return new NumberValue(sum); } /** * Returns the return type of the function. In this case, NUMBER. The method * does not validate the parameters, the user must check the parameters * before calling this method. * * @param types A list of the types of the scalar function parameters. * * @return The type of the returned value: Number. */ public ValueType getReturnType(List<ValueType> types) { return ValueType.NUMBER; } /** * Validates that all function parameters are of type NUMBER, and that there * are exactly 2 parameters. Throws a ScalarFunctionException otherwise. * * @param types A list of parameter types. * * @throws InvalidQueryException Thrown if the parameters are invalid. */ public void validateParameters(List<ValueType> types) throws InvalidQueryException { if (types.size() != 2) { throw new InvalidQueryException("The function " + FUNCTION_NAME + " requires 2 parmaeters "); } for (ValueType type : types) { if (type != ValueType.NUMBER) { throw new InvalidQueryException("Can't perform the function " + FUNCTION_NAME + " on values that are not numbers"); } } } /** * {@inheritDoc} */ public String toQueryString(List<String> argumentsQueryStrings) { return "(" + argumentsQueryStrings.get(0) + " + " + argumentsQueryStrings.get(1) + ")"; } }
apache-2.0
mfelgamal/zeppelin
zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/InterpreterFactoryTest.java
7328
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.zeppelin.interpreter; import java.io.*; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.NullArgumentException; import org.apache.zeppelin.conf.ZeppelinConfiguration; import org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars; import org.apache.zeppelin.dep.Dependency; import org.apache.zeppelin.dep.DependencyResolver; import org.apache.zeppelin.interpreter.mock.MockInterpreter1; import org.apache.zeppelin.interpreter.mock.MockInterpreter2; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sonatype.aether.RepositoryException; import static org.junit.Assert.*; public class InterpreterFactoryTest { private InterpreterFactory factory; private File tmpDir; private ZeppelinConfiguration conf; private InterpreterContext context; private DependencyResolver depResolver; @Before public void setUp() throws Exception { tmpDir = new File(System.getProperty("java.io.tmpdir")+"/ZeppelinLTest_"+System.currentTimeMillis()); tmpDir.mkdirs(); new File(tmpDir, "conf").mkdirs(); MockInterpreter1.register("mock1", "org.apache.zeppelin.interpreter.mock.MockInterpreter1"); MockInterpreter2.register("mock2", "org.apache.zeppelin.interpreter.mock.MockInterpreter2"); System.setProperty(ConfVars.ZEPPELIN_HOME.getVarName(), tmpDir.getAbsolutePath()); System.setProperty(ConfVars.ZEPPELIN_INTERPRETERS.getVarName(), "org.apache.zeppelin.interpreter.mock.MockInterpreter1,org.apache.zeppelin.interpreter.mock.MockInterpreter2"); conf = new ZeppelinConfiguration(); depResolver = new DependencyResolver(tmpDir.getAbsolutePath() + "/local-repo"); factory = new InterpreterFactory(conf, new InterpreterOption(false), null, null, null, depResolver); context = new InterpreterContext("note", "id", "title", "text", null, null, null, null, null, null, null); } @After public void tearDown() throws Exception { FileUtils.deleteDirectory(tmpDir); } @Test public void testBasic() { List<InterpreterSetting> all = factory.get(); InterpreterSetting mock1Setting = null; for (InterpreterSetting setting : all) { if (setting.getName().equals("mock1")) { mock1Setting = setting; break; } } // mock1Setting = factory.createNewSetting("mock11", "mock1", new ArrayList<Dependency>(), new InterpreterOption(false), new Properties()); InterpreterGroup interpreterGroup = mock1Setting.getInterpreterGroup("sharedProcess"); factory.createInterpretersForNote(mock1Setting, "sharedProcess", "session"); // get interpreter assertNotNull("get Interpreter", interpreterGroup.get("session").get(0)); // try to get unavailable interpreter assertNull(factory.get("unknown")); // restart interpreter factory.restart(mock1Setting.getId()); assertNull(mock1Setting.getInterpreterGroup("sharedProcess").get("session")); } @Test public void testFactoryDefaultList() throws IOException, RepositoryException { // get default settings List<String> all = factory.getDefaultInterpreterSettingList(); assertTrue(factory.getRegisteredInterpreterList().size() >= all.size()); } @Test public void testExceptions() throws InterpreterException, IOException, RepositoryException { List<String> all = factory.getDefaultInterpreterSettingList(); // add setting with null option & properties expected nullArgumentException.class try { factory.add("mock2", new ArrayList<InterpreterInfo>(), new LinkedList<Dependency>(), new InterpreterOption(false), new Properties(), ""); } catch(NullArgumentException e) { assertEquals("Test null option" , e.getMessage(),new NullArgumentException("option").getMessage()); } try { factory.add("mock2", new ArrayList<InterpreterInfo>(), new LinkedList<Dependency>(), new InterpreterOption(false), new Properties(), ""); } catch (NullArgumentException e){ assertEquals("Test null properties" , e.getMessage(),new NullArgumentException("properties").getMessage()); } } @Test public void testSaveLoad() throws IOException, RepositoryException { // interpreter settings int numInterpreters = factory.get().size(); // check if file saved assertTrue(new File(conf.getInterpreterSettingPath()).exists()); factory.createNewSetting("new-mock1", "mock1", new LinkedList<Dependency>(), new InterpreterOption(false), new Properties()); assertEquals(numInterpreters + 1, factory.get().size()); InterpreterFactory factory2 = new InterpreterFactory(conf, null, null, null, depResolver); assertEquals(numInterpreters + 1, factory2.get().size()); } @Test public void testInterpreterAliases() throws IOException, RepositoryException { factory = new InterpreterFactory(conf, null, null, null, depResolver); final InterpreterInfo info1 = new InterpreterInfo("className1", "name1", true); final InterpreterInfo info2 = new InterpreterInfo("className2", "name1", true); factory.add("group1", new ArrayList<InterpreterInfo>(){{ add(info1); }}, new ArrayList<Dependency>(), new InterpreterOption(true), new Properties(), "/path1"); factory.add("group2", new ArrayList<InterpreterInfo>(){{ add(info2); }}, new ArrayList<Dependency>(), new InterpreterOption(true), new Properties(), "/path2"); final InterpreterSetting setting1 = factory.createNewSetting("test-group1", "group1", new ArrayList<Dependency>(), new InterpreterOption(true), new Properties()); final InterpreterSetting setting2 = factory.createNewSetting("test-group2", "group1", new ArrayList<Dependency>(), new InterpreterOption(true), new Properties()); factory.setInterpreters("note", new ArrayList<String>() {{ add(setting1.getId()); add(setting2.getId()); }}); assertEquals("className1", factory.getInterpreter("note", "test-group1").getClassName()); assertEquals("className1", factory.getInterpreter("note", "group1").getClassName()); } @Test public void testInvalidInterpreterSettingName() { try { factory.createNewSetting("new.mock1", "mock1", new LinkedList<Dependency>(), new InterpreterOption(false), new Properties()); fail("expect fail because of invalid InterpreterSetting Name"); } catch (IOException e) { assertEquals("'.' is invalid for InterpreterSetting name.", e.getMessage()); } } }
apache-2.0
jay-hodgson/SynapseWebClient
src/test/java/org/sagebionetworks/web/unitclient/widget/entity/SynapseSuggestOracleTest.java
4282
package org.sagebionetworks.web.unitclient.widget.entity; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.LinkedList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.sagebionetworks.repo.model.UserGroupHeader; import org.sagebionetworks.repo.model.principal.TypeFilter; import org.sagebionetworks.web.client.GWTTimer; import org.sagebionetworks.web.client.widget.search.SynapseSuggestBox; import org.sagebionetworks.web.client.widget.search.SynapseSuggestOracle; import org.sagebionetworks.web.client.widget.search.SynapseSuggestionBundle; import org.sagebionetworks.web.client.widget.search.UserGroupSuggestion; import org.sagebionetworks.web.client.widget.search.UserGroupSuggestionProvider; import org.sagebionetworks.web.test.helper.AsyncMockStubber; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.SuggestOracle; import com.google.gwt.user.client.ui.SuggestOracle.Response; public class SynapseSuggestOracleTest { SynapseSuggestBox mockSuggestBox; UserGroupSuggestionProvider mockSuggestionProvider; SynapseSuggestOracle presenter; UserGroupSuggestion mockSuggestion; SuggestOracle.Callback mockCallback; SuggestOracle.Request mockRequest; GWTTimer mockTimer; int pageSize = 10; int offset = 0; SynapseSuggestionBundle suggBundle; String query = "test"; public final String USERNAME = "username"; @Before public void setup() { mockSuggestBox = mock(SynapseSuggestBox.class); mockSuggestionProvider = mock(UserGroupSuggestionProvider.class); mockSuggestion = mock(UserGroupSuggestion.class); mockCallback = mock(SuggestOracle.Callback.class); mockRequest = mock(SuggestOracle.Request.class); when(mockRequest.getQuery()).thenReturn(query); mockTimer = mock(GWTTimer.class); presenter = new SynapseSuggestOracle(mockTimer); presenter.configure(mockSuggestBox, pageSize, mockSuggestionProvider); presenter.requestSuggestions(mockRequest, mockCallback); List<UserGroupSuggestion> suggList = new LinkedList<>(); for (int i = 0; i < pageSize; i++) { suggList.add(mockSuggestion); } int totalResults = 42; suggBundle = new SynapseSuggestionBundle(suggList, totalResults); } @Test public void testConfigure() { presenter.configure(mockSuggestBox, pageSize, mockSuggestionProvider); mockTimer.configure(any(Runnable.class)); } @Test public void testGetSuggestionsWithoutExactMatch() { when(mockSuggestBox.getText()).thenReturn(USERNAME); UserGroupHeader mockHeader = mock(UserGroupHeader.class); when(mockHeader.getUserName()).thenReturn("notUsername"); when(mockSuggestion.getHeader()).thenReturn(mockHeader); AsyncMockStubber.callSuccessWith(suggBundle).when(mockSuggestionProvider).getSuggestions(any(TypeFilter.class), anyInt(), anyInt(), anyInt(), anyString(), any(AsyncCallback.class)); presenter.getSuggestions(offset); verify(mockSuggestBox).showLoading(); verify(mockSuggestBox).setSelectedSuggestion((UserGroupSuggestion) isNull()); verify(mockSuggestionProvider).getSuggestions(eq(TypeFilter.ALL), eq(offset), eq(pageSize), anyInt(), eq(query), any(AsyncCallback.class)); verify(mockSuggestBox).hideLoading(); verify(mockSuggestBox).updateFieldStateForSuggestions((int) suggBundle.getTotalNumberOfResults(), offset); verify(mockCallback).onSuggestionsReady(eq(mockRequest), any(Response.class)); } @Test public void testGetSuggestionsFailure() { Exception caught = new Exception("an error message"); AsyncMockStubber.callFailureWith(caught).when(mockSuggestionProvider).getSuggestions(any(TypeFilter.class), anyInt(), anyInt(), anyInt(), anyString(), any(AsyncCallback.class)); presenter.getSuggestions(offset); verify(mockSuggestBox).showLoading(); verify(mockSuggestionProvider).getSuggestions(eq(TypeFilter.ALL), eq(offset), eq(pageSize), anyInt(), eq(query), any(AsyncCallback.class)); verify(mockSuggestBox).hideLoading(); verify(mockSuggestBox).handleOracleException(caught); } }
apache-2.0
ashigeru/asakusafw
core-project/asakusa-runtime/src/test/java/com/asakusafw/runtime/stage/input/TemporaryInputFormatTest.java
7945
/** * Copyright 2011-2019 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.runtime.stage.input; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.asakusafw.runtime.directio.hadoop.BlockInfo; import com.asakusafw.runtime.directio.hadoop.BlockMap; import com.asakusafw.runtime.io.ModelOutput; import com.asakusafw.runtime.stage.temporary.TemporaryFile; import com.asakusafw.runtime.stage.temporary.TemporaryStorage; import com.asakusafw.runtime.util.hadoop.ConfigurationProvider; import com.asakusafw.runtime.windows.WindowsSupport; /** * Test for {@link TemporaryInputFormat}. */ public class TemporaryInputFormatTest { /** * Windows platform support. */ @ClassRule public static final WindowsSupport WINDOWS_SUPPORT = new WindowsSupport(); /** * Temporary folder for testing. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); /** * simple case for computing splits. */ @Test public void splits_simple() { BlockMap blocks = blocks("testing", m(10)); List<FileSplit> splits = TemporaryInputFormat.computeSplits(new Path("testing"), blocks, m(64)); assertThat(splits, hasSize(1)); FileSplit s0 = find(splits, 0); assertThat(s0.getLength(), is(m(10))); } /** * computing splits with already aligned blocks. */ @Test public void splits_aligned() { BlockMap blocks = blocks("testing", TemporaryFile.BLOCK_SIZE, TemporaryFile.BLOCK_SIZE); List<FileSplit> splits = TemporaryInputFormat.computeSplits(new Path("testing"), blocks, m(64)); assertThat(splits, hasSize(2)); FileSplit s0 = find(splits, 0); assertThat(s0.getLength(), is((long) TemporaryFile.BLOCK_SIZE)); FileSplit s1 = find(splits, TemporaryFile.BLOCK_SIZE); assertThat(s1.getLength(), is((long) TemporaryFile.BLOCK_SIZE)); } /** * computing splits without unaligned blocks. */ @Test public void splits_unaligned() { BlockMap blocks = blocks("testing", TemporaryFile.BLOCK_SIZE - 10, TemporaryFile.BLOCK_SIZE); List<FileSplit> splits = TemporaryInputFormat.computeSplits(new Path("testing"), blocks, m(128)); assertThat(splits, hasSize(2)); FileSplit s0 = find(splits, 0); assertThat(s0.getLength(), is((long) TemporaryFile.BLOCK_SIZE)); FileSplit s1 = find(splits, TemporaryFile.BLOCK_SIZE); assertThat(s1.getLength(), is((long) TemporaryFile.BLOCK_SIZE - 10)); } /** * computing splits with aligned blocks plus. */ @Test public void splits_aligned_rest() { BlockMap blocks = blocks("testing", TemporaryFile.BLOCK_SIZE, TemporaryFile.BLOCK_SIZE + 10); List<FileSplit> splits = TemporaryInputFormat.computeSplits(new Path("testing"), blocks, m(64)); assertThat(splits, hasSize(2)); FileSplit s0 = find(splits, 0); assertThat(s0.getLength(), is((long) TemporaryFile.BLOCK_SIZE)); FileSplit s1 = find(splits, TemporaryFile.BLOCK_SIZE); assertThat(s1.getLength(), is((long) TemporaryFile.BLOCK_SIZE + 10)); } /** * computing splits with forcibly splitting. */ @Test public void splits_force() { BlockMap blocks = blocks("testing", TemporaryFile.BLOCK_SIZE * 10); List<FileSplit> splits = TemporaryInputFormat.computeSplits( new Path("testing"), blocks, TemporaryFile.BLOCK_SIZE + 1); assertThat(splits, hasSize(5)); FileSplit s0 = find(splits, TemporaryFile.BLOCK_SIZE * 0); assertThat(s0.getLength(), is((long) TemporaryFile.BLOCK_SIZE * 2)); FileSplit s1 = find(splits, TemporaryFile.BLOCK_SIZE * 2); assertThat(s1.getLength(), is((long) TemporaryFile.BLOCK_SIZE * 2)); FileSplit s2 = find(splits, TemporaryFile.BLOCK_SIZE * 4); assertThat(s2.getLength(), is((long) TemporaryFile.BLOCK_SIZE * 2)); FileSplit s3 = find(splits, TemporaryFile.BLOCK_SIZE * 6); assertThat(s3.getLength(), is((long) TemporaryFile.BLOCK_SIZE * 2)); FileSplit s4 = find(splits, TemporaryFile.BLOCK_SIZE * 8); assertThat(s4.getLength(), is((long) TemporaryFile.BLOCK_SIZE * 2)); } /** * computing splits w/ suppress. */ @Test public void splits_suppress() { BlockMap blocks = blocks("testing", TemporaryFile.BLOCK_SIZE * 10); List<FileSplit> splits = TemporaryInputFormat.computeSplits(new Path("testing"), blocks, 0); assertThat(splits, hasSize(1)); FileSplit s0 = find(splits, 0); assertThat(s0.getLength(), is((long) TemporaryFile.BLOCK_SIZE * 10)); } /** * Simple case for record readers. * @throws Exception if failed */ @Test public void reader_simple() throws Exception { Configuration conf = new ConfigurationProvider().newInstance(); FileStatus stat = write(conf, 1); try (RecordReader<NullWritable, Text> reader = TemporaryInputFormat.createRecordReader()) { reader.initialize( new FileSplit(stat.getPath(), 0, stat.getLen(), null), new TaskAttemptContextImpl(conf, new TaskAttemptID())); assertThat(reader.nextKeyValue(), is(true)); assertThat(reader.getCurrentValue(), is(new Text("Hello, world!"))); assertThat(reader.nextKeyValue(), is(false)); assertThat((double) reader.getProgress(), closeTo(1.0, 0.01)); } } private FileStatus write(Configuration conf, int count) throws IOException { Path path = new Path(folder.newFile().toURI()); try (ModelOutput<Text> output = TemporaryStorage.openOutput(conf, Text.class, path)) { Text buffer = new Text("Hello, world!"); for (int i = 0; i < count; i++) { output.write(buffer); } } return path.getFileSystem(conf).getFileStatus(path); } private long m(long value) { return value * 1024 * 1024; } private FileSplit find(List<FileSplit> splits, long start) { for (FileSplit split : splits) { if (split.getStart() == start) { return split; } } throw new AssertionError(start); } private BlockMap blocks(String path, long... blockSizes) { List<BlockInfo> blockList = new ArrayList<>(); long totalSize = 0; for (long blockSize : blockSizes) { long next = totalSize + blockSize; blockList.add(new BlockInfo(totalSize, next, null)); totalSize = next; } return BlockMap.create(path, totalSize, blockList, false); } }
apache-2.0
androidx/constraintlayout
constraintlayout/constraintlayout/src/main/java/androidx/constraintlayout/motion/utils/ViewSpline.java
8330
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.constraintlayout.motion.utils; import android.os.Build; import android.util.Log; import android.util.SparseArray; import android.view.View; import androidx.constraintlayout.core.motion.utils.CurveFit; import androidx.constraintlayout.core.motion.utils.SplineSet; import androidx.constraintlayout.motion.widget.Key; import androidx.constraintlayout.motion.widget.MotionLayout; import androidx.constraintlayout.widget.ConstraintAttribute; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public abstract class ViewSpline extends SplineSet { private static final String TAG = "ViewSpline"; public static ViewSpline makeCustomSpline(String str, SparseArray<ConstraintAttribute> attrList) { return new CustomSet(str, attrList); } public static ViewSpline makeSpline(String str) { switch (str) { case Key.ALPHA: return new AlphaSet(); case Key.ELEVATION: return new ElevationSet(); case Key.ROTATION: return new RotationSet(); case Key.ROTATION_X: return new RotationXset(); case Key.ROTATION_Y: return new RotationYset(); case Key.PIVOT_X: return new PivotXset(); case Key.PIVOT_Y: return new PivotYset(); case Key.TRANSITION_PATH_ROTATE: return new PathRotate(); case Key.SCALE_X: return new ScaleXset(); case Key.SCALE_Y: return new ScaleYset(); case Key.WAVE_OFFSET: return new AlphaSet(); case Key.WAVE_VARIES_BY: return new AlphaSet(); case Key.TRANSLATION_X: return new TranslationXset(); case Key.TRANSLATION_Y: return new TranslationYset(); case Key.TRANSLATION_Z: return new TranslationZset(); case Key.PROGRESS: return new ProgressSet(); default: return null; } } public abstract void setProperty(View view, float t); static class ElevationSet extends ViewSpline { @Override public void setProperty(View view, float t) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setElevation(get(t)); } } } static class AlphaSet extends ViewSpline { @Override public void setProperty(View view, float t) { view.setAlpha(get(t)); } } static class RotationSet extends ViewSpline { @Override public void setProperty(View view, float t) { view.setRotation(get(t)); } } static class RotationXset extends ViewSpline { @Override public void setProperty(View view, float t) { view.setRotationX(get(t)); } } static class RotationYset extends ViewSpline { @Override public void setProperty(View view, float t) { view.setRotationY(get(t)); } } static class PivotXset extends ViewSpline { @Override public void setProperty(View view, float t) { view.setPivotX(get(t)); } } static class PivotYset extends ViewSpline { @Override public void setProperty(View view, float t) { view.setPivotY(get(t)); } } public static class PathRotate extends ViewSpline { @Override public void setProperty(View view, float t) { } public void setPathRotate(View view, float t, double dx, double dy) { view.setRotation(get(t) + (float) Math.toDegrees(Math.atan2(dy, dx))); } } static class ScaleXset extends ViewSpline { @Override public void setProperty(View view, float t) { view.setScaleX(get(t)); } } static class ScaleYset extends ViewSpline { @Override public void setProperty(View view, float t) { view.setScaleY(get(t)); } } static class TranslationXset extends ViewSpline { @Override public void setProperty(View view, float t) { view.setTranslationX(get(t)); } } static class TranslationYset extends ViewSpline { @Override public void setProperty(View view, float t) { view.setTranslationY(get(t)); } } static class TranslationZset extends ViewSpline { @Override public void setProperty(View view, float t) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.setTranslationZ(get(t)); } } } public static class CustomSet extends ViewSpline { String mAttributeName; SparseArray<ConstraintAttribute> mConstraintAttributeList; float[] mTempValues; public CustomSet(String attribute, SparseArray<ConstraintAttribute> attrList) { mAttributeName = attribute.split(",")[1]; mConstraintAttributeList = attrList; } public void setup(int curveType) { int size = mConstraintAttributeList.size(); int dimensionality = mConstraintAttributeList.valueAt(0).numberOfInterpolatedValues(); double[] time = new double[size]; mTempValues = new float[dimensionality]; double[][] values = new double[size][dimensionality]; for (int i = 0; i < size; i++) { int key = mConstraintAttributeList.keyAt(i); ConstraintAttribute ca = mConstraintAttributeList.valueAt(i); time[i] = key * 1E-2; ca.getValuesToInterpolate(mTempValues); for (int k = 0; k < mTempValues.length; k++) { values[i][k] = mTempValues[k]; } } mCurveFit = CurveFit.get(curveType, time, values); } public void setPoint(int position, float value) { throw new RuntimeException("don't call for custom attribute call setPoint(pos, ConstraintAttribute)"); } public void setPoint(int position, ConstraintAttribute value) { mConstraintAttributeList.append(position, value); } @Override public void setProperty(View view, float t) { mCurveFit.getPos(t, mTempValues); CustomSupport.setInterpolatedValue(mConstraintAttributeList.valueAt(0), view, mTempValues); } } static class ProgressSet extends ViewSpline { boolean mNoMethod = false; @Override public void setProperty(View view, float t) { if (view instanceof MotionLayout) { ((MotionLayout) view).setProgress(get(t)); } else { if (mNoMethod) { return; } Method method = null; try { method = view.getClass().getMethod("setProgress", Float.TYPE); } catch (NoSuchMethodException e) { mNoMethod = true; } if (method != null) { try { method.invoke(view, get(t)); } catch (IllegalAccessException e) { Log.e(TAG, "unable to setProgress", e); } catch (InvocationTargetException e) { Log.e(TAG, "unable to setProgress", e); } } } } } }
apache-2.0
tgraf/cilium
cilium/cmd/endpoint_regenerate.go
1304
// Copyright 2017-2019 Authors of Cilium // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cmd import ( "fmt" "github.com/cilium/cilium/api/v1/models" "github.com/spf13/cobra" ) // endpointRegenerateCmd represents the endpoint_regenerate command var endpointRegenerateCmd = &cobra.Command{ Use: "regenerate <endpoint-id>", Short: "Force regeneration of endpoint program", PreRun: requireEndpointID, Run: func(cmd *cobra.Command, args []string) { id := args[0] cfg := &models.EndpointConfigurationSpec{} if err := client.EndpointConfigPatch(id, cfg); err != nil { Fatalf("Cannot regenerate endpoint %s: %s\n", id, err) } else { fmt.Printf("Endpoint %s successfully regenerated\n", id) } }, } func init() { endpointCmd.AddCommand(endpointRegenerateCmd) }
apache-2.0
stephane-martin/salt-debian-packaging
salt-2016.3.2/tests/integration/files/file/base/_modules/runtests_helpers.py
920
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` runtests_helpers.py ~~~~~~~~~~~~~~~~~~~ ''' # Import python libs from __future__ import absolute_import import os import tempfile # Import salt libs import salt.utils SYS_TMP_DIR = os.path.realpath( # Avoid ${TMPDIR} and gettempdir() on MacOS as they yield a base path too long # for unix sockets: ``error: AF_UNIX path too long`` # Gentoo Portage prefers ebuild tests are rooted in ${TMPDIR} os.environ.get('TMPDIR', tempfile.gettempdir()) if not salt.utils.is_darwin() else '/tmp' ) # This tempdir path is defined on tests.integration.__init__ TMP = os.path.join(SYS_TMP_DIR, 'salt-tests-tmpdir') def get_salt_temp_dir(): return TMP def get_salt_temp_dir_for_path(*path): return os.path.join(TMP, *path) def get_sys_temp_dir_for_path(*path): return os.path.join(SYS_TMP_DIR, *path)
apache-2.0
googleapis/google-cloud-ruby
google-cloud-data_catalog-v1/snippets/data_catalog/delete_entry_group.rb
1266
# frozen_string_literal: true # Copyright 2021 Google LLC # # 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 # # https://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. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! # [START datacatalog_v1_generated_DataCatalog_DeleteEntryGroup_sync] require "google/cloud/data_catalog/v1" # Create a client object. The client can be reused for multiple calls. client = Google::Cloud::DataCatalog::V1::DataCatalog::Client.new # Create a request. To set request fields, pass in keyword arguments. request = Google::Cloud::DataCatalog::V1::DeleteEntryGroupRequest.new # Call the delete_entry_group method. result = client.delete_entry_group request # The returned object is of type Google::Protobuf::Empty. p result # [END datacatalog_v1_generated_DataCatalog_DeleteEntryGroup_sync]
apache-2.0
douglasmariano/spring-webmvc
src/main/webapp/resources/template/stopwatch/Gruntfile.js
1491
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! <%= pkg.name %> <%= pkg.version %> <%=grunt.template.today("yyyy-mm-dd")%>*/' }, dist: { src: ['src/timer.jquery.js'], dest: 'dist/timer.jquery.min.js' }, }, // Implement coding guidelines jscs: { src: ['src/timer.jquery.js', 'test/timer.jquery.test.js'], options: { config: '.jscsrc' } }, jshint: { all: { src: ['src/timer.jquery.js'], options: { jshintrc: '.jshintrc' }, globals: { exports: true } } }, // Start a connect server for qunit tests connect: { server: { options: { port: 8000, base: '.' } } }, // Run qunit tests with PhantomJS qunit: { all: { options: { urls: [ 'http://localhost:8000/test/timer.jquery.html' ] } } }, watch: { scripts: { files: ['src/timer.jquery.js', 'test/timer.jquery.test.js'], tasks: ['jscs', 'jshint', 'uglify'], options: { nospawn: true } } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks("grunt-jscs"); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-watch'); //register default task grunt.registerTask('default', 'watch'); grunt.registerTask('test', ['connect', 'qunit']); }
apache-2.0
FHPproject/FHPUsef
usef-build/usef-workflow/usef-dso/src/main/java/energy/usef/dso/workflow/dto/package-info.java
718
/* * Copyright 2015-2016 USEF Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Data transfer object classes for the Distribution Service Operator. */ package energy.usef.dso.workflow.dto;
apache-2.0
martinbede/second-sight
tensorflow/core/kernels/resize_nearest_neighbor_op_gpu.cu.cc
3529
/* Copyright 2015 Google Inc. 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. ==============================================================================*/ #if GOOGLE_CUDA #define EIGEN_USE_GPU #include <stdio.h> #include "tensorflow/core/kernels/resize_nearest_neighbor_op_gpu.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/util/cuda_kernel_helper.h" namespace tensorflow { namespace { template <typename T> __global__ void ResizeNearestNeighborNHWC(const int nthreads, const T* bottom_data, const int in_height, const int in_width, const int channels, const int out_height, const int out_width, const float height_scale, const float width_scale, T* top_data) { CUDA_1D_KERNEL_LOOP(index, nthreads) { int n = index; int c = n % channels; n /= channels; int out_x = n % out_width; n /= out_width; int out_y = n % out_height; n /= out_height; const T* bottom_data_n = bottom_data + n * channels * in_height * in_width; const int in_x = min(static_cast<int>(floorf(out_x * width_scale)), in_width - 1); const int in_y = min(static_cast<int>(floorf(out_y * height_scale)), in_height - 1); const int idx = (in_y * in_width + in_x) * channels + c; top_data[index] = ldg(bottom_data_n + idx); } } } // namespace template <typename T> bool ResizeNearestNeighbor(const T* bottom_data, const int batch, const int in_height, const int in_width, const int channels, const int out_height, const int out_width, const float height_scale, const float width_scale, T* top_data, const Eigen::GpuDevice& d) { const int output_size = batch * channels * out_height * out_width; CudaLaunchConfig config = GetCudaLaunchConfig(output_size, d); ResizeNearestNeighborNHWC<T> <<<config.block_count, config.thread_per_block, 0, d.stream()>>>( output_size, bottom_data, in_height, in_width, channels, out_height, out_width, height_scale, width_scale, top_data); return d.ok(); } #define DECLARE_GPU_SPEC(T) \ template bool ResizeNearestNeighbor(const T* bottom_data, const int batch, \ const int in_height, const int in_width, \ const int channels, const int out_height, \ const int out_width, const float height_scale, \ const float width_scale, T* top_data, \ const Eigen::GpuDevice& d); TF_CALL_GPU_NUMBER_TYPES(DECLARE_GPU_SPEC); #undef DECLARE_GPU_SPEC } // end namespace tensorflow #endif // GOOGLE_CUDA
apache-2.0
adufilie/flex-falcon
compiler/src/org/apache/flex/compiler/projects/IFlexProject.java
8006
/* * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.flex.compiler.projects; import java.io.File; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.flex.compiler.common.DependencyTypeSet; import org.apache.flex.compiler.common.XMLName; import org.apache.flex.compiler.config.RSLSettings; import org.apache.flex.compiler.css.ICSSManager; import org.apache.flex.compiler.exceptions.LibraryCircularDependencyException; import org.apache.flex.compiler.internal.config.IWriteOnlyProjectSettings; import org.apache.flex.compiler.internal.css.CSSManager; import org.apache.flex.compiler.mxml.IMXMLNamespaceMapping; import org.apache.flex.compiler.mxml.IXMLNameResolver; import org.apache.flex.compiler.targets.ISWCTarget; import org.apache.flex.compiler.targets.ITargetProgressMonitor; import org.apache.flex.compiler.targets.ITargetSettings; /** * Base interface for all project types that support all flex source file types * ( mxml, fxg, css, etc ). */ public interface IFlexProject extends IASProject, IXMLNameResolver, IWriteOnlyProjectSettings { /** * Create a SWC target * * @param targetSettings The settings to use for this target * @param progressMonitor to collect progress information, can be <code>null</code> * @return The newly created ISWCTarget * @throws InterruptedException */ ISWCTarget createSWCTarget(ITargetSettings targetSettings, ITargetProgressMonitor progressMonitor) throws InterruptedException; /** * Sets the mappings from MXML namespace URI to manifest files, as specified * by -namespace options. * * @param namespaceMappings An array of {@code MXMLNamespaceMapping} * objects. */ @Override void setNamespaceMappings(List<? extends IMXMLNamespaceMapping> namespaceMappings); /** * Get all the namespace mappings. * * @return An array of namespace mappings. */ IMXMLNamespaceMapping[] getNamespaceMappings(); /** * Get the project-level CSS manager. * * @return {@link CSSManager} of the project. */ ICSSManager getCSSManager(); /** * Returns the requested locales for this project. * * @return a list of project's locales */ Collection<String> getLocales(); /** * Sets the locale dependent path map for the project. For each entry, * the key is the path of a locale dependent resource (source path or library path entry) * and the value is the locale it depends on. * * @param localeDependentResources map that contains project's locale * dependent resources */ void setLocaleDependentResources(Map<String, String> localeDependentResources); /** * Returns the locale of the resource with a given path if the resource * is locale dependent. This currently returns the locale for only * source path and library path entries, which are the only resources passed to * compiler and can contain {locale} token. * * @param path path of a file/directory for which to determine the locale * @return locale of the resource with a given path if the resource * is locale dependent or <code>null</code> if the resource is not locale * dependent. */ String getResourceLocale(String path); // // New configurator interface // /** * Returns the file encoding use to compile ActionScript files. * * @return the file encoding use to compile ActionScript files. */ String getActionScriptFileEncoding(); /** * Returns a map of extension element files to extension paths. * * @return a map of extension element files to extension paths. */ Map<File, List<String>> getExtensionLibraries(); /** * The absolute path of the services-config.xml file. This file used * to configure a Flex client to talk to a BlazeDS server. * * @return the absolute path of the services-config.xml file. Null * if the file has not been configured. */ String getServicesXMLPath(); /** * The list of RSLs configured for this application. * * @return a list of {@link RSLSettings} where each entry in the list is an * RSL to load at runtime. */ List<RSLSettings> getRuntimeSharedLibraryPath(); /** * Set the RSL library path with an ordered list of RSLs. The runtime will * load the RSLs in the order specified. * * @param rsls Each {@link RSLSettings} in the list describes an RSL and * its failovers. If null, the list of RSLs is reset. */ void setRuntimeSharedLibraryPath(List<RSLSettings> rsls); /** * Get the set of libraries a given library depends on. * * @param targetLibrary The library to find dependencies for. May not be * null. * @param dependencyTypeSet The types of dependencies to consider when * determining the library's dependencies. If this parameter is null or an empty set, then all * dependencies will be considered. * @return A set of Strings; where each String is the location of a library in the file system. */ Set<String> computeLibraryDependencies(File targetLibrary, DependencyTypeSet dependencyTypeSet) throws LibraryCircularDependencyException; /** * Get the dependency order of libraries on the internal library path and * external library path of this project. * * @param dependencySet The types of dependencies to consider when * determining the dependency order. If this parameter is null or an empty set, then all * dependencies will be considered. * @return An ordered list of library dependencies. Each String in the * list is the location of a library in the file system. The first library in the list has no * dependencies. Each library in the list has at least the same dependencies as its * predecessor and may be dependent on its predecessor as well. */ List<String> computeLibraryDependencyOrder(DependencyTypeSet dependencySet) throws LibraryCircularDependencyException; /** * Get the names of all the themes used in this project. * * @return A list of theme names. */ List<String> getThemeNames(); /** * Option of enable or prevent various Flex compiler behaviors. * This is currently used to enable/disable the generation of a root class for library swfs * and generation of code for application swfs. */ boolean isFlex(); /** * Uses the manifest information to find all the MXML tags that map to a * specified fully-qualified ActionScript classname, such as as * <code>"spark.controls.Button"</code> * * @param className Fully-qualified ActionScript classname, such as as * <code>"spark.controls.Button"</code> * @return A collection of {@link XMLName}'s representing a MXML tags, such * as a <code>"Button"</code> tag in the namespace * <code>"library://ns.adobe.com/flex/spark"</code>. */ Collection<XMLName> getTagNamesForClass(String className); }
apache-2.0
aaron-prindle/minikube
pkg/localkube/localkube.go
10446
/* Copyright 2016 The Kubernetes Authors 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. */ package localkube import ( "crypto/tls" "crypto/x509" "encoding/pem" "fmt" "io/ioutil" "net" "net/http" "path" "strconv" "strings" "github.com/golang/glog" "github.com/pkg/errors" utilnet "k8s.io/apimachinery/pkg/util/net" "k8s.io/apiserver/pkg/util/flag" "k8s.io/minikube/pkg/util/kubeconfig" "k8s.io/minikube/pkg/util" ) const serverInterval = 200 // LocalkubeServer provides a fully functional Kubernetes cluster running entirely through goroutines type LocalkubeServer struct { // Inherits Servers Servers // Options Containerized bool EnableDNS bool DNSDomain string LocalkubeDirectory string ServiceClusterIPRange net.IPNet APIServerAddress net.IP APIServerPort int APIServerInsecureAddress net.IP APIServerInsecurePort int APIServerName string ShouldGenerateCerts bool ShouldGenerateKubeconfig bool ShowVersion bool ShowHostIP bool RuntimeConfig flag.ConfigurationMap NodeIP net.IP ContainerRuntime string RemoteRuntimeEndpoint string RemoteImageEndpoint string NetworkPlugin string FeatureGates string ExtraConfig util.ExtraOptionSlice } func (lk *LocalkubeServer) AddServer(server Server) { lk.Servers = append(lk.Servers, server) } func (lk LocalkubeServer) GetEtcdDataDirectory() string { return path.Join(lk.LocalkubeDirectory, "etcd") } func (lk LocalkubeServer) GetDNSDataDirectory() string { return path.Join(lk.LocalkubeDirectory, "dns") } func (lk LocalkubeServer) GetCertificateDirectory() string { return path.Join(lk.LocalkubeDirectory, "certs") } func (lk LocalkubeServer) GetPrivateKeyCertPath() string { return path.Join(lk.GetCertificateDirectory(), "apiserver.key") } func (lk LocalkubeServer) GetPublicKeyCertPath() string { return path.Join(lk.GetCertificateDirectory(), "apiserver.crt") } func (lk LocalkubeServer) GetCAPrivateKeyCertPath() string { return path.Join(lk.GetCertificateDirectory(), "ca.key") } func (lk LocalkubeServer) GetCAPublicKeyCertPath() string { return path.Join(lk.GetCertificateDirectory(), "ca.crt") } func (lk LocalkubeServer) GetProxyClientPrivateKeyCertPath() string { return path.Join(lk.GetCertificateDirectory(), "proxy-client.key") } func (lk LocalkubeServer) GetProxyClientPublicKeyCertPath() string { return path.Join(lk.GetCertificateDirectory(), "proxy-client.crt") } func (lk LocalkubeServer) GetProxyClientCAPublicKeyCertPath() string { return path.Join(lk.GetCertificateDirectory(), "proxy-client-ca.crt") } func (lk LocalkubeServer) GetProxyClientCAPrivateKeyCertPath() string { return path.Join(lk.GetCertificateDirectory(), "proxy-client-ca.key") } func (lk LocalkubeServer) GetAPIServerSecureURL() string { return fmt.Sprintf("https://%s:%d", lk.APIServerAddress.String(), lk.APIServerPort) } func (lk LocalkubeServer) GetAPIServerInsecureURL() string { if lk.APIServerInsecurePort != 0 { return fmt.Sprintf("http://%s:%d", lk.APIServerInsecureAddress.String(), lk.APIServerInsecurePort) } return "" } func (lk LocalkubeServer) GetAPIServerProtocol() string { if lk.APIServerInsecurePort != 0 { return "http://" } return "https://" } func (lk LocalkubeServer) GetTransport() (*http.Transport, error) { if lk.APIServerInsecurePort != 0 { return &http.Transport{}, nil } cert, err := tls.LoadX509KeyPair(lk.GetPublicKeyCertPath(), lk.GetPrivateKeyCertPath()) if err != nil { glog.Error(err) return &http.Transport{}, err } // Load CA cert caCert, err := ioutil.ReadFile(lk.GetCAPublicKeyCertPath()) if err != nil { glog.Warning(err) return &http.Transport{}, err } caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: caCertPool, } tlsConfig.BuildNameToCertificate() return &http.Transport{TLSClientConfig: tlsConfig}, nil } // Get the host's public IP address func (lk LocalkubeServer) GetHostIP() (net.IP, error) { return utilnet.ChooseBindAddress(net.ParseIP("0.0.0.0")) } func (lk LocalkubeServer) getExtraConfigForComponent(component string) []util.ExtraOption { e := []util.ExtraOption{} for _, c := range lk.ExtraConfig { if c.Component == component { e = append(e, c) } } return e } func (lk LocalkubeServer) SetExtraConfigForComponent(component string, config interface{}) { extra := lk.getExtraConfigForComponent(component) for _, e := range extra { glog.Infof("Setting %s to %s on %s.\n", e.Key, e.Value, component) if err := util.FindAndSet(e.Key, config, e.Value); err != nil { glog.Warningf("Unable to set %s to %s. Error: %s", e.Key, e.Value, err) } } } func (lk LocalkubeServer) GetFeatureGates() (map[string]bool, error) { fg := map[string]bool{} if lk.FeatureGates == "" { return fg, nil } gates := strings.Split(lk.FeatureGates, ",") for _, g := range gates { kvp := strings.SplitN(g, "=", 2) if len(kvp) != 2 { return nil, fmt.Errorf("invalid feature gate specification: %s", g) } value, err := strconv.ParseBool(kvp[1]) if err != nil { return nil, fmt.Errorf("invalid feature gate specification: %s", g) } fg[kvp[0]] = value } return fg, nil } func (lk LocalkubeServer) loadCert(path string) (*x509.Certificate, error) { contents, err := ioutil.ReadFile(path) if err != nil { return nil, err } decoded, _ := pem.Decode(contents) if decoded == nil { return nil, fmt.Errorf("Unable to decode certificate.") } return x509.ParseCertificate(decoded.Bytes) } func (lk LocalkubeServer) shouldGenerateCerts(ips []net.IP) bool { if !(util.CanReadFile(lk.GetPublicKeyCertPath()) && util.CanReadFile(lk.GetPrivateKeyCertPath())) { fmt.Println("Regenerating certs because the files aren't readable") return true } cert, err := lk.loadCert(lk.GetPublicKeyCertPath()) if err != nil { fmt.Println("Regenerating certs because there was an error loading the certificate: ", err) return true } certIPs := map[string]bool{} for _, certIP := range cert.IPAddresses { certIPs[certIP.String()] = true } for _, ip := range ips { if _, ok := certIPs[ip.String()]; !ok { fmt.Println("Regenerating certs becase an IP is missing: ", ip) return true } } return false } func (lk LocalkubeServer) shouldGenerateCACerts() bool { if !(util.CanReadFile(lk.GetCAPublicKeyCertPath()) && util.CanReadFile(lk.GetCAPrivateKeyCertPath())) { fmt.Println("Regenerating CA certs because the files aren't readable") return true } _, err := lk.loadCert(lk.GetCAPublicKeyCertPath()) if err != nil { fmt.Println("Regenerating CA certs because there was an error loading the certificate: ", err) return true } return false } func (lk LocalkubeServer) GenerateKubeconfig() error { if !lk.ShouldGenerateKubeconfig { return nil } // setup kubeconfig kubeConfigFile := util.DefaultKubeConfigPath glog.Infof("Setting up kubeconfig at: %s", kubeConfigFile) kubeHost := "http://127.0.0.1:" + strconv.Itoa(lk.APIServerInsecurePort) //TODO(aaron-prindle) configure this so that it can generate secure certs as well kubeCfgSetup := &kubeconfig.KubeConfigSetup{ ClusterName: lk.APIServerName, ClusterServerAddress: kubeHost, KeepContext: false, } kubeCfgSetup.SetKubeConfigFile(kubeConfigFile) if err := kubeconfig.SetupKubeConfig(kubeCfgSetup); err != nil { glog.Errorln("Error setting up kubeconfig: ", err) return err } return nil } func (lk LocalkubeServer) getAllIPs() ([]net.IP, error) { serviceIP, err := util.GetServiceClusterIP(lk.ServiceClusterIPRange.String()) if err != nil { return nil, errors.Wrap(err, "getting service cluster ip") } ips := []net.IP{serviceIP} addrs, err := net.InterfaceAddrs() if err != nil { return nil, err } for _, addr := range addrs { ipnet, ok := addr.(*net.IPNet) if !ok { fmt.Println("Skipping: ", addr) continue } ips = append(ips, ipnet.IP) } return ips, nil } func (lk LocalkubeServer) GenerateCerts() error { if !lk.shouldGenerateCACerts() { fmt.Println( "Using these existing CA certs: ", lk.GetCAPublicKeyCertPath(), lk.GetCAPrivateKeyCertPath(), lk.GetProxyClientCAPublicKeyCertPath(), lk.GetProxyClientCAPrivateKeyCertPath(), ) } else { fmt.Println("Creating CA cert") if err := util.GenerateCACert( lk.GetCAPublicKeyCertPath(), lk.GetCAPrivateKeyCertPath(), lk.APIServerName, ); err != nil { fmt.Println("Failed to create CA cert: ", err) return err } fmt.Println("Creating proxy client CA cert") if err := util.GenerateCACert( lk.GetProxyClientCAPublicKeyCertPath(), lk.GetProxyClientCAPrivateKeyCertPath(), "proxyClientCA", ); err != nil { fmt.Println("Failed to create proxy client CA cert: ", err) return err } } ips, err := lk.getAllIPs() if err != nil { return err } if !lk.shouldGenerateCerts(ips) { fmt.Println( "Using these existing certs: ", lk.GetPublicKeyCertPath(), lk.GetPrivateKeyCertPath(), lk.GetProxyClientPublicKeyCertPath(), lk.GetProxyClientPrivateKeyCertPath(), ) return nil } fmt.Println("Creating cert with IPs: ", ips) if err := util.GenerateSignedCert( lk.GetPublicKeyCertPath(), lk.GetPrivateKeyCertPath(), "minikube", ips, util.GetAlternateDNS(lk.DNSDomain), lk.GetCAPublicKeyCertPath(), lk.GetCAPrivateKeyCertPath(), ); err != nil { fmt.Println("Failed to create cert: ", err) return err } if err := util.GenerateSignedCert( lk.GetProxyClientPublicKeyCertPath(), lk.GetProxyClientPrivateKeyCertPath(), "aggregator", []net.IP{}, []string{}, lk.GetProxyClientCAPublicKeyCertPath(), lk.GetProxyClientCAPrivateKeyCertPath(), ); err != nil { fmt.Println("Failed to create proxy client cert: ", err) return err } return nil }
apache-2.0
freemanpd/chef-elixr-cookbook
metadata.rb
276
name 'elixir' maintainer 'YOUR_COMPANY_NAME' maintainer_email 'YOUR_EMAIL' license 'All rights reserved' description 'Installs/Configures elixir' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0'
apache-2.0
apache/logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/util/Base64Util.java
2475
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.util; import java.lang.reflect.Method; import org.apache.logging.log4j.LoggingException; /** * Base64 encodes Strings. This utility is only necessary because the mechanism to do this changed in Java 8 and * the original method was removed in Java 9. */ public final class Base64Util { private static Method encodeMethod = null; private static Object encoder = null; static { try { Class<?> clazz = LoaderUtil.loadClass("java.util.Base64"); Class<?> encoderClazz = LoaderUtil.loadClass("java.util.Base64$Encoder"); Method method = clazz.getMethod("getEncoder"); encoder = method.invoke(null); encodeMethod = encoderClazz.getMethod("encodeToString", byte[].class); } catch (Exception ex) { try { Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DataTypeConverter"); encodeMethod = clazz.getMethod("printBase64Binary"); } catch (Exception ex2) { LowLevelLogUtil.logException("Unable to create a Base64 Encoder", ex2); } } } private Base64Util() { } public static String encode(String str) { if (str == null) { return null; } byte [] data = str.getBytes(); if (encodeMethod != null) { try { return (String) encodeMethod.invoke(encoder, data); } catch (Exception ex) { throw new LoggingException("Unable to encode String", ex); } } throw new LoggingException("No Encoder, unable to encode string"); } }
apache-2.0
NICTA/javallier
src/main/java/com/n1analytics/paillier/EncodedNumber.java
12560
/** * Copyright 2015 NICTA * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.n1analytics.paillier; import com.n1analytics.paillier.util.HashChain; import java.math.BigDecimal; import java.math.BigInteger; /** * Represents encoded numbers, enabling Paillier encrypted operations on * signed integers and signed floating point numbers. * * This class defines public methods: * <ul> * <li>To check whether another EncodedNumber or an EncryptedNumber has the same PaillierContext</li> * <li>To decode exactly and approximately to a BigInteger, long, double and Number</li> * <li>To perform arithmetic operations; addition, subtraction, limited multiplication and limited division.</li> * </ul> */ public final class EncodedNumber { /** * The Paillier context used to encode this number. */ protected final PaillierContext context; /** * The value of the encoded number. Must be a non-negative integer less than <code>context.getModulus()</code> */ protected final BigInteger value; /** * The exponent of the encoded number. */ protected final int exponent; /** * Constructs an encoded number given an encoding and an encoded value. The * encoded value must be a non-negative integer less than * {@code context.getModulus()}. * * @param context used to encode value. * @param value of the encoded number must be a non-negative integer less than {@code context.getModulus()}. * @param exponent of the encoded number. */ protected EncodedNumber(PaillierContext context, BigInteger value, int exponent) { if (context == null) { throw new IllegalArgumentException("context must not be null"); } if (value == null) { throw new IllegalArgumentException("value must not be null"); } if (value.signum() < 0) { throw new IllegalArgumentException("value must be non-negative"); } if (value.compareTo(context.getPublicKey().getModulus()) >= 0) { throw new IllegalArgumentException("value must be less than modulus"); } this.context = context; this.value = value; this.exponent = exponent; } /** * @return the {@code context} with which this number is encoded. */ public PaillierContext getContext() { return context; } /** * @return the encoded {@code value}. */ public BigInteger getValue() { return value; } /** * @return {@code exponent}. */ public int getExponent() { return exponent; } /** * Checks whether this encoded number is valid in the current context. * * @return true if encoded number is valid, false otherwise. */ public boolean isValid() { return context.isValid(this); } /** * Returns the signum function of this EncodedNumber. * @return -1, 0 or 1 as the value of this EncodedNumber is negative, zero or positive. */ public int signum(){ return context.signum(this); } /** * Checks whether an {@code EncryptedNumber} has the same context as this {@code EncodedNumber}. * * @param other {@code EncryptedNumber} to compare to. * @return {@code other} provided the contexts match, else PaillierContextMismatchException is thrown. * @throws PaillierContextMismatchException if the contexts are different. */ public EncryptedNumber checkSameContext(EncryptedNumber other) throws PaillierContextMismatchException { return context.checkSameContext(other); } /** * Checks whether another {@code EncodedNumber} has the same context as this {@code EncodedNumber}. * * @param other {@code EncodedNumber} to compare to. * @return {@code other} provided the contexts match, else PaillierContextMismatchException is thrown. * @throws PaillierContextMismatchException if the context are different. */ public EncodedNumber checkSameContext(EncodedNumber other) throws PaillierContextMismatchException { return context.checkSameContext(other); } /** * Decodes to a {@code BigInteger} representation. See * {@link com.n1analytics.paillier.PaillierContext#decodeBigInteger(EncodedNumber)} for details. * * @return the decoded number. * @throws ArithmeticException if this {@code EncodedNumber} cannot be represented as a {@code BigInteger}. */ public BigInteger decodeBigInteger() throws ArithmeticException { return context.decodeBigInteger(this); } /** * Decodes this {@code EncodedNumber} to a {@code double} representation. See * {@link com.n1analytics.paillier.PaillierContext#decodeDouble(EncodedNumber)} for details. * * @return the decoded number. * @throws ArithmeticException if this {@code EncodedNumber} cannot be represented as a valid {@code double}. */ public double decodeDouble() throws ArithmeticException { return context.decodeDouble(this); } /** * Decodes this {@code EncodedNumber} to a {@code long} representation. See * {@link com.n1analytics.paillier.PaillierContext#decodeLong(EncodedNumber)} for details. * * @return the decoded number. * @throws ArithmeticException if this cannot be represented as a valid {@code long}. */ public long decodeLong() throws ArithmeticException { return context.decodeLong(this); } public BigDecimal decodeBigDecimal() throws ArithmeticException { return context.decodeBigDecimal(this); } /** * Decreases the exponent of this {@code EncodedNumber} to {@code newExp}, if {@code newExp} is less than * the current {@code exponent}. * See {@link com.n1analytics.paillier.PaillierContext#decreaseExponentTo(EncodedNumber, int)} for details. * * @param newExp the new exponent for the {@code EncodedNumber}, must be less than the current exponent. * @return an {@code EncodedNumber} which exponent is equal to {@code newExp}. */ public EncodedNumber decreaseExponentTo(int newExp) { return context.decreaseExponentTo(this, newExp); } /** * Encrypts this {@code EncodedNumber}. See * {@link com.n1analytics.paillier.PaillierContext#encrypt(EncodedNumber)} for details. * * @return the encrypted number. */ public EncryptedNumber encrypt() { return context.encrypt(this); } /** * Adds an {@code EncryptedNumber} to this {@code EncodedNumber}. See * {@link com.n1analytics.paillier.PaillierContext#add(EncodedNumber, EncryptedNumber)} for details. * * @param other {@code EncryptedNumber} to be added. * @return the addition result. */ public EncryptedNumber add(EncryptedNumber other) { return context.add(this, other); } /** * Adds another {@code EncodedNumber} to this {@code EncodedNumber}. See * {@link com.n1analytics.paillier.PaillierContext#add(EncodedNumber, EncodedNumber)} for details. * * @param other {@code EncodedNumber} to be added. * @return the addition result. */ public EncodedNumber add(EncodedNumber other) { return context.add(this, other); } /** * Adds a {@code BigInteger} to this {@code EncodedNumber}. * * @param other {@code EncodedNumber} to be added. * @return the addition result. */ public EncodedNumber add(BigInteger other) { return add(context.encode(other)); } /** * Adds a {@code double} to this {@code EncodedNumber}. * * @param other {@code double} to be added. * @return the addition result. */ public EncodedNumber add(double other) { return add(context.encode(other)); } /** * Adds a {@code long} to this {@code EncodedNumber}. * * @param other {@code long} to be added. * @return the addition result. */ public EncodedNumber add(long other) { return add(context.encode(other)); } /** * @return additive inverse of this {@code EncodedNumber}. */ public EncodedNumber additiveInverse() { return context.additiveInverse(this); } /** * Subtracts an {@code EncryptedNumber} from this {@code EncodedNumber}. * * @param other {@code EncryptedNumber} to be subtracted from this. * @return the subtraction result. */ public EncryptedNumber subtract(EncryptedNumber other) { return context.subtract(this, other); } /** * Subtracts another {@code EncodedNumber} from this {@code EncodedNumber}. * * @param other {@code EncodedNumber} to be subtracted from this. * @return the subtraction result. */ public EncodedNumber subtract(EncodedNumber other) { return context.subtract(this, other); } /** * Subtracts a {@code BigInteger} from this {@code EncodedNumber}. * * @param other {@code BigInteger} to be subtracted from this {@code EncodedNumber}. * @return the subtraction result. */ public EncodedNumber subtract(BigInteger other) { return subtract(context.encode(other)); } /** * Subtracts a {@code double} from this {@code EncodedNumber}. * * @param other {@code double} to be subtracted from this. * @return the subtraction result. */ public EncodedNumber subtract(double other) { return subtract(context.encode(other)); } /** * Subtracts a {@code long} from this {@code EncodedNumber}. * * @param other {@code long} to be subtracted from this. * @return the subtraction result. */ public EncodedNumber subtract(long other) { // NOTE it would be nice to do add(context.encode(-other)) however this // would fail if other == Long.MIN_VALUE since it has no // corresponding positive value. return subtract(context.encode(other)); } /** * Multiplies an {@code EncryptedNumber} with this {@code EncodedNumber}. * * @param other {@code EncryptedNumber} to be multiplied with. * @return the multiplication result. */ public EncryptedNumber multiply(EncryptedNumber other) { return context.multiply(this, other); } /** * Multiplies another {@code EncodedNumber} with this {@code EncodedNumber}. * * @param other {@code EncodedNumber} to be multiplied with. * @return the multiplication result. */ public EncodedNumber multiply(EncodedNumber other) { return context.multiply(this, other); } /** * Multiplies a {@code BigInteger} with this {@code EncodedNumber}. * * @param other {@code BigInteger} to be multiplied with. * @return the multiplication result. */ public EncodedNumber multiply(BigInteger other) { return multiply(context.encode(other)); } /** * Multiplies a {@code double} with this {@code EncodedNumber}. * * @param other {@code double} to be multiplied with. * @return the multiplication result. */ public EncodedNumber multiply(double other) { return multiply(context.encode(other)); } /** * Multiplies a {@code long} with this {@code EncodedNumber}. * * @param other {@code long} to be multiplied with. * @return the multiplication result. */ public EncodedNumber multiply(long other) { return multiply(context.encode(other)); } /** * Divides this {@code EncodedNumber} with a {@code double}. * * @param other {@code double} to divide this with. * @return the division result. */ public EncodedNumber divide(double other) { return multiply(context.encode(1.0 / other)); } /** * Divides this {@code EncodedNumber} with a {@code long}. * * @param other {@code long} to divide this with. * @return the division result. */ public EncodedNumber divide(long other) { return multiply(context.encode(1.0 / other)); } @Override public int hashCode() { return new HashChain().chain(context).chain(value).hashCode(); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o == null || o.getClass() != EncodedNumber.class) { return false; } EncodedNumber number = (EncodedNumber) o; return context.equals(number.context) && value.equals(number.value); } public boolean equals(EncodedNumber o) { return o == this || (o != null && context.equals(o.context) && value.equals(o.value)); } }
apache-2.0
aparo/scalajs-react-components
core/src/main/scala/chandu0101/scalajs/react/components/hljs/IHighlightResultBase.scala
243
package chandu0101.scalajs.react.components.hljs import scala.scalajs.js @js.native trait IHighlightResultBase extends js.Object { var language: String = js.native var relevance: Double = js.native var value: String = js.native }
apache-2.0
speedster-kiev/namecheap-php-sdk
src/Namecheap/examples/domains.ns.delete.php
673
<?php error_reporting(E_ALL | E_STRICT); ini_set('display_startup_errors', true); ini_set('display_errors', true); include_once '../Api.php'; try { $config = new \Namecheap\Config(); $config->apiUser('api-username') ->apiKey('api-key') ->clientIp('your-ip') ->sandbox(true); $command = Namecheap\Api::factory($config, 'domains.ns.delete'); $command->domainName('example1.com') ->nameserver('ns1.example1.com') ->dispatch(); } catch (\Exception $e) { die($e->getMessage()); } if ($command->status() == 'error') { die($command->errorMessage); } d($command); function d($value = array()) { echo '<pre>' . "\n"; print_r($value); die('</pre>' . "\n"); }
apache-2.0
jarekankowski/iosched
lib/src/main/java/com/google/samples/apps/iosched/io/model/Block.java
843
/* * Copyright 2014 Google Inc. 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. */ package com.google.samples.apps.iosched.io.model; public class Block { public String title; public String subtitle; public String start; public String end; public String type; public String kind; }
apache-2.0
sivakumar-kailasam/refactor-faster
src/main/com/google/errorprone/refaster/RefasterScanner.java
4820
/* * Copyright 2014 Google Inc. 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. */ package com.google.errorprone.refaster; import com.google.auto.value.AutoValue; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.DescriptionListener; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.DoWhileLoopTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; /** * Scanner that outputs suggested fixes generated by a {@code RefasterMatcher}. * * @author lowasser@google.com (Louis Wasserman) */ @AutoValue abstract class RefasterScanner<M extends TemplateMatch, T extends Template<M>> extends TreeScanner<Void, Context> { static <M extends TemplateMatch, T extends Template<M>> RefasterScanner<M, T> create( RefasterRule<M, T> rule, DescriptionListener listener) { return new AutoValue_RefasterScanner<>(rule, listener); } abstract RefasterRule<M, T> rule(); abstract DescriptionListener listener(); @Override public Void visitClass(ClassTree node, Context context) { Symbol sym = ASTHelpers.getSymbol(node); if (sym == null || !sym.getQualifiedName().contentEquals(rule().qualifiedTemplateClass())) { return super.visitClass(node, context); } else { return null; } } @Override public Void scan(Tree tree, Context context) { if (tree == null) { return null; } JCCompilationUnit compilationUnit = context.get(JCCompilationUnit.class); for (T beforeTemplate : rule().beforeTemplates()) { for (M match : beforeTemplate.match((JCTree) tree, context)) { if (rule().rejectMatchesWithComments()) { String matchContents = match.getRange(compilationUnit); if (matchContents.contains("//") || matchContents.contains("/*")) { continue; } } Fix fix; if (rule().afterTemplate() == null) { fix = SuggestedFix.delete(match.getLocation()); } else { fix = rule().afterTemplate().replace(match); } listener().onDescribed(new Description( match.getLocation(), rule().qualifiedTemplateClass(), fix, SeverityLevel.WARNING)); } } return super.scan(tree, context); } private static final SimpleTreeVisitor<Tree, Void> SKIP_PARENS = new SimpleTreeVisitor<Tree, Void>() { @Override public Tree visitParenthesized(ParenthesizedTree node, Void v) { return node.getExpression().accept(this, null); } @Override protected Tree defaultAction(Tree node, Void v) { return node; } }; /* * Matching on the parentheses surrounding the condition of an if, while, or do-while * is nonsensical, as those parentheses are obligatory and should never be changed. */ @Override public Void visitDoWhileLoop(DoWhileLoopTree node, Context context) { scan(node.getStatement(), context); scan(SKIP_PARENS.visit(node.getCondition(), null), context); return null; } @Override public Void visitWhileLoop(WhileLoopTree node, Context context) { scan(SKIP_PARENS.visit(node.getCondition(), null), context); scan(node.getStatement(), context); return null; } @Override public Void visitSynchronized(SynchronizedTree node, Context context) { scan(SKIP_PARENS.visit(node.getExpression(), null), context); scan(node.getBlock(), context); return null; } @Override public Void visitIf(IfTree node, Context context) { scan(SKIP_PARENS.visit(node.getCondition(), null), context); scan(node.getThenStatement(), context); scan(node.getElseStatement(), context); return null; } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-androidenterprise/v1/1.29.2/com/google/api/services/androidenterprise/model/ApprovalUrlInfo.java
2808
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.androidenterprise.model; /** * Information on an approval URL. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Google Play EMM API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class ApprovalUrlInfo extends com.google.api.client.json.GenericJson { /** * A URL that displays a product's permissions and that can also be used to approve the product * with the Products.approve call. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String approvalUrl; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * A URL that displays a product's permissions and that can also be used to approve the product * with the Products.approve call. * @return value or {@code null} for none */ public java.lang.String getApprovalUrl() { return approvalUrl; } /** * A URL that displays a product's permissions and that can also be used to approve the product * with the Products.approve call. * @param approvalUrl approvalUrl or {@code null} for none */ public ApprovalUrlInfo setApprovalUrl(java.lang.String approvalUrl) { this.approvalUrl = approvalUrl; return this; } /** * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * @param kind kind or {@code null} for none */ public ApprovalUrlInfo setKind(java.lang.String kind) { this.kind = kind; return this; } @Override public ApprovalUrlInfo set(String fieldName, Object value) { return (ApprovalUrlInfo) super.set(fieldName, value); } @Override public ApprovalUrlInfo clone() { return (ApprovalUrlInfo) super.clone(); } }
apache-2.0
MeoMix/StreamusChromeExtension
src/js/foreground/view/streamControlBar/previousButtonView.js
898
import {LayoutView} from 'marionette'; import previousButtonTemplate from 'template/streamControlBar/previousButton.hbs!'; import previousIconTemplate from 'template/icon/previousIcon_24.hbs!'; var PreviousButton = LayoutView.extend({ id: 'previousButton', className: 'button button--icon button--icon--primary button--large', template: previousButtonTemplate, templateHelpers: { previousIcon: previousIconTemplate }, events: { 'click': '_onClick' }, modelEvents: { 'change:enabled': '_onChangeEnabled' }, onRender: function() { this._setState(this.model.get('enabled')); }, _onClick: function() { this.model.tryDoTimeBasedPrevious(); }, _onChangeEnabled: function(model, enabled) { this._setState(enabled); }, _setState: function(enabled) { this.$el.toggleClass('is-disabled', !enabled); } }); export default PreviousButton;
apache-2.0
nugget/home-assistant
homeassistant/components/elkm1/sensor.py
7721
"""Support for control of ElkM1 sensors.""" from homeassistant.components.elkm1 import ( DOMAIN as ELK_DOMAIN, create_elk_entities, ElkEntity) DEPENDENCIES = [ELK_DOMAIN] async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Create the Elk-M1 sensor platform.""" if discovery_info is None: return elk = hass.data[ELK_DOMAIN]['elk'] entities = create_elk_entities( hass, elk.counters, 'counter', ElkCounter, []) entities = create_elk_entities( hass, elk.keypads, 'keypad', ElkKeypad, entities) entities = create_elk_entities( hass, [elk.panel], 'panel', ElkPanel, entities) entities = create_elk_entities( hass, elk.settings, 'setting', ElkSetting, entities) entities = create_elk_entities( hass, elk.zones, 'zone', ElkZone, entities) async_add_entities(entities, True) def temperature_to_state(temperature, undefined_temperature): """Convert temperature to a state.""" return temperature if temperature > undefined_temperature else None class ElkSensor(ElkEntity): """Base representation of Elk-M1 sensor.""" def __init__(self, element, elk, elk_data): """Initialize the base of all Elk sensors.""" super().__init__(element, elk, elk_data) self._state = None @property def state(self): """Return the state of the sensor.""" return self._state class ElkCounter(ElkSensor): """Representation of an Elk-M1 Counter.""" @property def icon(self): """Icon to use in the frontend.""" return 'mdi:numeric' def _element_changed(self, element, changeset): self._state = self._element.value class ElkKeypad(ElkSensor): """Representation of an Elk-M1 Keypad.""" @property def temperature_unit(self): """Return the temperature unit.""" return self._temperature_unit @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._temperature_unit @property def icon(self): """Icon to use in the frontend.""" return 'mdi:thermometer-lines' @property def device_state_attributes(self): """Attributes of the sensor.""" from elkm1_lib.util import username attrs = self.initial_attrs() attrs['area'] = self._element.area + 1 attrs['temperature'] = self._element.temperature attrs['last_user_time'] = self._element.last_user_time.isoformat() attrs['last_user'] = self._element.last_user + 1 attrs['code'] = self._element.code attrs['last_user_name'] = username(self._elk, self._element.last_user) attrs['last_keypress'] = self._element.last_keypress return attrs def _element_changed(self, element, changeset): self._state = temperature_to_state(self._element.temperature, -40) async def async_added_to_hass(self): """Register callback for ElkM1 changes and update entity state.""" await super().async_added_to_hass() self.hass.data[ELK_DOMAIN]['keypads'][ self._element.index] = self.entity_id class ElkPanel(ElkSensor): """Representation of an Elk-M1 Panel.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:home" @property def device_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs['system_trouble_status'] = self._element.system_trouble_status return attrs def _element_changed(self, element, changeset): if self._elk.is_connected(): self._state = 'Paused' if self._element.remote_programming_status \ else 'Connected' else: self._state = 'Disconnected' class ElkSetting(ElkSensor): """Representation of an Elk-M1 Setting.""" @property def icon(self): """Icon to use in the frontend.""" return 'mdi:numeric' def _element_changed(self, element, changeset): self._state = self._element.value @property def device_state_attributes(self): """Attributes of the sensor.""" from elkm1_lib.const import SettingFormat attrs = self.initial_attrs() attrs['value_format'] = SettingFormat( self._element.value_format).name.lower() return attrs class ElkZone(ElkSensor): """Representation of an Elk-M1 Zone.""" @property def icon(self): """Icon to use in the frontend.""" from elkm1_lib.const import ZoneType zone_icons = { ZoneType.FIRE_ALARM.value: 'fire', ZoneType.FIRE_VERIFIED.value: 'fire', ZoneType.FIRE_SUPERVISORY.value: 'fire', ZoneType.KEYFOB.value: 'key', ZoneType.NON_ALARM.value: 'alarm-off', ZoneType.MEDICAL_ALARM.value: 'medical-bag', ZoneType.POLICE_ALARM.value: 'alarm-light', ZoneType.POLICE_NO_INDICATION.value: 'alarm-light', ZoneType.KEY_MOMENTARY_ARM_DISARM.value: 'power', ZoneType.KEY_MOMENTARY_ARM_AWAY.value: 'power', ZoneType.KEY_MOMENTARY_ARM_STAY.value: 'power', ZoneType.KEY_MOMENTARY_DISARM.value: 'power', ZoneType.KEY_ON_OFF.value: 'toggle-switch', ZoneType.MUTE_AUDIBLES.value: 'volume-mute', ZoneType.POWER_SUPERVISORY.value: 'power-plug', ZoneType.TEMPERATURE.value: 'thermometer-lines', ZoneType.ANALOG_ZONE.value: 'speedometer', ZoneType.PHONE_KEY.value: 'phone-classic', ZoneType.INTERCOM_KEY.value: 'deskphone' } return 'mdi:{}'.format( zone_icons.get(self._element.definition, 'alarm-bell')) @property def device_state_attributes(self): """Attributes of the sensor.""" from elkm1_lib.const import ( ZoneLogicalStatus, ZonePhysicalStatus, ZoneType) attrs = self.initial_attrs() attrs['physical_status'] = ZonePhysicalStatus( self._element.physical_status).name.lower() attrs['logical_status'] = ZoneLogicalStatus( self._element.logical_status).name.lower() attrs['definition'] = ZoneType( self._element.definition).name.lower() attrs['area'] = self._element.area + 1 attrs['bypassed'] = self._element.bypassed attrs['triggered_alarm'] = self._element.triggered_alarm return attrs @property def temperature_unit(self): """Return the temperature unit.""" from elkm1_lib.const import ZoneType if self._element.definition == ZoneType.TEMPERATURE.value: return self._temperature_unit return None @property def unit_of_measurement(self): """Return the unit of measurement.""" from elkm1_lib.const import ZoneType if self._element.definition == ZoneType.TEMPERATURE.value: return self._temperature_unit if self._element.definition == ZoneType.ANALOG_ZONE.value: return 'V' return None def _element_changed(self, element, changeset): from elkm1_lib.const import ZoneLogicalStatus, ZoneType from elkm1_lib.util import pretty_const if self._element.definition == ZoneType.TEMPERATURE.value: self._state = temperature_to_state(self._element.temperature, -60) elif self._element.definition == ZoneType.ANALOG_ZONE.value: self._state = self._element.voltage else: self._state = pretty_const(ZoneLogicalStatus( self._element.logical_status).name)
apache-2.0
huihoo/olat
olat7.8/src/main/java/org/olat/presentation/portfolio/artefacts/run/details/FileArtefactDetailsController.java
8046
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) frentix GmbH<br> * http://www.frentix.com<br> * <p> */ package org.olat.presentation.portfolio.artefacts.run.details; import javax.servlet.http.HttpServletRequest; import org.olat.data.commons.vfs.OlatRelPathImpl; import org.olat.data.commons.vfs.VFSItem; import org.olat.data.commons.vfs.VFSLeaf; import org.olat.data.filebrowser.metadata.MetaInfo; import org.olat.data.portfolio.artefact.AbstractArtefact; import org.olat.data.portfolio.artefact.FileArtefact; import org.olat.lms.commons.filemetadata.FileMetadataInfoService; import org.olat.lms.commons.mediaresource.MediaResource; import org.olat.lms.commons.mediaresource.VFSMediaResource; import org.olat.lms.portfolio.EPFrontendManager; import org.olat.presentation.framework.core.UserRequest; import org.olat.presentation.framework.core.components.Component; import org.olat.presentation.framework.core.components.download.DownloadComponent; import org.olat.presentation.framework.core.components.link.Link; import org.olat.presentation.framework.core.components.link.LinkFactory; import org.olat.presentation.framework.core.components.panel.Panel; import org.olat.presentation.framework.core.components.velocity.VelocityContainer; import org.olat.presentation.framework.core.control.Controller; import org.olat.presentation.framework.core.control.WindowControl; import org.olat.presentation.framework.core.control.controller.BasicController; import org.olat.presentation.framework.core.control.generic.closablewrapper.CloseableCalloutWindowController; import org.olat.presentation.framework.core.control.generic.modal.DialogBoxController; import org.olat.presentation.framework.core.control.generic.modal.DialogBoxUIFactory; import org.olat.presentation.framework.dispatcher.mapper.Mapper; import org.olat.presentation.framework.dispatcher.mapper.MapperRegistry; import org.olat.presentation.portfolio.artefacts.collect.EPCreateFileArtefactStepForm00; import org.olat.system.event.Event; import org.olat.system.spring.CoreSpringFactory; /** * Description:<br> * show specific infos for FileArtefact allow to delete / upload a file * <P> * Initial Date: 08.10.2010 <br> * * @author Roman Haag, roman.haag@frentix.com, http://www.frentix.com */ public class FileArtefactDetailsController extends BasicController { private VelocityContainer vC; private final boolean readOnlyMode; MediaResource mr; private Link delLink; private DialogBoxController delDialog; private final FileArtefact fArtefact; private Controller fileUploadCtrl; private final EPFrontendManager ePFMgr; private Link uploadLink; private CloseableCalloutWindowController calloutCtrl; private final Panel viewPanel; public FileArtefactDetailsController(final UserRequest ureq, final WindowControl wControl, final AbstractArtefact artefact, final boolean readOnlyMode) { super(ureq, wControl); this.readOnlyMode = readOnlyMode; fArtefact = (FileArtefact) artefact; ePFMgr = (EPFrontendManager) CoreSpringFactory.getBean(EPFrontendManager.class); viewPanel = new Panel("empty"); initViewDependingOnFileExistance(ureq); putInitialPanel(viewPanel); } private void initViewDependingOnFileExistance(final UserRequest ureq) { final VFSItem file = ePFMgr.getArtefactContainer(fArtefact).resolve(fArtefact.getFilename()); if (file != null && file instanceof VFSLeaf) { initFileView(file, ureq); } else if (!readOnlyMode) { initUploadView(ureq); } } private void initFileView(final VFSItem file, final UserRequest ureq) { vC = createVelocityContainer("fileDetails"); FileMetadataInfoService metaInfoService = CoreSpringFactory.getBean(FileMetadataInfoService.class); final MetaInfo meta = metaInfoService.createMetaInfoFor((OlatRelPathImpl) file); vC.contextPut("meta", meta); final DownloadComponent downlC = new DownloadComponent("download", (VFSLeaf) file); vC.put("download", downlC); vC.contextPut("filename", fArtefact.getFilename()); // show a preview thumbnail if possible if (meta.isThumbnailAvailable()) { final VFSLeaf thumb = meta.getThumbnail(200, 200); if (thumb != null) { mr = new VFSMediaResource(thumb); } if (mr != null) { final String thumbMapper = MapperRegistry.getInstanceFor(ureq.getUserSession()).register(new Mapper() { @SuppressWarnings("unused") @Override public MediaResource handle(final String relPath, final HttpServletRequest request) { return mr; } }); vC.contextPut("thumbMapper", thumbMapper); } } if (!readOnlyMode) { // allow to delete delLink = LinkFactory.createLink("delete.file", vC, this); delLink.setUserObject(file); } viewPanel.setContent(vC); } @SuppressWarnings("unused") private void initUploadView(final UserRequest ureq) { vC = createVelocityContainer("fileDetailsUpload"); uploadLink = LinkFactory.createLink("upload.link", vC, this); viewPanel.setContent(vC); } private void popupUploadCallout(final UserRequest ureq) { removeAsListenerAndDispose(fileUploadCtrl); fileUploadCtrl = new EPCreateFileArtefactStepForm00(ureq, getWindowControl(), fArtefact); listenTo(fileUploadCtrl); removeAsListenerAndDispose(calloutCtrl); calloutCtrl = new CloseableCalloutWindowController(ureq, getWindowControl(), fileUploadCtrl.getInitialComponent(), uploadLink, fArtefact.getTitle(), true, null); calloutCtrl.addDisposableChildController(fileUploadCtrl); listenTo(calloutCtrl); calloutCtrl.activate(); } @SuppressWarnings("unused") @Override protected void event(final UserRequest ureq, final Component source, final Event event) { if (source == delLink) { delDialog = activateYesNoDialog(ureq, translate("delete.file"), translate("delete.dialog"), delDialog); delDialog.setUserObject(delLink.getUserObject()); } else if (source == uploadLink) { popupUploadCallout(ureq); } } /** */ @Override protected void event(final UserRequest ureq, final Controller source, final Event event) { if (source == delDialog && DialogBoxUIFactory.isYesEvent(event)) { final VFSItem artefactFile = (VFSItem) delDialog.getUserObject(); artefactFile.delete(); fArtefact.setFilename(""); ePFMgr.updateArtefact(fArtefact); initViewDependingOnFileExistance(ureq); } else if (source == fileUploadCtrl) { calloutCtrl.deactivate(); removeAsListenerAndDispose(calloutCtrl); ePFMgr.updateArtefact(fArtefact); initViewDependingOnFileExistance(ureq); } else if (source == calloutCtrl && event.equals(CloseableCalloutWindowController.CLOSE_WINDOW_EVENT)) { removeAsListenerAndDispose(calloutCtrl); calloutCtrl = null; } } @Override protected void doDispose() { // nothing } }
apache-2.0
coding0011/elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/rest/action/RestActivateWatchAction.java
4724
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.watcher.rest.action; import org.apache.logging.log4j.LogManager; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.BytesRestResponse; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.RestResponse; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.rest.action.RestBuilderListener; import org.elasticsearch.xpack.core.watcher.support.xcontent.WatcherParams; import org.elasticsearch.xpack.core.watcher.transport.actions.activate.ActivateWatchAction; import org.elasticsearch.xpack.core.watcher.transport.actions.activate.ActivateWatchRequest; import org.elasticsearch.xpack.core.watcher.transport.actions.activate.ActivateWatchResponse; import org.elasticsearch.xpack.core.watcher.watch.WatchField; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestRequest.Method.PUT; /** * The rest action to de/activate a watch */ public class RestActivateWatchAction extends BaseRestHandler { private static final DeprecationLogger deprecationLogger = new DeprecationLogger(LogManager.getLogger(RestActivateWatchAction.class)); public RestActivateWatchAction(RestController controller) { // TODO: remove deprecated endpoint in 8.0.0 controller.registerWithDeprecatedHandler( POST, "/_watcher/watch/{id}/_activate", this, POST, "/_xpack/watcher/watch/{id}/_activate", deprecationLogger); controller.registerWithDeprecatedHandler( PUT, "/_watcher/watch/{id}/_activate", this, PUT, "/_xpack/watcher/watch/{id}/_activate", deprecationLogger); final DeactivateRestHandler deactivateRestHandler = new DeactivateRestHandler(); controller.registerWithDeprecatedHandler( POST, "/_watcher/watch/{id}/_deactivate", deactivateRestHandler, POST, "/_xpack/watcher/watch/{id}/_deactivate", deprecationLogger); controller.registerWithDeprecatedHandler( PUT, "/_watcher/watch/{id}/_deactivate", deactivateRestHandler, PUT, "/_xpack/watcher/watch/{id}/_deactivate", deprecationLogger); } @Override public String getName() { return "watcher_activate_watch"; } @Override public RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) { String watchId = request.param("id"); return channel -> client.execute(ActivateWatchAction.INSTANCE, new ActivateWatchRequest(watchId, true), new RestBuilderListener<ActivateWatchResponse>(channel) { @Override public RestResponse buildResponse(ActivateWatchResponse response, XContentBuilder builder) throws Exception { return new BytesRestResponse(RestStatus.OK, builder.startObject() .field(WatchField.STATUS.getPreferredName(), response.getStatus(), WatcherParams.HIDE_SECRETS) .endObject()); } }); } private static class DeactivateRestHandler extends BaseRestHandler { DeactivateRestHandler() { } @Override public String getName() { return "watcher_deactivate_watch"; } @Override public RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) { String watchId = request.param("id"); return channel -> client.execute(ActivateWatchAction.INSTANCE, new ActivateWatchRequest(watchId, false), new RestBuilderListener<ActivateWatchResponse>(channel) { @Override public RestResponse buildResponse(ActivateWatchResponse response, XContentBuilder builder) throws Exception { return new BytesRestResponse(RestStatus.OK, builder.startObject() .field(WatchField.STATUS.getPreferredName(), response.getStatus(), WatcherParams.HIDE_SECRETS) .endObject()); } }); } } }
apache-2.0
linqiangl/compatibility-detector
src/detectors/mouse_enter_leave.js
4046
/** * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @bug https://code.google.com/p/compatibility-detector/issues/detail?id=14 * WontFix */ addScriptToInject(function() { chrome_comp.CompDetect.declareDetector( 'mouse_enter_leave', chrome_comp.CompDetect.ScanDomBaseDetector, function constructor(rootNode) { var This = this; var enterFlag = false; var leaveFlag = false; this.hookOverHandler_ = function(oldValue, newValue, reason) { if (reason == 'set') { enterFlag=true; } }; //When onmouseenter and onmouseover same time bound , //that the author considers the problem this.hookEnterHandler_ = function(oldValue, newValue, reason) { if (reason == 'set' && enterCounter == true) This.addProblem('BT9017', { nodes: [this], needsStack: true }); return newValue; }; this.hookOutHandler_ = function(oldValue, newValue, reason) { if (reason == 'set') { leaveFlag=true; } }; //When onmouseout and onmouseleave same time bound , //that the author considers the problem this.hookLeaveHandler_ = function(oldValue, newValue, reason) { if (reason == 'set' && leaveFlag == true) This.addProblem('BT9017', { nodes: [this], needsStack: true }); return newValue; }; enterFlag = false; leaveFlag = false; }, function checkNode(node, context) { if (Node.ELEMENT_NODE != node.nodeType) return; //Increase the filter conditions , When the elements //of the display: none ,no problem. var display = window.getComputedStyle(node, null).display; //Increase the filter conditions , When the elements //of the visibility: hidden ,no problem. var visibility = window.getComputedStyle(node, null).visibility; if (display == 'none' || visibility == 'hidden') return; //Increase the filter conditions, when onmouseenter and onmouseover exist, //that the author considers the problem if (node.hasAttribute('onmouseenter') && node.hasAttribute('onmouseover')) return; //Increase the filter conditions, when onmouseleave and onmouseout exist, //that the author considers the problem else if (node.hasAttribute('onmouseleave') && node.hasAttribute('onmouseout')) return; if (node.hasAttribute('onmouseenter') || node.hasAttribute('onmouseleave')) this.addProblem('BT9017', [node]); }, function setUp() { //add onmouseover hook of register chrome_comp.CompDetect.registerSimplePropertyHook( Element.prototype, 'onmouseover', this.hookOverHandler_); chrome_comp.CompDetect.registerSimplePropertyHook( Element.prototype, 'onmouseenter', this.hookEnterHandler_); //add onmouseout hook of register chrome_comp.CompDetect.registerSimplePropertyHook( Element.prototype, 'onmouseout', this.hookOutHandler_); chrome_comp.CompDetect.registerSimplePropertyHook( Element.prototype, 'onmouseleave', this.hookLeaveHandler_); }, function cleanUp() { //add onmouseover hook of unregister chrome_comp.CompDetect.unregisterSimplePropertyHook( Element.prototype, 'onmouseover', this.hookOverHandler_); chrome_comp.CompDetect.unregisterSimplePropertyHook( Element.prototype, 'onmouseenter', this.hookEnterHandler_); //add onmouseout hook of unregister chrome_comp.CompDetect.unregisterSimplePropertyHook( Element.prototype, 'onmouseout', this.hookOutHandler_); chrome_comp.CompDetect.unregisterSimplePropertyHook( Element.prototype, 'onmouseleave', this.hookLeaveHandler_); } ); // declareDetector });
apache-2.0
Lawouach/weave
nameserver/mdns_lookup.go
1026
package nameserver import ( "github.com/miekg/dns" . "github.com/zettio/weave/common" "net" ) func mdnsLookup(client *MDNSClient, name string, qtype uint16) (*Response, error) { channel := make(chan *Response) client.SendQuery(name, qtype, channel) for resp := range channel { if err := resp.Err; err != nil { Debug.Printf("[mdns] Error for query type %s name %s: %s", dns.TypeToString[qtype], name, err) return nil, err } else { Debug.Printf("[mdns] Got response name for query type %s name %s: name %s, addr %s", dns.TypeToString[qtype], name, resp.Name, resp.Addr) return resp, nil } } return nil, LookupError(name) } func (client *MDNSClient) LookupName(name string) (net.IP, error) { if r, e := mdnsLookup(client, name, dns.TypeA); r != nil { return r.Addr, nil } else { return nil, e } } func (client *MDNSClient) LookupInaddr(inaddr string) (string, error) { if r, e := mdnsLookup(client, inaddr, dns.TypePTR); r != nil { return r.Name, nil } else { return "", e } }
apache-2.0
apache/solr
solr/modules/analytics/src/java/org/apache/solr/analytics/stream/reservation/read/FloatCheckedDataReader.java
1297
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.analytics.stream.reservation.read; import java.io.DataInput; import java.io.IOException; import org.apache.solr.analytics.util.function.FloatConsumer; public class FloatCheckedDataReader extends ReductionCheckedDataReader<FloatConsumer> { public FloatCheckedDataReader(DataInput inputStream, FloatConsumer applier) { super(inputStream, applier); } @Override public void checkedRead() throws IOException { applier.accept(inputStream.readFloat()); } }
apache-2.0
philips/shortbread
Godeps/_workspace/src/code.google.com/p/go.crypto/ssh/agent/server.go
4510
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent import ( "crypto/rsa" "encoding/binary" "fmt" "io" "log" "math/big" "github.com/coreos/shortbread/Godeps/_workspace/src/code.google.com/p/go.crypto/ssh" ) // Server wraps an Agent and uses it to implement the agent side of // the SSH-agent, wire protocol. type server struct { agent Agent } func (s *server) processRequestBytes(reqData []byte) []byte { rep, err := s.processRequest(reqData) if err != nil { if err != errLocked { // TODO(hanwen): provide better logging interface? log.Printf("agent %d: %v", reqData[0], err) } return []byte{agentFailure} } if err == nil && rep == nil { return []byte{agentSuccess} } return ssh.Marshal(rep) } func marshalKey(k *Key) []byte { var record struct { Blob []byte Comment string } record.Blob = k.Marshal() record.Comment = k.Comment return ssh.Marshal(&record) } type agentV1IdentityMsg struct { Numkeys uint32 `sshtype:"2"` } type agentRemoveIdentityMsg struct { KeyBlob []byte `sshtype:"18"` } type agentLockMsg struct { Passphrase []byte `sshtype:"22"` } type agentUnlockMsg struct { Passphrase []byte `sshtype:"23"` } func (s *server) processRequest(data []byte) (interface{}, error) { switch data[0] { case agentRequestV1Identities: return &agentV1IdentityMsg{0}, nil case agentRemoveIdentity: var req agentRemoveIdentityMsg if err := ssh.Unmarshal(data, &req); err != nil { return nil, err } var wk wireKey if err := ssh.Unmarshal(req.KeyBlob, &wk); err != nil { return nil, err } return nil, s.agent.Remove(&Key{Format: wk.Format, Blob: req.KeyBlob}) case agentRemoveAllIdentities: return nil, s.agent.RemoveAll() case agentLock: var req agentLockMsg if err := ssh.Unmarshal(data, &req); err != nil { return nil, err } return nil, s.agent.Lock(req.Passphrase) case agentUnlock: var req agentLockMsg if err := ssh.Unmarshal(data, &req); err != nil { return nil, err } return nil, s.agent.Unlock(req.Passphrase) case agentSignRequest: var req signRequestAgentMsg if err := ssh.Unmarshal(data, &req); err != nil { return nil, err } var wk wireKey if err := ssh.Unmarshal(req.KeyBlob, &wk); err != nil { return nil, err } k := &Key{ Format: wk.Format, Blob: req.KeyBlob, } sig, err := s.agent.Sign(k, req.Data) // TODO(hanwen): flags. if err != nil { return nil, err } return &signResponseAgentMsg{SigBlob: ssh.Marshal(sig)}, nil case agentRequestIdentities: keys, err := s.agent.List() if err != nil { return nil, err } rep := identitiesAnswerAgentMsg{ NumKeys: uint32(len(keys)), } for _, k := range keys { rep.Keys = append(rep.Keys, marshalKey(k)...) } return rep, nil case agentAddIdentity: return nil, s.insertIdentity(data) } return nil, fmt.Errorf("unknown opcode %d", data[0]) } func (s *server) insertIdentity(req []byte) error { var record struct { Type string `sshtype:"17"` Rest []byte `ssh:"rest"` } if err := ssh.Unmarshal(req, &record); err != nil { return err } switch record.Type { case ssh.KeyAlgoRSA: var k rsaKeyMsg if err := ssh.Unmarshal(req, &k); err != nil { return err } priv := rsa.PrivateKey{ PublicKey: rsa.PublicKey{ E: int(k.E.Int64()), N: k.N, }, D: k.D, Primes: []*big.Int{k.P, k.Q}, } priv.Precompute() return s.agent.Add(&priv, nil, k.Comments) } return fmt.Errorf("not implemented: %s", record.Type) } // ServeAgent serves the agent protocol on the given connection. It // returns when an I/O error occurs. func ServeAgent(agent Agent, c io.ReadWriter) error { s := &server{agent} var length [4]byte for { if _, err := io.ReadFull(c, length[:]); err != nil { return err } l := binary.BigEndian.Uint32(length[:]) if l > maxAgentResponseBytes { // We also cap requests. return fmt.Errorf("agent: request too large: %d", l) } req := make([]byte, l) if _, err := io.ReadFull(c, req); err != nil { return err } repData := s.processRequestBytes(req) if len(repData) > maxAgentResponseBytes { return fmt.Errorf("agent: reply too large: %d bytes", len(repData)) } binary.BigEndian.PutUint32(length[:], uint32(len(repData))) if _, err := c.Write(length[:]); err != nil { return err } if _, err := c.Write(repData); err != nil { return err } } }
apache-2.0
sergecodd/FireFox-OS
B2G/gecko/widget/gtk2/nsScreenGtk.cpp
4454
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsScreenGtk.h" #include <gdk/gdk.h> #ifdef MOZ_X11 #include <gdk/gdkx.h> #include <X11/Xatom.h> #endif #include <gtk/gtk.h> nsScreenGtk :: nsScreenGtk ( ) : mScreenNum(0), mRect(0, 0, 0, 0), mAvailRect(0, 0, 0, 0) { } nsScreenGtk :: ~nsScreenGtk() { } NS_IMETHODIMP nsScreenGtk :: GetRect(int32_t *outLeft, int32_t *outTop, int32_t *outWidth, int32_t *outHeight) { *outLeft = mRect.x; *outTop = mRect.y; *outWidth = mRect.width; *outHeight = mRect.height; return NS_OK; } // GetRect NS_IMETHODIMP nsScreenGtk :: GetAvailRect(int32_t *outLeft, int32_t *outTop, int32_t *outWidth, int32_t *outHeight) { *outLeft = mAvailRect.x; *outTop = mAvailRect.y; *outWidth = mAvailRect.width; *outHeight = mAvailRect.height; return NS_OK; } // GetAvailRect NS_IMETHODIMP nsScreenGtk :: GetPixelDepth(int32_t *aPixelDepth) { GdkVisual * visual = gdk_screen_get_system_visual(gdk_screen_get_default()); *aPixelDepth = gdk_visual_get_depth(visual); return NS_OK; } // GetPixelDepth NS_IMETHODIMP nsScreenGtk :: GetColorDepth(int32_t *aColorDepth) { return GetPixelDepth ( aColorDepth ); } // GetColorDepth void nsScreenGtk :: Init (GdkWindow *aRootWindow) { // We listen for configure events on the root window to pick up // changes to this rect. We could listen for "size_changed" signals // on the default screen to do this, except that doesn't work with // versions of GDK predating the GdkScreen object. See bug 256646. mAvailRect = mRect = nsIntRect(0, 0, gdk_screen_width(), gdk_screen_height()); #ifdef MOZ_X11 // We need to account for the taskbar, etc in the available rect. // See http://freedesktop.org/Standards/wm-spec/index.html#id2767771 // XXX do we care about _NET_WM_STRUT_PARTIAL? That will // add much more complexity to the code here (our screen // could have a non-rectangular shape), but should // lead to greater accuracy. long *workareas; GdkAtom type_returned; int format_returned; int length_returned; #if GTK_CHECK_VERSION(2,0,0) GdkAtom cardinal_atom = gdk_x11_xatom_to_atom(XA_CARDINAL); #else GdkAtom cardinal_atom = (GdkAtom) XA_CARDINAL; #endif gdk_error_trap_push(); // gdk_property_get uses (length + 3) / 4, hence G_MAXLONG - 3 here. if (!gdk_property_get(aRootWindow, gdk_atom_intern ("_NET_WORKAREA", FALSE), cardinal_atom, 0, G_MAXLONG - 3, FALSE, &type_returned, &format_returned, &length_returned, (guchar **) &workareas)) { // This window manager doesn't support the freedesktop standard. // Nothing we can do about it, so assume full screen size. return; } // Flush the X queue to catch errors now. gdk_flush(); if (!gdk_error_trap_pop() && type_returned == cardinal_atom && length_returned && (length_returned % 4) == 0 && format_returned == 32) { int num_items = length_returned / sizeof(long); for (int i = 0; i < num_items; i += 4) { nsIntRect workarea(workareas[i], workareas[i + 1], workareas[i + 2], workareas[i + 3]); if (!mRect.Contains(workarea)) { // Note that we hit this when processing screen size changes, // since we'll get the configure event before the toolbars have // been moved. We'll end up cleaning this up when we get the // change notification to the _NET_WORKAREA property. However, // we still want to listen to both, so we'll handle changes // properly for desktop environments that don't set the // _NET_WORKAREA property. NS_WARNING("Invalid bounds"); continue; } mAvailRect.IntersectRect(mAvailRect, workarea); } } g_free (workareas); #endif } #ifdef MOZ_X11 void nsScreenGtk :: Init (XineramaScreenInfo *aScreenInfo) { nsIntRect xineRect(aScreenInfo->x_org, aScreenInfo->y_org, aScreenInfo->width, aScreenInfo->height); mScreenNum = aScreenInfo->screen_number; mAvailRect = mRect = xineRect; } #endif
apache-2.0
neozhu/WebFormsScaffolding
Samples.CS/3_Associations/Products/Default.aspx.cs
776
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.Entity; using Samples.Associations; using Samples.Models; namespace Samples._3_Associations.Products { public partial class Default : System.Web.UI.Page { protected Samples.Models.ApplicationDbContext _db = new Samples.Models.ApplicationDbContext(); protected void Page_Load(object sender, EventArgs e) { } // Model binding method to get List of Product entries // USAGE: <asp:ListView SelectMethod="GetData"> public IQueryable<Samples.Associations.Product> GetData() { return _db.Products.Include(m => m.Category); } } }
apache-2.0
rsimha-amp/amphtml
extensions/amp-story-dev-tools/0.1/amp-story-dev-tools-tab-debug.js
7804
/** * Copyright 2020 The AMP HTML Authors. 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 {Services} from '#service'; import {createElementWithAttributes} from '#core/dom'; import {htmlFor} from '#core/dom/static-template'; import {loadScript} from '../../../src/validator-integration'; import {urls} from '../../../src/config'; import {user, userAssert} from '../../../src/log'; /** * Creates a tab content, will be deleted when the tabs get implemented. * @param {!Window} win * @param {string} storyUrl * @return {!Element} the layout */ export function createTabDebugElement(win, storyUrl) { const element = win.document.createElement('amp-story-dev-tools-tab-debug'); element.setAttribute('data-story-url', storyUrl); return element; } /** * Creates the success message when there are no errors. * @param {!ELement} element * @return {!Element} the layout */ const buildSuccessMessageTemplate = (element) => { const html = htmlFor(element); return html`<div class="i-amphtml-story-dev-tools-debug-success"> <div class="i-amphtml-story-dev-tools-debug-success-image"></div> <h1 class="i-amphtml-story-dev-tools-debug-success-message"> Great Job!<br />No issues found </h1> </div>`; }; /** * Returns a "failed" or "passed" icon from the status * @param {!Element} element * @param {boolean} statusPassed * @return {!Element} */ function buildStatusIcon(element, statusPassed) { const html = htmlFor(element); const iconEl = html`<div class="i-amphtml-story-dev-tools-log-status-icon" ></div>`; iconEl.classList.add( 'i-amphtml-story-dev-tools-log-status-icon-' + (statusPassed ? 'passed' : 'failed') ); return iconEl; } const buildLogMessageTemplate = (element) => { const html = htmlFor(element); return html`<div class="i-amphtml-story-dev-tools-log-message"> <div> <span class="i-amphtml-story-dev-tools-log-type"></span> <span> at </span> <span class="i-amphtml-story-dev-tools-log-position"></span> </div> <span class="i-amphtml-story-dev-tools-log-description"></span> <a class="i-amphtml-story-dev-tools-log-spec" target="_blank">Learn more</a> <pre class="i-amphtml-story-dev-tools-log-code"></pre> </div>`; }; /** @const {string} */ const TAG = 'AMP_STORY_DEV_TOOLS_DEBUG'; export class AmpStoryDevToolsTabDebug extends AMP.BaseElement { /** @override @nocollapse */ static prerenderAllowed() { return false; } /** @param {!Element} element */ constructor(element) { super(element); /** @private {string} */ this.storyUrl_ = ''; /** @private {!Array} */ this.errorList_ = []; } /** @override */ isLayoutSupported() { return true; } /** @override */ buildCallback() { this.storyUrl_ = this.element.getAttribute('data-story-url'); this.element.classList.add('i-amphtml-story-dev-tools-tab'); return loadScript(this.element.ownerDocument, `${urls.cdn}/v0/validator.js`) .then(() => this.validateUrl_(/* global amp: false */ amp.validator, this.storyUrl_) ) .then((errorList) => { this.errorList_ = errorList; this.updateDebugTabIcon(errorList); }); } /** @override */ layoutCallback() { return this.buildDebugContent_(); } /** * Validates a URL input, showing the errors on the screen. * * @private * @param {!Validator} validator * @param {string} url * @return {!Promise<Array>} promise of list of errors */ validateUrl_(validator, url) { return Services.xhrFor(this.win) .fetchText(url) .then((response) => { userAssert(response.ok, 'Invalid story url'); return response.text(); }) .then((html) => { const htmlLines = html.split('\n'); const validationResult = validator.validateString(html); return validationResult.errors.map((error) => { error.htmlLines = htmlLines.slice(error.line - 2, error.line + 3); error.message = validator.renderErrorMessage(error); return error; }); }) .catch((error) => { user().error(TAG, error); }); } /** * @private * @return {!Promise} */ buildDebugContent_() { const debugContainer = this.errorList_.length ? this.createErrorsList_() : buildSuccessMessageTemplate(this.element); debugContainer.prepend(this.buildDebugTitle_(this.errorList_.length)); this.mutateElement(() => { this.element.textContent = ''; this.element.appendChild(debugContainer); }); } /** * * @private * @param {number} errorCount * @return {!Element} */ buildDebugTitle_(errorCount) { const statusIcon = buildStatusIcon(this.element, errorCount == 0); statusIcon.classList.add('i-amphtml-story-dev-tools-log-status-icon'); const title = htmlFor( this.element )`<div class="i-amphtml-story-dev-tools-log-status-title"></div>`; const statusText = htmlFor(this.element)`<span></span>`; statusText.textContent = errorCount ? `Failed - ${errorCount} errors` : 'Passed'; title.appendChild(statusIcon); title.appendChild(statusText); return title; } /** * Updates the icon (passed / failed) next to the debug tab selector. * @param {!Array} errorList */ updateDebugTabIcon(errorList) { const debugTabSelector = this.win.document.querySelector('[data-tab="Debug"]'); if (!debugTabSelector) { return; } let statusIcon; if (errorList.length) { statusIcon = createElementWithAttributes( this.element.ownerDocument, 'span', { 'class': 'i-amphtml-story-dev-tools-log-status-number-failed', } ); statusIcon.textContent = errorList.length; } else { statusIcon = buildStatusIcon(this.element, true); } this.mutateElement(() => debugTabSelector.appendChild(statusIcon)); } /** * @private * @return {!Element} */ createErrorsList_() { const debugContainer = this.element.ownerDocument.createElement('div'); this.errorList_.forEach((content) => { const logEl = buildLogMessageTemplate(this.element); logEl.querySelector('.i-amphtml-story-dev-tools-log-type').textContent = content.code; const codeEl = logEl.querySelector('.i-amphtml-story-dev-tools-log-code'); content.htmlLines.forEach((l, i) => { const lineEl = this.element.ownerDocument.createElement('span'); lineEl.classList.add('i-amphtml-story-dev-tools-log-code-line'); lineEl.textContent = (i + content.line - 1).toString() + '|' + l; codeEl.appendChild(lineEl); }); logEl.querySelector( '.i-amphtml-story-dev-tools-log-position' ).textContent = `${content.line}:${content.col}`; logEl.querySelector( '.i-amphtml-story-dev-tools-log-description' ).textContent = content.message; const specUrlElement = logEl.querySelector( '.i-amphtml-story-dev-tools-log-spec' ); if (content.specUrl) { specUrlElement.href = content.specUrl; } else { specUrlElement.remove(); } debugContainer.appendChild(logEl); }); return debugContainer; } }
apache-2.0
stevem999/gocd
server/src/test-fast/java/com/thoughtworks/go/config/update/RoleConfigCreateCommandTest.java
3489
/* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.config.update; import com.thoughtworks.go.config.BasicCruiseConfig; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.PluginRoleConfig; import com.thoughtworks.go.helper.GoConfigMother; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.service.GoConfigService; import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RoleConfigCreateCommandTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void currentUserShouldBeAnAdminToAddRole() throws Exception { GoConfigService goConfigService = mock(GoConfigService.class); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); Username viewUser = mock(Username.class); when(goConfigService.isUserAdmin(viewUser)).thenReturn(false); RoleConfigCreateCommand command = new RoleConfigCreateCommand(goConfigService, null, viewUser, result); assertFalse(command.canContinue(null)); assertFalse(result.isSuccessful()); assertThat(result.httpCode(), is(401)); } @Test public void update_shouldAddPluginRoleConfigToRoles() throws Exception { BasicCruiseConfig cruiseConfig = GoConfigMother.defaultCruiseConfig(); PluginRoleConfig role = new PluginRoleConfig("blackbird", "ldap"); RoleConfigCreateCommand command = new RoleConfigCreateCommand(null, role, null, null); command.update(cruiseConfig); assertThat(cruiseConfig.server().security().getRoles().findByName(new CaseInsensitiveString("blackbird")), equalTo(role)); } @Test public void isValid_shouldSkipUpdatedRoleValidation() throws Exception { PluginRoleConfig pluginRoleConfig = new PluginRoleConfig(null, "ldap"); RoleConfigCreateCommand command = new RoleConfigCreateCommand(null, pluginRoleConfig, null, null); assertFalse(command.isValid(GoConfigMother.defaultCruiseConfig())); assertThat(pluginRoleConfig.errors().size(), is(2)); assertThat(pluginRoleConfig.errors().get("name").get(0), is("Invalid role name name 'null'. This must be " + "alphanumeric and can contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.")); assertThat(pluginRoleConfig.errors().get("authConfigId").get(0), is("No such security auth configuration present for id: `ldap`")); } }
apache-2.0
kuFEAR/crest
core/src/main/java/org/codegist/crest/param/DefaultCookieParamProcessor.java
1700
/* * Copyright 2011 CodeGist.org * * 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. * * =================================================================== * * More information at http://www.codegist.org. */ package org.codegist.crest.param; import java.nio.charset.Charset; import java.util.Collections; import java.util.List; import static java.util.Collections.singletonList; import static org.codegist.common.lang.Strings.isBlank; import static org.codegist.crest.util.Pairs.join; import static org.codegist.crest.util.Pairs.toPreEncodedPair; /** * @author laurent.gilles@codegist.org */ class DefaultCookieParamProcessor extends DefaultParamProcessor { static final ParamProcessor INSTANCE = new DefaultCookieParamProcessor(); @Override public List<EncodedPair> process(Param param, Charset charset, boolean encodeIfNeeded) throws Exception { List<EncodedPair> pairs = super.process(param, charset, encodeIfNeeded); String cookie = join(pairs, ','); if(isBlank(cookie)) { return Collections.emptyList(); } return singletonList(toPreEncodedPair("Cookie", cookie)); } }
apache-2.0
barnyard/p2p-core
src/test/java/com/bt/pi/core/past/content/DhtContentTypeTest.java
171
package com.bt.pi.core.past.content; import org.junit.Test; public class DhtContentTypeTest { @Test public void create() { new DhtContentType(); } }
apache-2.0
ernestp/consulo
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemResolveProjectTask.java
3217
package com.intellij.openapi.externalSystem.service.internal; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.externalSystem.model.DataNode; import com.intellij.openapi.externalSystem.model.ProjectSystemId; import com.intellij.openapi.externalSystem.model.project.ProjectData; import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType; import com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager; import com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolver; import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.concurrent.atomic.AtomicReference; /** * Thread-safe. * * @author Denis Zhdanov * @since 1/24/12 7:21 AM */ public class ExternalSystemResolveProjectTask extends AbstractExternalSystemTask { private final AtomicReference<DataNode<ProjectData>> myExternalProject = new AtomicReference<DataNode<ProjectData>>(); @NotNull private final String myProjectPath; private final boolean myIsPreviewMode; public ExternalSystemResolveProjectTask(@NotNull ProjectSystemId externalSystemId, @NotNull Project project, @NotNull String projectPath, boolean isPreviewMode) { super(externalSystemId, ExternalSystemTaskType.RESOLVE_PROJECT, project, projectPath); myProjectPath = projectPath; myIsPreviewMode = isPreviewMode; } @SuppressWarnings("unchecked") protected void doExecute() throws Exception { final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class); Project ideProject = getIdeProject(); RemoteExternalSystemProjectResolver resolver = manager.getFacade(ideProject, myProjectPath, getExternalSystemId()).getResolver(); ExternalSystemExecutionSettings settings = ExternalSystemApiUtil.getExecutionSettings(ideProject, myProjectPath, getExternalSystemId()); DataNode<ProjectData> project = resolver.resolveProjectInfo(getId(), myProjectPath, myIsPreviewMode, settings); if (project == null) { return; } myExternalProject.set(project); } protected boolean doCancel() throws Exception { final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class); Project ideProject = getIdeProject(); RemoteExternalSystemProjectResolver resolver = manager.getFacade(ideProject, myProjectPath, getExternalSystemId()).getResolver(); return resolver.cancelTask(getId()); } @Nullable public DataNode<ProjectData> getExternalProject() { return myExternalProject.get(); } @Override @NotNull protected String wrapProgressText(@NotNull String text) { return ExternalSystemBundle.message("progress.update.text", getExternalSystemId().getReadableName(), text); } }
apache-2.0
WDAqua/openQA
openqa.engine/src/main/java/org/aksw/openqa/component/PluginProcessProvider.java
2474
package org.aksw.openqa.component; import java.util.ArrayList; import java.util.List; import org.aksw.openqa.component.context.IContext; import org.aksw.openqa.component.object.IParams; import org.aksw.openqa.component.object.IResult; import org.aksw.openqa.component.object.Result; import org.aksw.openqa.component.providers.impl.ServiceProvider; import org.apache.log4j.Logger; public class PluginProcessProvider<C extends IPluginProcess, F extends IPluginFactorySpi<C>> extends AbstractPluginProvider<C, F> implements IProcess { private static Logger logger = Logger.getLogger(PluginProcessProvider.class); public PluginProcessProvider(Class<F> clazz, List<? extends ClassLoader> classLoaders, ServiceProvider serviceProvider) { super(clazz, classLoaders, serviceProvider); } public PluginProcessProvider() { } protected List<IResult> process(List<? extends IParams> arguments, List<C> components, ServiceProvider serviceProvider, IContext context) { List<IResult> results = new ArrayList<IResult>(); boolean processed = false; for (C component : components) { // if the component is activated and can process the argument List<? extends IParams> canProcessArguments = getArguments(arguments, component); if(component.isActive() && canProcessArguments != null) { processed = true; try { results.addAll(component.process(canProcessArguments, serviceProvider, context)); // process the token } catch (Exception e) { logger.error("ProcessProvider exception", e); } catch (Error e) { logger.error("ProcessProvider error", e); } } } // if is no processed, return the token themselves if(!processed) { for(IParams token : arguments) { Result result = new Result(token.getParameters(), token, this); results.add(result); // return } } return results; } public List<? extends IParams> getArguments(List<? extends IParams> arguments, C component) { List<IParams> componentArguments = null; for(IParams argument: arguments) { if(component.canProcess(argument)) { if(componentArguments == null) componentArguments = new ArrayList<IParams>(); componentArguments.add(argument); } } return componentArguments; } public List<IResult> process(List<? extends IParams> arguments, ServiceProvider services, IContext context) throws Exception { return process(arguments, list(), services, context); } }
apache-2.0
cloudnautique/cloud-cattle
code/iaas/agent-instance/src/main/java/io/cattle/platform/agent/instance/service/AgentInstanceManager.java
643
package io.cattle.platform.agent.instance.service; import io.cattle.platform.core.model.Agent; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.NetworkServiceProvider; import io.cattle.platform.core.model.Nic; import java.util.List; import java.util.Map; public interface AgentInstanceManager { List<? extends Agent> getAgents(NetworkServiceProvider provider); Map<NetworkServiceProvider,Instance> getAgentInstances(Nic clientNic); NetworkServiceInfo getNetworkService(Instance instance, String kind, boolean waitForStart); List<? extends Nic> getNicsFromResource(Object resource); }
apache-2.0
crazycode/weixin-java-tools
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpBaseAPITest.java
1069
package me.chanjar.weixin.mp.api; import com.google.inject.Inject; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.api.test.ApiTestModule; import org.apache.commons.lang3.StringUtils; import org.testng.*; import org.testng.annotations.*; /** * 基础API测试 * * @author chanjarster */ @Test(groups = "baseAPI") @Guice(modules = ApiTestModule.class) public class WxMpBaseAPITest { @Inject protected WxMpService wxService; public void testRefreshAccessToken() throws WxErrorException { WxMpConfigStorage configStorage = this.wxService.getWxMpConfigStorage(); String before = configStorage.getAccessToken(); this.wxService.getAccessToken(false); String after = configStorage.getAccessToken(); Assert.assertNotEquals(before, after); Assert.assertTrue(StringUtils.isNotBlank(after)); } public void testJsapiTicket() throws WxErrorException { String jsapiTicket = this.wxService.getJsapiTicket(false); System.out.println(jsapiTicket); Assert.assertNotNull(jsapiTicket); } }
apache-2.0
dunkhong/grr
grr/server/grr_response_server/gui/static/angular-components/hunt/hunt-crashes-directive.js
1645
goog.module('grrUi.hunt.huntCrashesDirective'); goog.module.declareLegacyNamespace(); /** @type {number} */ let AUTO_REFRESH_INTERVAL_MS = 20 * 1000; /** * Sets the delay between automatic refreshes. * * @param {number} millis Interval value in milliseconds. * @export */ exports.setAutoRefreshInterval = function(millis) { AUTO_REFRESH_INTERVAL_MS = millis; }; /** * Controller for HuntCrashesDirective. * * @constructor * @param {!angular.Scope} $scope * @ngInject */ const HuntCrashesController = function($scope) { /** @private {!angular.Scope} */ this.scope_ = $scope; /** @type {string} */ this.scope_.huntId; /** @export {string} */ this.crashesUrl; /** @type {number} */ this.autoRefreshInterval = AUTO_REFRESH_INTERVAL_MS; this.scope_.$watch('huntId', this.onHuntIdChange_.bind(this)); }; /** * Handles huntId attribute changes. * * @param {string} huntId * @private */ HuntCrashesController.prototype.onHuntIdChange_ = function(huntId) { if (angular.isDefined(huntId)) { this.crashesUrl = 'hunts/' + huntId + '/crashes'; } }; /** * Directive for displaying crashes of a hunt with a given URN. * * @return {!angular.Directive} Directive definition object. * @ngInject * @export */ exports.HuntCrashesDirective = function() { return { scope: { huntId: '=' }, restrict: 'E', templateUrl: '/static/angular-components/hunt/hunt-crashes.html', controller: HuntCrashesController, controllerAs: 'controller' }; }; /** * Directive's name in Angular. * * @const * @export */ exports.HuntCrashesDirective.directive_name = 'grrHuntCrashes';
apache-2.0
sbespalov/strongbox
strongbox-storage/strongbox-storage-core/src/main/java/org/carlspring/strongbox/storage/routing/MutableRoutingRule.java
2661
package org.carlspring.strongbox.storage.routing; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @author mtodorov * @author Pablo Tirado */ public class MutableRoutingRule implements Serializable { private UUID uuid; private String storageId; private String groupRepositoryId; private String pattern; private String type; private List<MutableRoutingRuleRepository> repositories = new ArrayList<>(); public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } public String getStorageId() { return storageId; } public void setStorageId(String storageId) { this.storageId = storageId; } public String getGroupRepositoryId() { return groupRepositoryId; } public void setGroupRepositoryId(String groupRepositoryId) { this.groupRepositoryId = groupRepositoryId; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<MutableRoutingRuleRepository> getRepositories() { return repositories; } public void setRepositories(List<MutableRoutingRuleRepository> repositories) { this.repositories = repositories; } public static MutableRoutingRule create(String groupStorageId, String groupRepositoryId, List<MutableRoutingRuleRepository> repositories, String rulePattern, RoutingRuleTypeEnum type) { MutableRoutingRule routingRule = new MutableRoutingRule(); routingRule.setPattern(rulePattern); routingRule.setStorageId(groupStorageId); routingRule.setGroupRepositoryId(groupRepositoryId); routingRule.setType(type.getType()); routingRule.setRepositories(repositories); return routingRule; } public boolean updateBy(MutableRoutingRule routingRule) { this.setRepositories(routingRule.getRepositories()); this.setPattern(routingRule.getPattern()); this.setStorageId(routingRule.getStorageId()); this.setGroupRepositoryId(routingRule.getGroupRepositoryId()); this.setType(routingRule.getType()); return true; } }
apache-2.0
whorbowicz/intellij-scala
scalap/src/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala
29335
/* ___ ____ ___ __ ___ ___ ** / _// __// _ | / / / _ | / _ \ Scala classfile decoder ** __\ \/ /__/ __ |/ /__/ __ |/ ___/ (c) 2003-2010, LAMP/EPFL ** /____/\___/_/ |_/____/_/ |_/_/ http://scala-lang.org/ ** */ package scala.tools.scalap package scalax package rules package scalasig import java.io.{ByteArrayOutputStream, PrintStream} import java.util.regex.Pattern import org.apache.commons.lang.StringEscapeUtils import scala.annotation.{switch, tailrec} import scala.collection.mutable import scala.reflect.NameTransformer import scala.tools.scalap.scalax.util.StringUtil sealed abstract class Verbosity case object ShowAll extends Verbosity case object HideClassPrivate extends Verbosity case object HideInstancePrivate extends Verbosity class ScalaSigPrinter(stream: PrintStream, verbosity: Verbosity) { import stream._ def this(stream: PrintStream, printPrivates: Boolean) = this(stream: PrintStream, if (printPrivates) ShowAll else HideClassPrivate) private val currentTypeParameters: mutable.HashMap[TypeSymbol, String] = new mutable.HashMap[TypeSymbol, String]() private def addTypeParameter(t: TypeSymbol) { def checkName(name: String): Boolean = { currentTypeParameters.forall { case (symbol: TypeSymbol, symbolName: String) => name != symbolName } } if (checkName(t.name)) { currentTypeParameters += ((t, t.name)) } else { @tailrec def writeWithIndex(index: Int) { val nameWithIndex: String = s"${t.name}_$$_$index" if (checkName(nameWithIndex)) { currentTypeParameters += ((t, nameWithIndex)) } else writeWithIndex(index + 1) } writeWithIndex(1) } } private def removeTypeParameter(t: TypeSymbol) { currentTypeParameters.remove(t) } val CONSTRUCTOR_NAME = "<init>" val INIT_NAME = "$init$" case class TypeFlags(printRep: Boolean) def printSymbol(symbol: Symbol) {printSymbol(0, symbol)} def printSymbolAttributes(s: Symbol, onNewLine: Boolean, indent: => Unit) = s match { case t: SymbolInfoSymbol => for (a <- t.attributes) { indent; print(toString(a)) if (onNewLine) print("\n") else print(" ") } case _ => } def printSymbol(level: Int, symbol: Symbol) { if (symbol.isSynthetic) return val shouldPrint = { val accessibilityOk = verbosity match { case ShowAll => true case HideClassPrivate => !symbol.isPrivate || symbol.isInstanceOf[AliasSymbol] || level == 0 case HideInstancePrivate => !symbol.isLocal || symbol.isInstanceOf[AliasSymbol] } val paramAccessor = symbol match { case m: MethodSymbol if m.isParamAccessor => true case _ => false } accessibilityOk && !symbol.isCaseAccessor && !paramAccessor } if (shouldPrint) { def indent() {for (i <- 1 to level) print(" ")} printSymbolAttributes(symbol, onNewLine = true, indent()) symbol match { case o: ObjectSymbol => indent() if (o.name == "package" || o.name == "`package`") { // print package object printPackageObject(level, o) } else { printObject(level, o) } case c: ClassSymbol if !refinementClass(c) && !c.isModule => indent() printClass(level, c) case m: MethodSymbol => printMethod(level, m, indent) case a: AliasSymbol => indent() printAlias(level, a) case t: TypeSymbol if !t.isParam && !t.name.matches("_\\$\\d+") && !t.name.matches("\\?(\\d)+") => // todo: type 0? found in Suite class from scalatest package. So this is quickfix, // todo: we need to find why such strange type is here indent() printTypeSymbol(level, t) case s => } } } def isCaseClassObject(o: ObjectSymbol): Boolean = { val TypeRefType(prefix, classSymbol: ClassSymbol, typeArgs) = o.infoType o.isFinal && (classSymbol.children.find(x => x.isCase && x.isInstanceOf[MethodSymbol]) match { case Some(_) => true case None => false }) } private def underCaseClass(m: MethodSymbol) = m.parent match { case Some(c: ClassSymbol) => c.isCase case _ => false } private def underObject(m: MethodSymbol) = m.parent match { case Some(c: ClassSymbol) => c.isModule case _ => false } private def underTrait(m: MethodSymbol) = m.parent match { case Some(c: ClassSymbol) => c.isTrait case _ => false } private def printChildren(level: Int, symbol: Symbol, filterFirstCons: Boolean = false) { var firstConsFiltered = !filterFirstCons for { child <- symbol.children if !(child.isParam && child.isType) } { if (!firstConsFiltered) child match { case m: MethodSymbol if m.name == CONSTRUCTOR_NAME => firstConsFiltered = true case _ => printSymbol(level + 1, child) } else printSymbol(level + 1, child) } } def printWithIndent(level: Int, s: String) { def indent() {for (i <- 1 to level) print(" ")} indent() print(s) } def printModifiers(symbol: Symbol) { lazy val privateWithin: Option[String] = { symbol match { case sym: SymbolInfoSymbol => sym.symbolInfo.privateWithin match { case Some(t: Symbol) => Some("[" + processName(t.name) + "]") case _ => None } case _ => None } } symbol.parent match { case Some(cSymbol: ClassSymbol) if refinementClass(cSymbol) => return //no modifiers allowed inside refinements case _ => } // print private access modifier if (symbol.isPrivate) { print("private") if (symbol.isLocal) print("[this] ") else print(" ") } else if (symbol.isProtected) { print("protected") if (symbol.isLocal) print("[this]") else privateWithin foreach print print(" ") } else privateWithin.foreach(s => print("private" + s + " ")) if (symbol.isSealed) print("sealed ") if (symbol.isImplicit) print("implicit ") if (symbol.isFinal && !symbol.isInstanceOf[ObjectSymbol]) print("final ") if (symbol.isOverride) print("override ") if (symbol.isAbstract) symbol match { case c@(_: ClassSymbol | _: ObjectSymbol) if !c.isTrait => print("abstract ") case _ => () } if (symbol.isCase && !symbol.isMethod) print("case ") } private def refinementClass(c: ClassSymbol) = c.name == "<refinement>" def printClass(level: Int, c: ClassSymbol) { if (c.name == "<local child>" /*scala.tools.nsc.symtab.StdNames.LOCALCHILD.toString()*/ ) { print("\n") } else if (c.name == "<refinement>") { //todo: make it better to avoin '\n' char print(" {\n") printChildren(level, c) printWithIndent(level, "}") } else { printModifiers(c) val defaultConstructor = if (!c.isTrait) getPrinterByConstructor(c) else "" if (c.isTrait) print("trait ") else print("class ") print(processName(c.name)) val it = c.infoType val (classType, typeParams) = it match { case PolyType(typeRef, symbols) => (PolyTypeWithCons(typeRef, symbols, defaultConstructor), symbols) case ClassInfoType(a, b) if !c.isTrait => (ClassInfoTypeWithCons(a, b, defaultConstructor), Seq.empty) case _ => (it, Seq.empty) } for (param <- typeParams) addTypeParameter(param) printType(classType) try { print(" {") //Print class selftype c.selfType match { case Some(t: Type) => print("\n"); print(" this : " + toString(t) + " =>") case None => } print("\n") printChildren(level, c, !c.isTrait) printWithIndent(level, "}\n") } finally { for (param <- typeParams) removeTypeParameter(param) } } } def getClassString(level: Int, c: ClassSymbol): String = { val baos = new ByteArrayOutputStream val stream = new PrintStream(baos) val printer = new ScalaSigPrinter(stream, verbosity) printer.printClass(level, c) baos.toString } def getPrinterByConstructor(c: ClassSymbol): String = { c.children.find { case m: MethodSymbol if m.name == CONSTRUCTOR_NAME => true case _ => false } match { case Some(m: MethodSymbol) => val baos = new ByteArrayOutputStream val stream = new PrintStream(baos) val printer = new ScalaSigPrinter(stream, verbosity) printer.printPrimaryConstructor(m, c) val res = baos.toString if (res.length() > 0 && res.charAt(0) != '(') " " + res else res case _ => "" } } def printPrimaryConstructor(m: MethodSymbol, c: ClassSymbol) { printModifiers(m) printMethodType(m.infoType, printResult = false, methodSymbolAsClassParam(_, c))(()) } def printPackageObject(level: Int, o: ObjectSymbol) { printModifiers(o) print("package ") print("object ") val poName = o.symbolInfo.owner.name print(processName(poName)) val TypeRefType(prefix, classSymbol: ClassSymbol, typeArgs) = o.infoType printType(classSymbol) print(" {\n") printChildren(level, classSymbol) printWithIndent(level, "}\n") } def printObject(level: Int, o: ObjectSymbol) { printModifiers(o) print("object ") print(processName(o.name)) val TypeRefType(prefix, classSymbol: ClassSymbol, typeArgs) = o.infoType printType(classSymbol) print(" {\n") printChildren(level, classSymbol) printWithIndent(level, "}\n") } private def methodSymbolAsMethodParam(ms: MethodSymbol): String = { val nameAndType = processName(ms.name) + " : " + toString(ms.infoType)(TypeFlags(true)) val default = if (ms.hasDefault) " = { /* compiled code */ }" else "" nameAndType + default } private def methodSymbolAsClassParam(msymb: MethodSymbol, c: ClassSymbol): String = { val baos = new ByteArrayOutputStream val stream = new PrintStream(baos) val printer = new ScalaSigPrinter(stream, verbosity) var break = false for (child <- c.children if !break) { child match { case ms: MethodSymbol if ms.isParamAccessor && msymb.name == ms.name => if (!ms.isPrivate || !ms.isLocal) { printer.printSymbolAttributes(ms, onNewLine = false, ()) printer.printModifiers(ms) if (ms.isParamAccessor && ms.isMutable) stream.print("var ") else if (ms.isParamAccessor) stream.print("val ") } break = true case _ => } } val nameAndType = processName(msymb.name) + " : " + toString(msymb.infoType)(TypeFlags(true)) val default = if (msymb.hasDefault) " = { /* compiled code */ }" else "" stream.print(nameAndType + default) baos.toString } def printMethodType(t: Type, printResult: Boolean, pe: MethodSymbol => String = methodSymbolAsMethodParam)(cont: => Unit) { def _pmt(mt: FunctionType) { val paramEntries = mt.paramSymbols.map({ case ms: MethodSymbol => pe(ms) case _ => "^___^" }) // Print parameter clauses print(paramEntries.mkString( "(" + (mt match { case _: ImplicitMethodType => "implicit " //for Scala 2.9 case mt: MethodType if mt.paramSymbols.nonEmpty && mt.paramSymbols.head.isImplicit => "implicit " case _ => "" }), ", ", ")")) // Print result type mt.resultType match { case mt: MethodType => printMethodType(mt, printResult, pe)({}) case imt: ImplicitMethodType => printMethodType(imt, printResult, pe)({}) case x => if (printResult) { print(" : ") printType(x) } } } t match { case mt@MethodType(resType, paramSymbols) => _pmt(mt) case mt@ImplicitMethodType(resType, paramSymbols) => _pmt(mt) case pt@PolyType(mt, typeParams) => for (param <- typeParams) addTypeParameter(param) print(typeParamString(typeParams)) try { printMethodType(mt, printResult)({}) } finally { for (param <- typeParams) removeTypeParameter(param) } //todo consider another method types case x => print(" : "); printType(x) } // Print rest of the symbol output cont } def printMethod(level: Int, m: MethodSymbol, indent: () => Unit) { val n = m.name if (underObject(m) && n == CONSTRUCTOR_NAME) return if (underTrait(m) && n == INIT_NAME) return if (n.matches(".+\\$default\\$\\d+")) return // skip default function parameters if (n.startsWith("super$")) return // do not print auxiliary qualified super accessors if (m.isAccessor && n.endsWith("_$eq")) return if (m.isParamAccessor) return //do not print class parameters indent() printModifiers(m) if (m.isAccessor) { val indexOfSetter = m.parent.get.children.indexWhere(x => x.isInstanceOf[MethodSymbol] && x.asInstanceOf[MethodSymbol].name == n + "_$eq") print(if (indexOfSetter > 0) "var " else "val ") } else { print("def ") } n match { case CONSTRUCTOR_NAME => print("this") printMethodType(m.infoType, printResult = false) { print(" = { /* compiled code */ }") } case name => val nn = processName(name) print(nn) val printBody = !m.isDeferred && (m.parent match { case Some(c: ClassSymbol) if refinementClass(c) => false case _ => true }) printMethodType(m.infoType, printResult = true)( {if (printBody) print(" = { /* compiled code */ }" /* Print body only for non-abstract methods */ )} ) } print("\n") } def printAlias(level: Int, a: AliasSymbol) { printModifiers(a) print("type ") print(processName(a.name)) val tp = a.infoType match { case PolyType(typeRef, symbols) => printType(PolyTypeWithCons(typeRef, symbols, " = ")) case tp => printType(tp, " = ") } print("\n") printChildren(level, a) } def printTypeSymbol(level: Int, t: TypeSymbol) { print("type ") print(processName(t.name)) t.infoType match { case PolyType(typeRef, symbols) => printType(PolyTypeWithCons(typeRef, symbols, "")) case _ => printType(t.infoType) } print("\n") } def toString(attrib: AttributeInfo): String = { val buffer = new StringBuffer buffer.append(toString(attrib.typeRef, "@")) if (attrib.value.isDefined) { buffer.append("(") buffer.append(valueToString(attrib.value.get)) buffer.append(")") } if (attrib.values.nonEmpty) { buffer.append("(") for (name ~ value <- attrib.values) { buffer.append(processName(name)) buffer.append(" = ") buffer.append(valueToString(value)) } buffer.append(")") } buffer.toString } // TODO char, float, etc. def valueToString(value: Any): String = value match { case t: Type => "classOf[%s]" format toString(t) case s: String => if (s.contains("\n") || s.contains("\r")) { "\"\"\"" + s + "\"\"\"" } else "\"" + StringEscapeUtils.escapeJava(s) + "\"" case arr: Array[_] => arr.map(valueToString).mkString("Array(", ", ", ")") case _ => value.toString } implicit object _tf extends TypeFlags(false) def printType(sym: SymbolInfoSymbol)(implicit flags: TypeFlags): Unit = printType(sym.infoType)(flags) def printType(t: Type)(implicit flags: TypeFlags): Unit = print(toString(t)(flags)) def printType(t: Type, sep: String)(implicit flags: TypeFlags): Unit = print(toString(t, sep)(flags)) def toString(t: Type)(implicit flags: TypeFlags): String = toString(t, "")(flags) def toString(t: Type, level: Int)(implicit flags: TypeFlags): String = toString(t, "", level)(flags) private val SingletonTypePattern = """(.*?)\.type""".r //TODO: this passing of 'level' look awful; def toString(t: Type, sep: String, level: Int = 0)(implicit flags: TypeFlags): String = { // print type itself t match { case ThisType(classSymbol: ClassSymbol) if refinementClass(classSymbol) => sep + "this.type" case ThisType(symbol) => sep + processName(symbol.name) + ".this.type" case SingleType(ThisType(thisSymbol: ClassSymbol), symbol) => val thisSymbolName: String = thisSymbol.name match { case "package" => thisSymbol.symbolInfo.owner match { case ex: ExternalSymbol => processName(ex.name) case _ => "this" } case name if thisSymbol.isModule => processName(name) case name => processName(name) + ".this" } sep + thisSymbolName + "." + processName(symbol.name) + ".type" case SingleType(ThisType(exSymbol: ExternalSymbol), symbol) if exSymbol.name == "<root>" => sep + processName(symbol.name) + ".type" case SingleType(ThisType(exSymbol: ExternalSymbol), symbol) => sep + StringUtil.cutSubstring(StringUtil.trimStart(processName(exSymbol.path), "<empty>."))(".`package`") + "." + processName(symbol.name) + ".type" case SingleType(NoPrefixType, symbol) => sep + processName(symbol.name) + ".type" case SingleType(typeRef, symbol) => var typeRefString = toString(typeRef, level) if (typeRefString.endsWith(".type")) typeRefString = typeRefString.dropRight(5) typeRefString = StringUtil.cutSubstring(typeRefString)(".`package`") sep + typeRefString + "." + processName(symbol.name) + ".type" case ConstantType(constant) => sep + (constant match { case null => "scala.Null" case _: Unit => "scala.Unit" case _: Boolean => "scala.Boolean" case _: Byte => "scala.Byte" case _: Char => "scala.Char" case _: Short => "scala.Short" case _: Int => "scala.Int" case _: Long => "scala.Long" case _: Float => "scala.Float" case _: Double => "scala.Double" case _: String => "java.lang.String" case c: Class[_] => "java.lang.Class[" + c.getComponentType.getCanonicalName.replace("$", ".") + "]" case ExternalSymbol(_, Some(parent), _) => parent.path //enum value }) case TypeRefType(NoPrefixType, symbol: TypeSymbol, typeArgs) if currentTypeParameters.isDefinedAt(symbol) => sep + processName(currentTypeParameters.getOrElse(symbol, symbol.name)) + typeArgString(typeArgs, level) case TypeRefType(prefix, symbol, typeArgs) => sep + (symbol.path match { case "scala.<repeated>" => flags match { case TypeFlags(true) => toString(typeArgs.head, level) + "*" case _ => "scala.Seq" + typeArgString(typeArgs, level) } case "scala.<byname>" => "=> " + toString(typeArgs.head, level) case _ => def checkContainsSelf(self: Option[Type], parent: Symbol): Boolean = { self match { case Some(tp) => tp match { case ThisType(symbol) => symbol == parent case SingleType(_, symbol) => symbol == parent case c: ConstantType => false case TypeRefType(_, symbol, _) => symbol == parent case t: TypeBoundsType => false case RefinedType(symbol, refs) => symbol == parent || !refs.forall(tp => !checkContainsSelf(Some(tp), parent)) case ClassInfoType(symbol, refs) => symbol == parent || !refs.forall(tp => !checkContainsSelf(Some(tp), parent)) case ClassInfoTypeWithCons(symbol, refs, _) => symbol == parent || !refs.forall(tp => !checkContainsSelf(Some(tp), parent)) case ImplicitMethodType(resultType, _) => false case MethodType(resultType, _) => false case NullaryMethodType(resultType) => false case PolyType(typeRef, symbols) => checkContainsSelf(Some(typeRef), parent) || symbols.contains(parent) case PolyTypeWithCons(typeRef, symbols, _) => checkContainsSelf(Some(typeRef), parent) || symbols.contains(parent) case AnnotatedType(typeRef, _) => checkContainsSelf(Some(typeRef), parent) case AnnotatedWithSelfType(typeRef, symbol, _) => checkContainsSelf(Some(typeRef), parent) || symbol == parent case ExistentialType(typeRef, symbols) => checkContainsSelf(Some(typeRef), parent) || symbols.contains(parent) case _ => false } case None => false } } val prefixStr = (prefix, symbol, toString(prefix, level)) match { case (NoPrefixType, _, _) => "" case (ThisType(objectSymbol), _, _) if objectSymbol.isModule && !objectSymbol.isStable => val name: String = objectSymbol.name objectSymbol match { case classSymbol: ClassSymbol if name == "package" => processName(classSymbol.symbolInfo.owner.path) + "." case _ => processName(name) + "." } case (ThisType(packSymbol), _, _) if !packSymbol.isType => processName(packSymbol.path.replace("<root>", "_root_")) + "." case (ThisType(classSymbol: ClassSymbol), _, _) if refinementClass(classSymbol) => "" case (ThisType(typeSymbol: ClassSymbol), ExternalSymbol(_, Some(parent), _), _) if typeSymbol.path != parent.path && checkContainsSelf(typeSymbol.selfType, parent) => processName(typeSymbol.name) + ".this." case (ThisType(typeSymbol), ExternalSymbol(_, Some(parent), _), _) if typeSymbol.path != parent.path => processName(typeSymbol.name) + ".super[" + processName(parent.name) + "/*"+ parent.path +"*/]." case (_, _, SingletonTypePattern(a)) => a + "." case (_, _, a) => a + "#" } //remove package object reference val path = StringUtil.cutSubstring(prefixStr)(".`package`") val name = processName(symbol.name) val res = path + name val typeBounds = if (name == "_") { symbol match { case ts: TypeSymbol => ts.infoType match { case t: TypeBoundsType => toString(t, level) case _ => "" } case _ => "" } } else "" val ress = StringUtil.trimStart(res, "<empty>.") + typeArgString(typeArgs, level) + typeBounds ress }) case TypeBoundsType(lower, upper) => val lb = toString(lower, level) val ub = toString(upper, level) val lbs = if (!lb.equals("scala.Nothing")) " >: " + lb else "" val ubs = if (!ub.equals("scala.Any")) " <: " + ub else "" lbs + ubs case RefinedType(classSym: ClassSymbol, typeRefs) => val classStr = { val text = getClassString(level + 1, classSym) if (text.trim.stripPrefix("{").stripSuffix("}").trim.isEmpty) "" else text } sep + typeRefs.map(toString(_, level)).mkString("", " with ", "") + classStr case RefinedType(classSym, typeRefs) => sep + typeRefs.map(toString(_, level)).mkString("", " with ", "") case ClassInfoType(symbol, typeRefs) => sep + typeRefs.map(toString(_, level)).mkString(" extends ", " with ", "") case ClassInfoTypeWithCons(symbol, typeRefs, cons) => sep + typeRefs.map(toString(_, level)). mkString(cons + " extends ", " with ", "") case ImplicitMethodType(resultType, _) => toString(resultType, sep, level) case MethodType(resultType, _) => toString(resultType, sep, level) case NullaryMethodType(resultType) => toString(resultType, sep, level) case PolyType(typeRef, symbols) => "({ type λ" + typeParamString(symbols) + " = " + toString(typeRef, sep, level) + " })#λ" case PolyTypeWithCons(typeRef, symbols, cons) => typeParamString(symbols) + cons + toString(typeRef, sep, level) case AnnotatedType(typeRef, attribTreeRefs) => toString(typeRef, sep, level) case AnnotatedWithSelfType(typeRef, symbol, attribTreeRefs) => toString(typeRef, sep, level) //case DeBruijnIndexType(typeLevel, typeIndex) => case ExistentialType(typeRef, symbols) => val refs = symbols.map(toString).filter(!_.startsWith("_")).map("type " + _) toString(typeRef, sep, level) + (if (refs.nonEmpty) refs.mkString(" forSome {", "; ", "}") else "") case _ => sep + t.toString } } def getVariance(t: TypeSymbol) = if (t.isCovariant) "+" else if (t.isContravariant) "-" else "" def toString(symbol: Symbol): String = symbol match { case symbol: TypeSymbol => val attrs = (for (a <- symbol.attributes) yield toString(a)).mkString(" ") val atrs = if (attrs.length > 0) attrs.trim + " " else "" val symbolType = symbol.infoType match { case PolyType(typeRef, symbols) => PolyTypeWithCons(typeRef, symbols, "") case tp => tp } val name: String = currentTypeParameters.getOrElse(symbol, symbol.name) atrs + getVariance(symbol) + processName(name) + toString(symbolType) case s => symbol.toString } def typeArgString(typeArgs: Seq[Type], level: Int): String = if (typeArgs.isEmpty) "" else typeArgs.map(toString(_, level)).map(StringUtil.trimStart(_, "=> ")).mkString("[", ", ", "]") def typeParamString(params: Seq[TypeSymbol]): String = if (params.isEmpty) "" else params.map(toString).mkString("[", ", ", "]") val _syms = Map("\\$bar" -> "|", "\\$tilde" -> "~", "\\$bang" -> "!", "\\$up" -> "^", "\\$plus" -> "+", "\\$minus" -> "-", "\\$eq" -> "=", "\\$less" -> "<", "\\$times" -> "*", "\\$div" -> "/", "\\$bslash" -> "\\\\", "\\$greater" -> ">", "\\$qmark" -> "?", "\\$percent" -> "%", "\\$amp" -> "&", "\\$colon" -> ":", "\\$u2192" -> "→", "\\$hash" -> "#") val pattern = Pattern.compile(_syms.keys.foldLeft("")((x, y) => if (x == "") y else x + "|" + y)) val placeholderPattern = "_\\$(\\d)+" private val keywordList = Set("true", "false", "null", "abstract", "case", "catch", "class", "def", "do", "else", "extends", "final", "finally", "for", "forSome", "if", "implicit", "import", "lazy", "match", "new", "object", "override", "package", "private", "protected", "return", "sealed", "super", "this", "throw", "trait", "try", "type", "val", "var", "while", "with", "yield") private def stripPrivatePrefix(name: String) = { val i = name.lastIndexOf("$$") if (i > 0) name.substring(i + 2) else name } def processName(name: String): String = { def processNameWithoutDot(name: String) = { def isIdentifier(id: String): Boolean = { //following four methods is the same like in scala.tools.nsc.util.Chars class /** Can character start an alphanumeric Scala identifier? */ def isIdentifierStart(c: Char): Boolean = (c == '_') || (c == '$') || Character.isUnicodeIdentifierStart(c) /** Can character form part of an alphanumeric Scala identifier? */ def isIdentifierPart(c: Char) = (c == '$') || Character.isUnicodeIdentifierPart(c) /** Is character a math or other symbol in Unicode? */ def isSpecial(c: Char) = { val chtp = Character.getType(c) chtp == Character.MATH_SYMBOL.toInt || chtp == Character.OTHER_SYMBOL.toInt } /** Can character form part of a Scala operator name? */ def isOperatorPart(c : Char) : Boolean = (c: @switch) match { case '~' | '!' | '@' | '#' | '%' | '^' | '*' | '+' | '-' | '<' | '>' | '?' | ':' | '=' | '&' | '|' | '/' | '\\' => true case c => isSpecial(c) } if (id.isEmpty) return false if (isIdentifierStart(id(0))) { if (id.indexWhere(c => !isIdentifierPart(c) && !isOperatorPart(c) && c != '_') >= 0) return false val index = id.indexWhere(isOperatorPart) if (index < 0) return true if (id(index - 1) != '_') return false id.drop(index).forall(isOperatorPart) } else if (isOperatorPart(id(0))) { id.forall(isOperatorPart) } else false } val result = NameTransformer.decode(name) if (!isIdentifier(result) || keywordList.contains(result) || result == "=") "`" + result + "`" else result } val stripped = stripPrivatePrefix(name) val m = pattern.matcher(stripped) var temp = stripped while (m.find) { val key = m.group val re = "\\" + key temp = temp.replaceAll(re, _syms(re)) } var result = temp.replaceAll(placeholderPattern, "_") //to avoid names like this one: ?0 (from existential type parameters) if (result.length() > 1 && result(0) == '?' && result(1).isDigit) result = "x" + result.substring(1) result.split('.').map(s => processNameWithoutDot(s)).mkString(".") } }
apache-2.0
AludraTest/aludratest-tutorial
ikea-search/src/test/java/org/aludratest/tutorial/ikea/search/IkeaSearchResultUIMap.java
2099
package org.aludratest.tutorial.ikea.search; import org.aludratest.service.gui.component.Button; import org.aludratest.service.gui.component.InputField; import org.aludratest.service.gui.component.Label; import org.aludratest.service.gui.web.AludraWebGUI; import org.aludratest.service.gui.web.uimap.UIMap; import org.aludratest.service.locator.element.GUIElementLocator; import org.aludratest.service.locator.element.IdLocator; import org.aludratest.service.locator.element.XPathLocator; public class IkeaSearchResultUIMap extends UIMap { // see IkeaMainUIMap for what this is private static GUIElementLocator SEARCH_RESULTS_HEADER = new XPathLocator("//h2[contains(., 'Search Results')]"); private static GUIElementLocator SEARCH_REPEAT_TEXT = new XPathLocator("//div[@class='serpSearchString']"); private static GUIElementLocator SEARCH_SERIES_TEXT = new IdLocator("serpSearchSeries"); private static GUIElementLocator MIN_PRICE = new IdLocator("minPrice"); private static GUIElementLocator MAX_PRICE = new IdLocator("maxPrice"); private static GUIElementLocator VIEW_BUTTON = new XPathLocator("//input[@type='button' and @value='View']"); private static GUIElementLocator PRICERANGE_ERROR = new IdLocator("minMaxPriceError"); public IkeaSearchResultUIMap(AludraWebGUI aludraGUI) { super(aludraGUI); } public Label searchResultsHeader() { return aludraGUI.getComponentFactory().createLabel(SEARCH_RESULTS_HEADER); } public Label searchRepeatText() { return aludraGUI.getComponentFactory().createLabel(SEARCH_REPEAT_TEXT); } public Label searchSeriesText() { return aludraGUI.getComponentFactory().createLabel(SEARCH_SERIES_TEXT); } public InputField minPrice() { return aludraGUI.getComponentFactory().createInputField(MIN_PRICE); } public InputField maxPrice() { return aludraGUI.getComponentFactory().createInputField(MAX_PRICE); } public Button viewButton() { return aludraGUI.getComponentFactory().createButton(VIEW_BUTTON); } public Label priceRangeError() { return aludraGUI.getComponentFactory().createLabel(PRICERANGE_ERROR); } }
apache-2.0
coreswitch/zebra
vendor/github.com/coreswitch/openconfigd/config/dhcp.go
13814
// Copyright 2016, 2017 OpenConfigd Project. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "encoding/json" "fmt" "log" "net" "os" "strconv" "text/template" "github.com/coreswitch/netutil" "github.com/coreswitch/process" "github.com/mitchellh/mapstructure" ) var DhcpProcessList = process.ProcessSlice{} func prefix2Subnet(subnet string) string { p, _ := netutil.ParsePrefix(subnet) p.ApplyMask() mask := net.IP(net.CIDRMask(p.Length, 32)) return "subnet " + p.IP.String() + " netmask " + mask.String() } func listDomainNameServers(dhcpIpPool *DhcpIpPool) string { list := "" for pos, server := range dhcpIpPool.Option.DomainNameServersList { if pos != 0 { list += ", " } list += server.Server } return list } func listNtpServers(dhcpIpPool *DhcpIpPool) string { list := "" for pos, server := range dhcpIpPool.Option.NtpServersList { if pos != 0 { list += ", " } list += server.Server } return list } func listVoipTftpServers(dhcpIpPool *DhcpIpPool) string { list := "" for pos, server := range dhcpIpPool.Option.VoipTftpServersList { if pos != 0 { list += ", " } list += server.Server } return list } func listSipServers(dhcpIpPool *DhcpIpPool) string { // Encoding IP (1). list := "1 " for pos, server := range dhcpIpPool.Option.SipServersList { if pos != 0 { list += ", " } list += server.Server } return list } func listClasslessRoutes(dhcpIpPool *DhcpIpPool) string { list := "" for pos, route := range dhcpIpPool.Option.ClasslessRoutesList { if pos != 0 { list += ", " } prefix, _ := netutil.ParsePrefix(route.Prefix) list += strconv.Itoa(prefix.Length) for i := 0; i < (prefix.Length+7)/8; i++ { list += fmt.Sprintf(", %d", prefix.IP[i]) } nexthop := netutil.ParseIPv4(route.Nexthop) list += fmt.Sprintf(", %d, %d, %d, %d", nexthop[0], nexthop[1], nexthop[2], nexthop[3]) } return list } func hasFailover(failoverRole string, failoverPeerAddress string) bool { if failoverRole != "" && failoverPeerAddress != "" { return true } return false } const dhcpConfigTemplateText = ` # Do not edit # This file is automatically generated from OpenConfigd. # ddns-update-style none; log-facility local7; option sip-servers code 120 = { integer 8, array of ip-address }; option voip-tftp-servers code 150 = array of ip-address; option rfc3442-classless-routes code 121 = array of integer 8; option ms-classless-routes code 249 = array of integer 8; default-lease-time {{if .Server.DefaultLeaseTime}}{{.Server.DefaultLeaseTime}}{{else}}600{{end}}; max-lease-time {{if .Server.MaxLeaseTime}}{{.Server.MaxLeaseTime}}{{else}}7200{{end}}; {{if .Server.PingCheck}}ping-check true;{{end}} {{if hasFailover .Pool.FailoverRole .Pool.FailoverPeerAddress}} failover peer "failover" { {{if eq .Pool.FailoverRole "master"}}primary;{{else}}secondary;{{end}} address {{.LocalAddr}}; port 647; peer address {{.Pool.FailoverPeerAddress}}; peer port 647; max-response-delay 30; max-unacked-updates 10; load balance max seconds 3; {{if eq .Pool.FailoverRole "master"}} mclt 180; split 255; {{end}} } {{end}} {{if ne (len .Pool.RangeList) 0}}{{prefix2Subnet .Pool.Subnet}} { {{if .Pool.DefaultLeaseTime}} default-lease-time {{.Pool.DefaultLeaseTime}};{{end}} {{if .Pool.MaxLeaseTime}} max-lease-time {{.Pool.MaxLeaseTime}};{{end}} {{if .Pool.GatewayIp}} option routers {{.Pool.GatewayIp}};{{end}} {{if .Pool.Option.DomainName}} option domain-name "{{.Pool.Option.DomainName}}";{{end}} {{if .Pool.Option.TftpServerName}} option tftp-server-name "{{.Pool.Option.TftpServerName}}";{{end}} {{if .Pool.Option.BootfileName}} option bootfile-name "{{.Pool.Option.BootfileName}}";{{end}} {{if .Pool.Option.InterfaceMtu}} option interface-mtu {{.Pool.Option.InterfaceMtu}};{{end}} {{if .Pool.Option.DhcpServerIdentifier}} option dhcp-server-identifier {{.Pool.Option.DhcpServerIdentifier}};{{end}} {{if ne (len .Pool.Option.DomainNameServersList) 0}} option domain-name-servers {{listDomainNameServers .Pool}};{{end}} {{if ne (len .Pool.Option.NtpServersList) 0}} option ntp-servers {{listNtpServers .Pool}};{{end}} {{if ne (len .Pool.Option.SipServersList) 0}} option sip-servers {{listSipServers .Pool}};{{end}} {{if ne (len .Pool.Option.VoipTftpServersList) 0}} option voip-tftp-servers {{listVoipTftpServers .Pool}};{{end}} {{if ne (len .Pool.Option.ClasslessRoutesList) 0}} option rfc3442-classless-routes {{listClasslessRoutes .Pool}};{{end}} {{if ne (len .Pool.Option.ClasslessRoutesList) 0}} option ms-classless-routes {{listClasslessRoutes .Pool}};{{end}} {{if ne .Pool.Option.TimeOffset 0}} option time-offset {{.Pool.Option.TimeOffset}};{{end}} pool { {{if hasFailover .Pool.FailoverRole .Pool.FailoverPeerAddress}} failover peer "failover";{{end}} {{range $j, $w := .Pool.RangeList}} range {{$w.RangeStartIp}} {{$w.RangeEndIp}};{{end}} } {{range $j, $w := .Pool.HostList}} host {{$w.HostName}} { hardware ethernet {{$w.MacAddress}}; fixed-address {{$w.IpAddress}}; } {{end}} } {{end}} ` func DhcpLocalAddrLookup(ifName string) string { addrConfig := configActive.LookupByPath([]string{"interfaces", "interface", ifName, "ipv4", "address"}) if addrConfig != nil && len(addrConfig.Keys) > 0 { prefix, _ := netutil.ParsePrefix(addrConfig.Keys[0].Name) return prefix.IP.String() } return "" } func DhcpServerExec(dhcp *Dhcp, poolConfig *DhcpIpPool) { // fmt.Println("DhcpServerExec") if poolConfig.Interface == "" { fmt.Println("Empty interface") return } if len(poolConfig.RangeList) == 0 { fmt.Println("Empty range list") return } if poolConfig.Subnet == "" { fmt.Println("Empty subnet") return } configFileName := fmt.Sprintf("/etc/dhcp/dhcpd-%s.conf", poolConfig.IpPoolName) pidFileName := fmt.Sprintf("/var/run/dhcpd-%s.pid", poolConfig.IpPoolName) leaseFileName := fmt.Sprintf("/var/lib/dhcp/dhcpd-%s.leases", poolConfig.IpPoolName) f, err := os.Create(configFileName) if err != nil { log.Println("Create file:", err) return } tmpl := template.Must(template.New("dhcpTemplate").Funcs(template.FuncMap{ "prefix2Subnet": prefix2Subnet, "listDomainNameServers": listDomainNameServers, "listNtpServers": listNtpServers, "listVoipTftpServers": listVoipTftpServers, "listSipServers": listSipServers, "listClasslessRoutes": listClasslessRoutes, "hasFailover": hasFailover, }).Parse(dhcpConfigTemplateText)) type TemplValue struct { Server *Server Pool *DhcpIpPool LocalAddr string } value := &TemplValue{ Server: &dhcp.Server, Pool: poolConfig, } if hasFailover(poolConfig.FailoverRole, poolConfig.FailoverPeerAddress) { fmt.Println("XXX FailoverConfig exists") value.LocalAddr = DhcpLocalAddrLookup(poolConfig.IpPoolName) } //tmpl.Execute(f, dhcp.Server) tmpl.Execute(f, value) if poolConfig.Interface != "" { DhcpServerStart(configFileName, pidFileName, leaseFileName, poolConfig.IpPoolName, poolConfig.Interface) } else { DhcpServerStart(configFileName, pidFileName, leaseFileName, poolConfig.IpPoolName) } } func DhcpServerStart(config string, pid string, lease string, ifName string, arg ...string) { // fmt.Println("DhcpServerStart") vrf := "" if len(arg) != 0 { vrf = arg[0] } args := []string{"-f", "-d", "-4", "-user", "root", "-group", "dhcpd", "-pf", pid, "-cf", config, "-lf", lease, ifName} proc := process.NewProcess("dhcpd", args...) proc.Vrf = vrf proc.File = lease proc.StartTimer = 3 DhcpProcessList = append(DhcpProcessList, proc) process.ProcessRegister(proc) } func DhcpVrf(config *Dhcp) string { vrf := "" if len(config.Server.DhcpIpPoolList) == 0 { return vrf } poolList := config.Server.DhcpIpPoolList[0] return poolList.Interface } func DhcpJsonConfig(path []string, str string) error { fmt.Println("[dhcp]DhcpJsonConfig") var jsonIntf interface{} err := json.Unmarshal([]byte(str), &jsonIntf) if err != nil { return err } dhcp := &Dhcp{} err = mapstructure.Decode(jsonIntf, &dhcp) if err != nil { return err } RelayGroupUpdate(dhcp) // Kill all of DhcpInstance. for _, proc := range DhcpProcessList { for index, value := range proc.Args { if value == "-pf" { pidFile := proc.Args[index + 1] err := os.Remove(pidFile) if err != nil { log.Println("Delete pid file:", err) } break } } process.ProcessUnregister(proc) } DhcpProcessList = DhcpProcessList[:0] if len(dhcp.Server.DhcpIpPoolList) == 0 { fmt.Println("Empty DhcpIpPoolList") return nil } for _, pool := range dhcp.Server.DhcpIpPoolList { //fmt.Println("DHCP pool", pool.IpPoolName) DhcpServerExec(dhcp, &pool) } return nil } func DhcpExitFunc() { for _, proc := range DhcpProcessList { for index, value := range proc.Args { if value == "-pf" { pidFile := proc.Args[index + 1] err := os.Remove(pidFile) if err != nil { log.Println("Delete pid file:", err) } break } } process.ProcessUnregister(proc) } DhcpProcessList = DhcpProcessList[:0] } func DhcpVrfClear(vrfId int, cfg *VrfsConfig) { dhcp := cfg.Dhcp.Server for _, pool := range dhcp.DhcpIpPoolList { fmt.Println(fmt.Sprintf("[dhcp]DhcpVrfClear:delete dhcp server dhcp-ip-pool %s", pool.Interface)) ExecLine(fmt.Sprintf("delete dhcp server dhcp-ip-pool %s", pool.Interface)) } } func DhcpVrfSync(vrfId int, cfg *VrfsConfig) { dhcp := &cfg.Dhcp.Server fmt.Printf("---- DHCP for vrf%d\n", cfg.Id) fmt.Println("Auto DHCP config", dhcp) if vrfConfig, ok := EtcdVrfMap[vrfId]; ok { DhcpVrfClear(vrfId, &vrfConfig) } for _, pool := range dhcp.DhcpIpPoolList { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s", pool.Interface)) ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s interface vrf%d", pool.Interface, cfg.Id)) ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s gateway-ip %s", pool.Interface, pool.GatewayIp)) ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s subnet %s", pool.Interface, pool.Subnet)) if pool.DefaultLeaseTime != 0 { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s default-lease-time %d", pool.Interface, pool.DefaultLeaseTime)) } if pool.MaxLeaseTime != 0 { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s max-lease-time %d", pool.Interface, pool.MaxLeaseTime)) } for pos, rng := range pool.RangeList { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s range %d range-start-ip %s", pool.Interface, pos, rng.RangeStartIp)) ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s range %d range-end-ip %s", pool.Interface, pos, rng.RangeEndIp)) } for _, host := range pool.HostList { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s host %s ip-address %s", pool.Interface, host.HostName, host.IpAddress)) ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s host %s mac-address %s", pool.Interface, host.HostName, host.MacAddress)) } option := &pool.Option if option.DomainName != "" { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s option domain-name %s", pool.Interface, option.DomainName)) } for _, o := range option.DomainNameServersList { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s option domain-name-servers %s", pool.Interface, o.Server)) } for _, o := range option.NtpServersList { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s option ntp-servers %s", pool.Interface, o.Server)) } if option.TftpServerName != "" { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s option tftp-server-name %s", pool.Interface, option.TftpServerName)) } for _, o := range option.VoipTftpServersList { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s option voip-tftp-servers %s", pool.Interface, o.Server)) } for _, o := range option.SipServersList { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s option sip-servers %s", pool.Interface, o.Server)) } for _, o := range option.ClasslessRoutesList { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s option classless-routes %s nexthop %s", pool.Interface, o.Prefix, o.Nexthop)) } if option.TimeOffset != 0 { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s option time-offset %d", pool.Interface, option.TimeOffset)) } if pool.FailoverRole != "" { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s failover-role %s", pool.Interface, pool.FailoverRole)) } if pool.FailoverPeerAddress != "" { ExecLine(fmt.Sprintf("set dhcp server dhcp-ip-pool %s failover-peer-address %s", pool.Interface, pool.FailoverPeerAddress)) } } fmt.Printf("---- DHCP relay for vrf%d\n", cfg.Id) relay := &cfg.Dhcp.Relay for _, group := range relay.ServerGroupList { ExecLine(fmt.Sprintf("delete dhcp relay server-group %s", group.ServerGroupName)) ExecLine(fmt.Sprintf("set dhcp relay server-group %s", group.ServerGroupName)) for _, addr := range group.ServerAddressList { ExecLine(fmt.Sprintf("set dhcp relay server-group %s server-address %s", group.ServerGroupName, addr.Address)) } } Commit() } func DhcpVrfDelete(vrfId int) { fmt.Println("DhcpVrfDelete:", vrfId) if vrfConfig, ok := EtcdVrfMap[vrfId]; ok { DhcpVrfClear(vrfId, &vrfConfig) } Commit() }
apache-2.0
Zodia/poc-tijari-mobile
dojoLib/toolkit/dojo/dojo/cldr/nls/number.js
4328
define({ root: //begin v1.x content { "scientificFormat": "#E0", "currencySpacing-afterCurrency-currencyMatch": "[:^S:]", "infinity": "∞", "list": ";", "percentSign": "%", "minusSign": "-", "currencySpacing-beforeCurrency-surroundingMatch": "[:digit:]", "decimalFormat-short": "000T", "currencySpacing-afterCurrency-insertBetween": " ", "nan": "NaN", "plusSign": "+", "currencySpacing-afterCurrency-surroundingMatch": "[:digit:]", "currencySpacing-beforeCurrency-currencyMatch": "[:^S:]", "currencyFormat": "¤ #,##0.00", "perMille": "‰", "group": ",", "percentFormat": "#,##0%", "decimalFormat-long": "000T", "decimalFormat": "#,##0.###", "decimal": ".", "currencySpacing-beforeCurrency-insertBetween": " ", "exponential": "E" } //end v1.x content , "af": true, "af-na": true, "agq": true, "ak": true, "am": true, "ar": true, "ar-dz": true, "ar-lb": true, "ar-ly": true, "ar-ma": true, "ar-mr": true, "ar-ps": true, "ar-qa": true, "ar-sa": true, "ar-sy": true, "ar-tn": true, "ar-ye": true, "as": true, "asa": true, "az": true, "az-cyrl": true, "bas": true, "be": true, "bem": true, "bez": true, "bg": true, "bm": true, "bn": true, "bo": true, "br": true, "brx": true, "bs": true, "bs-cyrl": true, "ca": true, "cgg": true, "chr": true, "cs": true, "cy": true, "da": true, "dav": true, "de": true, "de-at": true, "de-ch": true, "de-li": true, "dje": true, "dua": true, "dyo": true, "dz": true, "ebu": true, "ee": true, "el": true, "el-cy": true, "en": true, "en-150": true, "en-be": true, "en-bw": true, "en-bz": true, "en-gb": true, "en-hk": true, "en-in": true, "en-jm": true, "en-na": true, "en-sg": true, "en-tt": true, "en-us-posix": true, "en-za": true, "en-zw": true, "eo": true, "es": true, "es-419": true, "es-ar": true, "es-bo": true, "es-cl": true, "es-co": true, "es-cr": true, "es-ec": true, "es-gq": true, "es-py": true, "es-uy": true, "es-ve": true, "et": true, "eu": true, "ewo": true, "fa": true, "fa-af": true, "ff": true, "fi": true, "fil": true, "fo": true, "fr": true, "fr-be": true, "fr-ch": true, "fr-lu": true, "ga": true, "gl": true, "gsw": true, "gu": true, "guz": true, "gv": true, "ha": true, "ha-sd": true, "haw": true, "he": true, "hi": true, "hr": true, "hu": true, "hy": true, "id": true, "ig": true, "ii": true, "is": true, "it": true, "it-ch": true, "ja": true, "jgo": true, "jmc": true, "ka": true, "kab": true, "kam": true, "kde": true, "kea": true, "khq": true, "ki": true, "kk": true, "kkj": true, "kl": true, "kln": true, "km": true, "kn": true, "ko": true, "kok": true, "ks": true, "ksb": true, "ksf": true, "ku-tr": true, "kw": true, "ky": true, "lg": true, "ln": true, "lo": true, "lt": true, "lu": true, "luo": true, "luy": true, "lv": true, "mas": true, "mer": true, "mfe": true, "mg": true, "mgh": true, "mgo": true, "mk": true, "ml": true, "mn": true, "mo": true, "mr": true, "ms": true, "ms-latn-bn": true, "mt": true, "mua": true, "my": true, "naq": true, "nb": true, "nd": true, "ne": true, "nl": true, "nl-be": true, "nmg": true, "nn": true, "nnh": true, "nr": true, "nso": true, "nus": true, "nyn": true, "om": true, "or": true, "pa": true, "pa-pk": true, "pl": true, "ps": true, "pt": true, "pt-pt": true, "rm": true, "rn": true, "ro": true, "rof": true, "ru": true, "rw": true, "rwk": true, "saq": true, "sbp": true, "seh": true, "ses": true, "sg": true, "sh": true, "shi": true, "shi-latn": true, "si": true, "sk": true, "sl": true, "sn": true, "so": true, "sq": true, "sr": true, "sr-latn": true, "ss": true, "st": true, "sv": true, "sw": true, "sw-ke": true, "swc": true, "ta": true, "ta-my": true, "ta-sg": true, "te": true, "teo": true, "th": true, "ti": true, "tn": true, "to": true, "tr": true, "ts": true, "twq": true, "tzm": true, "uk": true, "ur": true, "ur-in": true, "uz-af": true, "uz-arab": true, "vai": true, "vai-latn": true, "ve": true, "vi": true, "vun": true, "xh": true, "xog": true, "yav": true, "yo": true, "zh": true, "zh-hans-hk": true, "zh-hans-mo": true, "zh-hans-sg": true, "zh-hant": true, "zh-hant-hk": true, "zh-hk": true, "zh-mo": true, "zh-tw": true, "zu": true });
apache-2.0
STMicroelectronics/cmsis_core
docs/SVD/html/search/all_1.js
120
var searchData= [ ['file_20conventions',['File Conventions',['../svd_xml_conventions_gr.html',1,'svd_Format_pg']]] ];
apache-2.0
jagatsingh/ambari-shell
src/test/java/com/sequenceiq/ambari/shell/commands/UsersCommandsTest.java
1628
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sequenceiq.ambari.shell.commands; import static org.mockito.Mockito.verify; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.sequenceiq.ambari.client.AmbariClient; import com.sequenceiq.ambari.shell.completion.Service; import com.sequenceiq.ambari.shell.model.AmbariContext; @RunWith(MockitoJUnitRunner.class) public class UsersCommandsTest { @InjectMocks private UsersCommands usersCommands; @Mock private AmbariClient client; @Mock private AmbariContext context; @Test public void testChangePassword() { usersCommands.changePassword("testuser", "oldpass", "newpass", false); verify(client).changePassword("testuser","oldpass","newpass",false); } }
apache-2.0