repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
devemux86/graphhopper
reader-gtfs/src/test/java/com/graphhopper/AnotherAgencyIT.java
5796
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH 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.graphhopper; import com.carrotsearch.hppc.IntHashSet; import com.graphhopper.reader.gtfs.*; import com.graphhopper.routing.util.AllEdgesIterator; import com.graphhopper.routing.weighting.FastestWeighting; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.Helper; import com.graphhopper.util.TranslationMap; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.time.Instant; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.util.Arrays; import java.util.Collections; import static com.graphhopper.reader.gtfs.GtfsHelper.time; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class AnotherAgencyIT { private static final String GRAPH_LOC = "target/AnotherAgencyIT"; private static PtRouteResource ptRouteResource; private static final ZoneId zoneId = ZoneId.of("America/Los_Angeles"); private static GraphHopperGtfs graphHopperGtfs; @BeforeClass public static void init() { GraphHopperConfig ghConfig = new GraphHopperConfig(); ghConfig.putObject("graph.flag_encoders", "car,foot"); ghConfig.putObject("graph.location", GRAPH_LOC); ghConfig.putObject("datareader.file", "files/beatty.osm"); ghConfig.putObject("gtfs.file", "files/sample-feed.zip,files/another-sample-feed.zip"); Helper.removeDir(new File(GRAPH_LOC)); graphHopperGtfs = new GraphHopperGtfs(ghConfig); graphHopperGtfs.init(ghConfig); graphHopperGtfs.importOrLoad(); ptRouteResource = PtRouteResource.createFactory(new TranslationMap().doImport(), graphHopperGtfs, graphHopperGtfs.getLocationIndex(), graphHopperGtfs.getGtfsStorage()) .createWithoutRealtimeFeed(); } @AfterClass public static void close() { graphHopperGtfs.close(); } @Test public void testRoute1() { Request ghRequest = new Request( Arrays.asList( new GHStationLocation("JUSTICE_COURT"), new GHStationLocation("MUSEUM") ), LocalDateTime.of(2007, 1, 1, 8, 30, 0).atZone(zoneId).toInstant() ); ghRequest.setIgnoreTransfers(true); ghRequest.setWalkSpeedKmH(0.005); // Prevent walk solution GHResponse route = ptRouteResource.route(ghRequest); assertFalse(route.hasErrors()); assertEquals(1, route.getAll().size()); ResponsePath transitSolution = route.getBest(); assertEquals("Expected total travel time == scheduled travel time + wait time", time(1, 30), transitSolution.getTime()); } @Test public void testRoute2() { Request ghRequest = new Request( Arrays.asList( new GHStationLocation("JUSTICE_COURT"), new GHStationLocation("AIRPORT") ), LocalDateTime.of(2007, 1, 1, 8, 30, 0).atZone(zoneId).toInstant() ); ghRequest.setIgnoreTransfers(true); ghRequest.setWalkSpeedKmH(0.005); // Prevent walk solution GHResponse route = ptRouteResource.route(ghRequest); assertFalse(route.hasErrors()); assertEquals(1, route.getAll().size()); ResponsePath transitSolution = route.getBest(); assertEquals(2, transitSolution.getLegs().size()); Trip.PtLeg ptLeg1 = (Trip.PtLeg) transitSolution.getLegs().get(0); assertEquals("COURT2MUSEUM", ptLeg1.route_id); assertEquals("MUSEUM1", ptLeg1.trip_id); assertEquals("JUSTICE_COURT", ptLeg1.stops.get(0).stop_id); assertEquals("MUSEUM", ptLeg1.stops.get(1).stop_id); Trip.PtLeg ptLeg2 = (Trip.PtLeg) transitSolution.getLegs().get(1); assertEquals("MUSEUM2AIRPORT", ptLeg2.route_id); assertEquals("MUSEUMAIRPORT1", ptLeg2.trip_id); assertEquals("NEXT_TO_MUSEUM", ptLeg2.stops.get(0).stop_id); assertEquals("AIRPORT", ptLeg2.stops.get(1).stop_id); assertEquals("Expected total travel time == scheduled travel time + wait time", time(2, 10), transitSolution.getTime()); } @Test public void testTransferBetweenFeeds() { Request ghRequest = new Request( Arrays.asList( new GHStationLocation("NEXT_TO_MUSEUM"), new GHStationLocation("BULLFROG") ), LocalDateTime.of(2007, 1, 1, 10, 0, 0).atZone(zoneId).toInstant() ); ghRequest.setIgnoreTransfers(true); ghRequest.setWalkSpeedKmH(0.005); // Prevent walk solution ResponsePath route = ptRouteResource.route(ghRequest).getBest(); LocalTime arrivalTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(route.getLegs().get(1).getArrivalTime().getTime()), zoneId).toLocalTime(); assertEquals("14:10", arrivalTime.toString()); } }
apache-2.0
code4wt/nutch-learning
src/java/org/apache/nutch/service/model/response/JobInfo.java
2705
/** * 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.nutch.service.model.response; import java.util.Map; import org.apache.nutch.service.JobManager.JobType; import org.apache.nutch.service.model.request.JobConfig; /** * This is the response object containing Job information * * */ public class JobInfo { public static enum State { IDLE, RUNNING, FINISHED, FAILED, KILLED, STOPPING, KILLING, ANY }; private String id; private JobType type; private String confId; private Map<String, Object> args; private Map<String, Object> result; private State state; private String msg; private String crawlId; public JobInfo(String generateId, JobConfig jobConfig, State state, String msg) { this.id = generateId; this.type = jobConfig.getType(); this.confId = jobConfig.getConfId(); this.crawlId = jobConfig.getCrawlId(); this.args = jobConfig.getArgs(); this.msg = msg; this.state = state; } public String getId() { return id; } public void setId(String id) { this.id = id; } public JobType getType() { return type; } public void setType(JobType type) { this.type = type; } public String getConfId() { return confId; } public void setConfId(String confId) { this.confId = confId; } public Map<String, Object> getArgs() { return args; } public void setArgs(Map<String, Object> args) { this.args = args; } public Map<String, Object> getResult() { return result; } public void setResult(Map<String, Object> result) { this.result = result; } public State getState() { return state; } public void setState(State state) { this.state = state; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCrawlId() { return crawlId; } public void setCrawlId(String crawlId) { this.crawlId = crawlId; } }
apache-2.0
hazelcast/hazelcast-python-client
tests/hzrc/client.py
2685
import logging from thrift import Thrift from thrift.protocol import TBinaryProtocol from thrift.transport import TSocket, TTransport from tests.hzrc import RemoteController class HzRemoteController(RemoteController.Iface): logger = logging.getLogger("HzRemoteController") def __init__(self, host, port): try: # Make socket transport = TSocket.TSocket(host=host, port=port) # Buffering is critical. Raw sockets are very slow transport = TTransport.TBufferedTransport(transport) # Wrap in a protocol protocol = TBinaryProtocol.TBinaryProtocol(transport) self.remote_controller = RemoteController.Client(protocol) # Connect! transport.open() except Thrift.TException: self.logger.exception("Something went wrong while connecting to remote controller.") def ping(self): return self.remote_controller.ping() def clean(self): return self.remote_controller.clean() def exit(self): self.remote_controller.exit() self.remote_controller._iprot.trans.close() def createCluster(self, hz_version, xml_config): return self.remote_controller.createCluster(hz_version, xml_config) def createClusterKeepClusterName(self, hz_version, xml_config): return self.remote_controller.createClusterKeepClusterName(hz_version, xml_config) def startMember(self, cluster_id): return self.remote_controller.startMember(cluster_id) def shutdownMember(self, cluster_id, member_id): return self.remote_controller.shutdownMember(cluster_id, member_id) def terminateMember(self, cluster_id, member_id): return self.remote_controller.terminateMember(cluster_id, member_id) def suspendMember(self, cluster_id, member_id): return self.remote_controller.suspendMember(cluster_id, member_id) def resumeMember(self, cluster_id, member_id): return self.remote_controller.resumeMember(cluster_id, member_id) def shutdownCluster(self, cluster_id): return self.remote_controller.shutdownCluster(cluster_id) def terminateCluster(self, cluster_id): return self.remote_controller.terminateCluster(cluster_id) def splitMemberFromCluster(self, member_id): return self.remote_controller.splitMemberFromCluster(member_id) def mergeMemberToCluster(self, cluster_id, member_id): return self.remote_controller.mergeMemberToCluster(cluster_id, member_id) def executeOnController(self, cluster_id, script, lang): return self.remote_controller.executeOnController(cluster_id, script, lang)
apache-2.0
scott-taylor/toolkit
toolkit-chains/src/main/java/org/tewls/toolkit/chains/SideEffect.java
1157
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tewls.toolkit.chains; /** * A side effect isn't interested in what is flowing through the chain, only that something is * flowing through the chain. They typically interact with other objects than those flowing through * the system. * * For example: Starting and stopping a stop watch to track execution time. * * SideEffects should normally propagate back any object returned or exception thrown from the * chain. * * @author Scott Taylor */ public interface SideEffect { <O> O process(Outputter<O> chain); }
apache-2.0
consulo/consulo-javascript
web-browser-impl/src/main/java/consulo/javascript/client/module/extension/ClientJavaScriptModuleExtension.java
3862
package consulo.javascript.client.module.extension; import javax.annotation.Nonnull; import org.jdom.Element; import javax.annotation.Nullable; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.SdkTable; import com.intellij.openapi.projectRoots.SdkType; import consulo.annotation.access.RequiredReadAction; import consulo.javascript.client.module.sdk.ClientJavaScriptSdkType; import consulo.javascript.lang.StandardJavaScriptVersions; import consulo.javascript.module.extension.JavaScriptModuleExtension; import consulo.lang.LanguageVersion; import consulo.module.extension.ModuleInheritableNamedPointer; import consulo.module.extension.impl.ModuleExtensionImpl; import consulo.module.extension.impl.ModuleInheritableNamedPointerImpl; import consulo.roots.ModuleRootLayer; import consulo.roots.impl.ModuleRootLayerImpl; import consulo.util.pointers.NamedPointer; /** * @author VISTALL * @since 29.06.14 */ public class ClientJavaScriptModuleExtension extends ModuleExtensionImpl<ClientJavaScriptModuleExtension> implements JavaScriptModuleExtension<ClientJavaScriptModuleExtension> { private ModuleInheritableNamedPointerImpl<Sdk> myPointer; protected LanguageVersion myLanguageVersion = StandardJavaScriptVersions.getInstance().getDefaultVersion(); public ClientJavaScriptModuleExtension(@Nonnull String id, @Nonnull ModuleRootLayer rootLayer) { super(id, rootLayer); myPointer = new ModuleInheritableNamedPointerImpl<Sdk>(rootLayer, id) { @Nullable @Override public String getItemNameFromModule(@Nonnull Module module) { ClientJavaScriptModuleExtension extension = ModuleUtilCore.getExtension(module, ClientJavaScriptModuleExtension.class); if(extension == null) { return null; } return extension.getSdkName(); } @Nullable @Override public Sdk getItemFromModule(@Nonnull Module module) { ClientJavaScriptModuleExtension extension = ModuleUtilCore.getExtension(module, ClientJavaScriptModuleExtension.class); if(extension == null) { return null; } return extension.getSdk(); } @Nonnull @Override public NamedPointer<Sdk> getPointer(@Nonnull ModuleRootLayer moduleRootLayer, @Nonnull String name) { return ((ModuleRootLayerImpl)moduleRootLayer).getRootModel().getConfigurationAccessor().getSdkPointer(name); } }; Sdk sdkByType = SdkTable.getInstance().findPredefinedSdkByType(ClientJavaScriptSdkType.getInstance()); myPointer.set(null, sdkByType); } @RequiredReadAction @Override protected void loadStateImpl(@Nonnull Element element) { super.loadStateImpl(element); myLanguageVersion = StandardJavaScriptVersions.getInstance().findVersionById(element.getAttributeValue("language-version")); } @Override protected void getStateImpl(@Nonnull Element element) { super.getStateImpl(element); if(myLanguageVersion != StandardJavaScriptVersions.getInstance().getDefaultVersion()) { element.setAttribute("language-version", myLanguageVersion.getId()); } } @Nonnull @Override public ModuleInheritableNamedPointer<Sdk> getInheritableSdk() { return myPointer; } @Nullable @Override public Sdk getSdk() { return myPointer.get(); } @Nullable @Override public String getSdkName() { return myPointer.getName(); } @Nonnull @Override public Class<? extends SdkType> getSdkTypeClass() { throw new IllegalArgumentException(); } @Nonnull @Override public LanguageVersion getLanguageVersion() { return myLanguageVersion; } @RequiredReadAction @Override public void commit(@Nonnull ClientJavaScriptModuleExtension mutableModuleExtension) { super.commit(mutableModuleExtension); myLanguageVersion = mutableModuleExtension.getLanguageVersion(); } }
apache-2.0
ubastation/ubastation
spec/models/competition_article_spec.rb
618
# encoding: utf-8 # == Schema Information # # Table name: competition_articles # # id :integer not null, primary key # title :string(255) not null # body :text not null # link :string(255) # show_comments :boolean default(TRUE), not null # competition_id :integer not null # slug :string(255) not null # created_at :datetime not null # updated_at :datetime not null # require 'spec_helper' describe CompetitionArticle do pending "add some examples to (or delete) #{__FILE__}" end
apache-2.0
Ariah-Group/Finance
af_webapp/src/main/java/org/kuali/kfs/sys/document/web/AccountingLineViewSequenceNumberField.java
5000
/* * Copyright 2008 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.kfs.sys.document.web; import java.util.List; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.web.renderers.PersistingTagRenderer; import org.kuali.kfs.sys.document.web.renderers.StringRenderer; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.kns.web.ui.Field; /** * A class to represent the rendering of a sequence number field */ public class AccountingLineViewSequenceNumberField extends FieldTableJoiningWithHeader { private String name = KFSConstants.AccountingLineViewStandardBlockNames.SEQUENCE_NUMBER_BLOCK; private String newLineLabelProperty = "accounting.line.new.line.sequence.number"; /** * Sequence numbers are always read only * @see org.kuali.kfs.sys.document.web.AccountingLineViewRenderableElementField#isReadOnly() */ public boolean isReadOnly() { return true; } /** * Returns the name of this sequence number field * @see org.kuali.kfs.sys.document.web.TableJoining#getName() */ public String getName() { return name; } /** * Sets the name of this sequence number field * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @see org.kuali.kfs.sys.document.web.TableJoiningWithHeader#getHeaderLabelProperty() */ public String getHeaderLabelProperty() { return this.name; } /** * @see org.kuali.kfs.sys.document.web.FieldTableJoining#createTableCell() */ @Override protected AccountingLineTableCell createTableCell() { AccountingLineTableCell cell = super.createTableCell(); cell.setRendersAsHeader(true); return cell; } /** * @see org.kuali.kfs.sys.document.web.RenderableElement#renderElement(javax.servlet.jsp.PageContext, javax.servlet.jsp.tagext.Tag, org.kuali.kfs.sys.document.web.AccountingLineRenderingContext) */ public void renderElement(PageContext pageContext, Tag parentTag, AccountingLineRenderingContext renderingContext) throws JspException { if (renderingContext.isNewLine()) { StringRenderer renderer = new StringRenderer(); renderer.setStringToRender(SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(newLineLabelProperty)); renderer.render(pageContext, parentTag); renderer.clear(); } else { PersistingTagRenderer renderer = new PersistingTagRenderer(); renderer.setStringToRender(getDisplaySequenceNumber(renderingContext)); renderer.setValueToPersist(renderingContext.getAccountingLine().getSequenceNumber().toString()); renderer.setPersistingProperty(renderingContext.getAccountingLinePropertyPath()+".sequenceNumber"); renderer.render(pageContext, parentTag); renderer.clear(); } } /** * Given the rendering context, returns what the sequence number of the line to be rendered is * @param renderingContext the rendering context which holds the accounting line * @return the sequence number to render (not the one to store as a value) */ protected String getDisplaySequenceNumber(AccountingLineRenderingContext renderingContext) { return renderingContext.getAccountingLine().getSequenceNumber().toString(); } /** * @see org.kuali.kfs.sys.document.web.TableJoiningWithHeader#createHeaderLabel() */ public HeaderLabel createHeaderLabel() { return new LiteralHeaderLabel("&nbsp;"); } /** * sequence number is never really related to lookups, so this implementation does nothing * @see org.kuali.kfs.sys.document.web.RenderableElement#appendFieldNames(java.util.List) * * KRAD Conversion: Customization of adding the fields - No use of data dictionary */ public void appendFields(List<Field> fields) { // take a nap } /** * Does nothing * @see org.kuali.kfs.sys.document.web.RenderableElement#populateWithTabIndexIfRequested(int[], int) */ public void populateWithTabIndexIfRequested(int reallyHighIndex) { } }
apache-2.0
cvandeplas/plaso
plaso/lib/bufferlib_test.py
1850
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # 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. """Tests for plaso.lib.buffer""" import unittest from plaso.lib import bufferlib class TestBuffer(unittest.TestCase): """Test the circular buffer.""" def testBuffer(self): items = range(1, 11) circular_buffer = bufferlib.CircularBuffer(10) self.assertEquals(len(circular_buffer), 10) self.assertEquals(circular_buffer.size, 10) self.assertTrue(circular_buffer.GetCurrent() is None) for item in items: circular_buffer.Append(item) self.assertEquals(circular_buffer.GetCurrent(), item) self.assertEquals(circular_buffer.size, 10) content = list(circular_buffer) self.assertEquals(items, content) circular_buffer.Append(11) self.assertEquals( [2, 3, 4, 5, 6, 7, 8, 9, 10, 11], list(circular_buffer.Flush())) self.assertEquals(circular_buffer.GetCurrent(), None) new_items = range(1, 51) for item in new_items: circular_buffer.Append(item) self.assertEquals(circular_buffer.GetCurrent(), item) self.assertEquals(circular_buffer.size, 10) self.assertEquals(range(41, 51), list(circular_buffer)) if __name__ == '__main__': unittest.main()
apache-2.0
jasongardnerlv/alakazam
alakazam-ws/src/test/java/io/alakazam/jaxws/JAXWSBundleTest.java
4634
package io.alakazam.jaxws; import io.alakazam.jetty.setup.ServletEnvironment; import io.alakazam.lifecycle.ServerLifecycleListener; import io.alakazam.lifecycle.setup.LifecycleEnvironment; import io.alakazam.setup.Bootstrap; import io.alakazam.setup.Environment; import org.junit.Before; import org.junit.Test; import javax.servlet.Servlet; import javax.servlet.ServletRegistration; import javax.servlet.http.HttpServlet; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.*; public class JAXWSBundleTest { Environment environment = mock(Environment.class); Bootstrap bootstrap = mock(Bootstrap.class); ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); ServletRegistration.Dynamic servlet = mock(ServletRegistration.Dynamic.class); JAXWSEnvironment jaxwsEnvironment = mock(JAXWSEnvironment.class); LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); @Before public void setUp() { when(environment.servlets()).thenReturn(servletEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(servletEnvironment.addServlet(anyString(), any(HttpServlet.class))).thenReturn(servlet); when(jaxwsEnvironment.buildServlet()).thenReturn(mock(HttpServlet.class)); when(jaxwsEnvironment.getDefaultPath()).thenReturn("/soap"); } @Test public void constructorArgumentChecks() { try { new JAXWSBundle(null, null); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(IllegalArgumentException.class))); } try { new JAXWSBundle("soap", null); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(IllegalArgumentException.class))); } } @Test public void initializeAndRun() { JAXWSBundle jaxwsBundle = new JAXWSBundle("/soap", jaxwsEnvironment); try { jaxwsBundle.run(null); } catch (Exception e) { assertThat(e, is(instanceOf(IllegalArgumentException.class))); } jaxwsBundle.initialize(bootstrap); jaxwsBundle.run(environment); verify(servletEnvironment).addServlet(eq("CXF Servlet"), any(Servlet.class)); verify(lifecycleEnvironment).addServerLifecycleListener(any(ServerLifecycleListener.class)); verify(servlet).addMapping("/soap/*"); } @Test public void publishEndpoint() { JAXWSBundle jaxwsBundle = new JAXWSBundle("/soap", jaxwsEnvironment); Object service = new Object(); try { jaxwsBundle.publishEndpoint(new EndpointBuilder("foo", null)); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(IllegalArgumentException.class))); } try { jaxwsBundle.publishEndpoint(new EndpointBuilder(null, service)); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(IllegalArgumentException.class))); } try { jaxwsBundle.publishEndpoint(new EndpointBuilder(" ", service)); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(IllegalArgumentException.class))); } EndpointBuilder builder = mock(EndpointBuilder.class); jaxwsBundle.publishEndpoint(builder); verify(jaxwsEnvironment).publishEndpoint(builder); } @Test public void getClient() { JAXWSBundle jaxwsBundle = new JAXWSBundle("/soap", jaxwsEnvironment); Class<?> cls = Object.class; String url = "http://foo"; try { jaxwsBundle.getClient(new ClientBuilder<>(null, null)); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(IllegalArgumentException.class))); } try { jaxwsBundle.getClient(new ClientBuilder<>(null, url)); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(IllegalArgumentException.class))); } try { jaxwsBundle.getClient(new ClientBuilder<>(cls, " ")); fail(); } catch (Exception e) { assertThat(e, is(instanceOf(IllegalArgumentException.class))); } ClientBuilder builder = new ClientBuilder<>(cls, url); jaxwsBundle.getClient(builder); verify(jaxwsEnvironment).getClient(builder); } }
apache-2.0
stevespringett/Alpine
alpine/src/main/java/alpine/filters/package-info.java
84
/** * This package contains JAX-RS and Servlet filters. */ package alpine.filters;
apache-2.0
lisaglendenning/zookeeper-lite
zkcore/src/main/java/edu/uw/zookeeper/netty/ChannelConnection.java
1963
package edu.uw.zookeeper.netty; import io.netty.channel.Channel; import java.util.Collection; import java.util.Collections; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import edu.uw.zookeeper.net.Connection; public class ChannelConnection<I,O> extends AbstractChannelConnection<I,O,ChannelConnection<I,O>> { public static <I,O> ChannelConnection<I,O> defaults( Class<? extends O> type, Channel channel) { Collection<Connection.Listener<? super O>> listeners = Collections.emptySet(); return withListeners(type, channel, listeners); } public static <I,O> ChannelConnection<I,O> withListeners( Class<? extends O> type, Channel channel, Collection<? extends Connection.Listener<? super O>> listeners) { Logger logger = LogManager.getLogger(ChannelConnection.class); EventfulHandler<O> eventful = EventfulHandler.withLogger(type, logger); ConnectionStateHandler state = ConnectionStateHandler.withLogger(logger); return newInstance(channel, eventful, state, listeners, logger); } public static <I,O> ChannelConnection<I,O> newInstance( Channel channel, EventfulHandler<? extends O> eventful, ConnectionStateHandler state, Collection<? extends Connection.Listener<? super O>> listeners, Logger logger) { return new ChannelConnection<I,O>(channel, eventful, state, listeners, logger); } protected ChannelConnection( Channel channel, EventfulHandler<? extends O> eventful, ConnectionStateHandler state, Collection<? extends Connection.Listener<? super O>> listeners, Logger logger) { super(channel, eventful, state, listeners, logger); } @Override protected ChannelConnection<I,O> self() { return this; } }
apache-2.0
rmp91/jitd
java/src/jitd/test/RegressionTest.java
1467
package jitd.test; import jitd.Cog; import jitd.CrackerMode; import jitd.Driver; import jitd.Mode; import jitd.PushdownMergeMode; import org.junit.Ignore; import org.junit.Test; public class RegressionTest extends CogTest { public Driver merge(Cog root) { return new Driver(new PushdownMergeMode(), root); } public Driver crack(Cog root) { return new Driver(new CrackerMode(), root); } @Test public void simBadger() { srand(42); Cog root = array(randArray(20000, 1000000)); Driver d = crack(root); Mode merge = new PushdownMergeMode(); Mode crack = d.mode; d.dump(); d.scan(100000, 180000); d.dump(); d.root = concat( d.root, array(randArray(20000, 1000000)) ); d.dump(); d.scan(40000, 80000); d.dump(); d.mode = merge; d.scan(110000, 115000); d.dump(); d.scan(115000, 2000000); d.dump(); } @Ignore @Test public void adaptiveMergeShouldWipeOutEmptyPartitions() { Cog root = bnode(8656, concat( bnode(9712, sorted(new long[] { 8656, 9500 }), sorted(new long[] { 9800, 9900 }) ), bnode(8656, sorted(new long[] { 8656, 8728 }), empty() ) ), sorted(new long[] { 1000, 2000, 3000, 4000, 5000 }) ); Driver d = merge(root); d.dump(); d.scan(8656, 8700); d.dump(); } }
apache-2.0
Linggify/AtticEngine
attic/properties/src/main/java/com/github/linggify/attic/properties/SpriteRendererProperty.java
3494
package com.github.linggify.attic.properties; import com.github.linggify.attic.render.IContext.VertexAttribute; import com.github.linggify.attic.render.RenderData; import com.github.linggify.attic.util.Color; import com.github.linggify.attic.util.Matrix33; import com.github.linggify.attic.util.Vector2D; /** * The SpriteRendererProperty is used to render Textured Quads at a specific * transorm * * @author Fredie * */ public class SpriteRendererProperty extends BaseProperty<RenderData> { private RenderData mData; private boolean mHasTransform; private PropertyListener mTransformChangeListener; private Matrix33 mTransform; /** * Creates a new {@link SpriteRendererProperty} with static or non static * {@link RenderData} * * @param isStatic */ public SpriteRendererProperty(boolean isStatic) { super(); // setup sprite mData = new RenderData(4, isStatic, VertexAttribute.POSITION, VertexAttribute.COLOR, VertexAttribute.TEX_COORD_0); // corners mData.setVertexData(0, VertexAttribute.POSITION, new Vector2D(0.5f, -0.5f)); mData.setVertexData(1, VertexAttribute.POSITION, new Vector2D(-0.5f, -0.5f)); mData.setVertexData(2, VertexAttribute.POSITION, new Vector2D(-0.5f, 0.5f)); mData.setVertexData(3, VertexAttribute.POSITION, new Vector2D(0.5f, 0.5f)); // color white Color white = new Color(1, 1, 1, 1); mData.setVertexData(0, VertexAttribute.COLOR, white); mData.setVertexData(1, VertexAttribute.COLOR, white); mData.setVertexData(2, VertexAttribute.COLOR, white); mData.setVertexData(3, VertexAttribute.COLOR, white); // texture coordinates mData.setVertexData(0, VertexAttribute.TEX_COORD_0, new Vector2D(1, 1)); mData.setVertexData(1, VertexAttribute.TEX_COORD_0, new Vector2D(0, 1)); mData.setVertexData(2, VertexAttribute.TEX_COORD_0, new Vector2D(0, 0)); mData.setVertexData(3, VertexAttribute.TEX_COORD_0, new Vector2D(1, 0)); // use transform changelistener mHasTransform = false; mTransformChangeListener = (target, event) -> { if (mHasTransform) { if (target instanceof TransformProperty) { if (event == PropertyEvent.PROPERTY_CHANGED) mTransform = ((TransformProperty) target).get(); else if (event == PropertyEvent.PROPERTY_REMOVED || event == PropertyEvent.PROPERTY_DISABLED) { target.removeListener(mTransformChangeListener); mHasTransform = false; mTransform = new Matrix33(); } } } }; } /** * Sets the Color of this {@link SpriteRendererProperty} * * @param color */ public void setTint(Color color) { // color white mData.setVertexData(0, VertexAttribute.COLOR, color); mData.setVertexData(1, VertexAttribute.COLOR, color); mData.setVertexData(2, VertexAttribute.COLOR, color); mData.setVertexData(3, VertexAttribute.COLOR, color); } @Override public Class<RenderData> getContentType() { return RenderData.class; } @Override public void update(double delta) { // do nothing here } @Override public RenderData get() { //if there is no transform, search for one if(!mHasTransform && hasParent()) { TransformProperty property = getParent().propertyByType(TransformProperty.class); if(property != null) { property.addListener(mTransformChangeListener); mHasTransform = true; } } //set transform and return mData.setTransform(mTransform); return mData; } }
apache-2.0
serilog/serilog-sinks-amazonkinesis
src/Serilog.Sinks.Amazon.Kinesis/Firehose/KinesisFirehoseLoggerConfigurationExtensions.cs
4870
// Copyright 2014 Serilog Contributors // // 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. using System; using Amazon.KinesisFirehose; using Serilog.Configuration; using Serilog.Core; using Serilog.Events; using Serilog.Formatting; using Serilog.Sinks.Amazon.Kinesis.Common; using Serilog.Sinks.Amazon.Kinesis.Firehose.Sinks; namespace Serilog.Sinks.Amazon.Kinesis.Firehose { /// <summary> /// Adds the WriteTo.AmazonKinesisFirehose() extension method to <see cref="LoggerConfiguration"/>. /// </summary> public static class KinesisFirehoseLoggerConfigurationExtensions { /// <summary> /// Adds a sink that writes log events as documents to Amazon Kinesis Firehose. /// </summary> /// <param name="loggerConfiguration">The logger configuration.</param> /// <param name="options"></param> /// <param name="kinesisFirehoseClient"></param> /// <returns>Logger configuration, allowing configuration to continue.</returns> /// <exception cref="ArgumentNullException">A required parameter is null.</exception> public static LoggerConfiguration AmazonKinesisFirehose( this LoggerSinkConfiguration loggerConfiguration, KinesisFirehoseSinkOptions options, IAmazonKinesisFirehose kinesisFirehoseClient) { if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration"); if (options == null) throw new ArgumentNullException("options"); ILogEventSink sink; if (options.BufferBaseFilename == null) { sink = new KinesisFirehoseSink(options, kinesisFirehoseClient); } else { sink = new DurableKinesisFirehoseSink(options, kinesisFirehoseClient); } return loggerConfiguration.Sink(sink, options.MinimumLogEventLevel ?? LevelAlias.Minimum); } /// <summary> /// Adds a sink that writes log events as documents to Amazon Kinesis. /// </summary> /// <param name="loggerConfiguration">The logger configuration.</param> /// <param name="kinesisFirehoseClient"></param> /// <param name="streamName"></param> /// <param name="bufferBaseFilename"></param> /// <param name="bufferFileSizeLimitBytes"></param> /// <param name="batchPostingLimit"></param> /// <param name="period"></param> /// <param name="minimumLogEventLevel"></param> /// <param name="onLogSendError"></param> /// <param name="shared"></param> /// <returns>Logger configuration, allowing configuration to continue.</returns> /// <exception cref="ArgumentNullException"></exception> public static LoggerConfiguration AmazonKinesisFirehose( this LoggerSinkConfiguration loggerConfiguration, IAmazonKinesisFirehose kinesisFirehoseClient, string streamName, string bufferBaseFilename = null, int? bufferFileSizeLimitBytes = null, int? batchPostingLimit = null, TimeSpan? period = null, ITextFormatter customFormatter = null, LogEventLevel? minimumLogEventLevel = null, EventHandler<LogSendErrorEventArgs> onLogSendError = null, bool shared = false) { if (kinesisFirehoseClient == null) throw new ArgumentNullException("kinesisFirehoseClient"); if (streamName == null) throw new ArgumentNullException("streamName"); var options = new KinesisFirehoseSinkOptions(streamName) { BufferFileSizeLimitBytes = bufferFileSizeLimitBytes, BufferBaseFilename = bufferBaseFilename == null ? null : bufferBaseFilename + ".firehose", Period = period ?? KinesisSinkOptionsBase.DefaultPeriod, BatchPostingLimit = batchPostingLimit ?? KinesisSinkOptionsBase.DefaultBatchPostingLimit, MinimumLogEventLevel = minimumLogEventLevel ?? LevelAlias.Minimum, OnLogSendError = onLogSendError, CustomDurableFormatter = customFormatter, Shared = shared }; return AmazonKinesisFirehose(loggerConfiguration, options, kinesisFirehoseClient); } } }
apache-2.0
ribbon-xx/VTVPro-Plus
VtvPro/src/mdn/vtvsport/fragment/RegisterFragment.java
2009
package mdn.vtvsport.fragment; import mdn.vtvsport.R; import mdn.vtvsport.common.ImageUtility; import android.graphics.Bitmap; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.assist.ImageScaleType; public class RegisterFragment extends BaseFragment { private ImageView ivRegister; private int mTypeCategory = 0; //0_channel,1_vod,2_series of vod, 3_search, // -2 favourist; -1 listnew; -3 listhot @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_guide_register, null); } @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); ivRegister = (ImageView) getView().findViewById(R.id.iv_register); // String imageUri = "assets://image.png"; // from assets String imageUri = "drawable://" + R.drawable.dangky; DisplayImageOptions options = new DisplayImageOptions.Builder() .cacheInMemory() .cacheOnDisc() .bitmapConfig(Bitmap.Config.RGB_565) .showImageForEmptyUri(R.drawable.no_image) .showImageOnFail(R.drawable.no_image) .showStubImage(R.drawable.no_image) .imageScaleType(ImageScaleType.NONE) .build(); ImageUtility.loadFullBitmapFromUrl(getActivity(), imageUri, ivRegister, options); } @Override protected void initUiTabbar() { // TODO Auto-generated method stub super.initUiTabbar(); // baseSlideMenuActivity.iconInteract.setVisibility(View.GONE); baseSlideMenuActivity.iconSetting.setVisibility(View.GONE); baseSlideMenuActivity.iconBack.setVisibility(View.VISIBLE); baseSlideMenuActivity.iconVtvPlus.setVisibility(View.GONE); if (mTypeCategory != 3) { baseSlideMenuActivity.closeViewSearch(); } } }
apache-2.0
sallyom/online-hibernation
vendor/github.com/go-openapi/spec/expander_test.go
45380
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "runtime" "testing" "github.com/go-openapi/jsonpointer" "github.com/go-openapi/swag" "github.com/stretchr/testify/assert" ) func jsonDoc(path string) (json.RawMessage, error) { data, err := swag.LoadFromFileOrHTTP(path) if err != nil { return nil, err } return json.RawMessage(data), nil } // tests that paths are normalized correctly func TestNormalizePaths(t *testing.T) { type testNormalizePathsTestCases []struct { refPath string base string expOutput string } testCases := func() testNormalizePathsTestCases { testCases := testNormalizePathsTestCases{ { // http basePath, absolute refPath refPath: "http://www.anotherexample.com/another/base/path/swagger.json#/definitions/Pet", base: "http://www.example.com/base/path/swagger.json", expOutput: "http://www.anotherexample.com/another/base/path/swagger.json#/definitions/Pet", }, { // http basePath, relative refPath refPath: "another/base/path/swagger.json#/definitions/Pet", base: "http://www.example.com/base/path/swagger.json", expOutput: "http://www.example.com/base/path/another/base/path/swagger.json#/definitions/Pet", }, } if runtime.GOOS == "windows" { testCases = append(testCases, testNormalizePathsTestCases{ { // file basePath, absolute refPath, no fragment refPath: `C:\another\base\path.json`, base: `C:\base\path.json`, expOutput: `C:\another\base\path.json`, }, { // file basePath, absolute refPath refPath: `C:\another\base\path.json#/definitions/Pet`, base: `C:\base\path.json`, expOutput: `C:\another\base\path.json#/definitions/Pet`, }, { // file basePath, relative refPath refPath: `another\base\path.json#/definitions/Pet`, base: `C:\base\path.json`, expOutput: `C:\base\another\base\path.json#/definitions/Pet`, }, }...) return testCases } // linux case testCases = append(testCases, testNormalizePathsTestCases{ { // file basePath, absolute refPath, no fragment refPath: "/another/base/path.json", base: "/base/path.json", expOutput: "/another/base/path.json", }, { // file basePath, absolute refPath refPath: "/another/base/path.json#/definitions/Pet", base: "/base/path.json", expOutput: "/another/base/path.json#/definitions/Pet", }, { // file basePath, relative refPath refPath: "another/base/path.json#/definitions/Pet", base: "/base/path.json", expOutput: "/base/another/base/path.json#/definitions/Pet", }, }...) return testCases }() for _, tcase := range testCases { out := normalizePaths(tcase.refPath, tcase.base) assert.Equal(t, tcase.expOutput, out) } } func TestExpandsKnownRef(t *testing.T) { schema := RefProperty("http://json-schema.org/draft-04/schema#") if assert.NoError(t, ExpandSchema(schema, nil, nil)) { assert.Equal(t, "Core schema meta-schema", schema.Description) } } func TestExpandResponseSchema(t *testing.T) { fp := "./fixtures/local_expansion/spec.json" b, err := jsonDoc(fp) if assert.NoError(t, err) { var spec Swagger if err := json.Unmarshal(b, &spec); assert.NoError(t, err) { err := ExpandSpec(&spec, &ExpandOptions{RelativeBase: fp}) if assert.NoError(t, err) { sch := spec.Paths.Paths["/item"].Get.Responses.StatusCodeResponses[200].Schema if assert.NotNil(t, sch) { assert.Empty(t, sch.Ref.String()) assert.Contains(t, sch.Type, "object") assert.Len(t, sch.Properties, 2) } } } } } func TestSpecExpansion(t *testing.T) { spec := new(Swagger) // resolver, err := defaultSchemaLoader(spec, nil, nil) // assert.NoError(t, err) err := ExpandSpec(spec, nil) assert.NoError(t, err) specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") assert.NoError(t, err) specPath, _ := absPath("fixtures/expansion/all-the-things.json") opts := &ExpandOptions{ RelativeBase: specPath, } spec = new(Swagger) err = json.Unmarshal(specDoc, spec) assert.NoError(t, err) pet := spec.Definitions["pet"] errorModel := spec.Definitions["errorModel"] petResponse := spec.Responses["petResponse"] petResponse.Schema = &pet stringResponse := spec.Responses["stringResponse"] tagParam := spec.Parameters["tag"] idParam := spec.Parameters["idParam"] err = ExpandSpec(spec, opts) assert.NoError(t, err) assert.Equal(t, tagParam, spec.Parameters["query"]) assert.Equal(t, petResponse, spec.Responses["petResponse"]) assert.Equal(t, petResponse, spec.Responses["anotherPet"]) assert.Equal(t, pet, *spec.Responses["petResponse"].Schema) assert.Equal(t, stringResponse, *spec.Paths.Paths["/"].Get.Responses.Default) assert.Equal(t, petResponse, spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200]) assert.Equal(t, pet, *spec.Paths.Paths["/pets"].Get.Responses.StatusCodeResponses[200].Schema.Items.Schema) assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Get.Responses.Default.Schema) assert.Equal(t, pet, spec.Definitions["petInput"].AllOf[0]) assert.Equal(t, spec.Definitions["petInput"], *spec.Paths.Paths["/pets"].Post.Parameters[0].Schema) assert.Equal(t, petResponse, spec.Paths.Paths["/pets"].Post.Responses.StatusCodeResponses[200]) assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Post.Responses.Default.Schema) pi := spec.Paths.Paths["/pets/{id}"] assert.Equal(t, idParam, pi.Get.Parameters[0]) assert.Equal(t, petResponse, pi.Get.Responses.StatusCodeResponses[200]) assert.Equal(t, errorModel, *pi.Get.Responses.Default.Schema) assert.Equal(t, idParam, pi.Delete.Parameters[0]) assert.Equal(t, errorModel, *pi.Delete.Responses.Default.Schema) } func TestResolveRef(t *testing.T) { var root interface{} err := json.Unmarshal([]byte(PetStore20), &root) assert.NoError(t, err) ref, err := NewRef("#/definitions/Category") assert.NoError(t, err) sch, err := ResolveRef(root, &ref) assert.NoError(t, err) b, _ := sch.MarshalJSON() assert.JSONEq(t, `{"id":"Category","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}}}`, string(b)) } func TestResponseExpansion(t *testing.T) { specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") assert.NoError(t, err) basePath, err := absPath("fixtures/expansion/all-the-things.json") assert.NoError(t, err) spec := new(Swagger) err = json.Unmarshal(specDoc, spec) assert.NoError(t, err) resolver, err := defaultSchemaLoader(spec, nil, nil) assert.NoError(t, err) resp := spec.Responses["anotherPet"] r := spec.Responses["petResponse"] err = expandResponse(&r, resolver, basePath) assert.NoError(t, err) expected := r err = expandResponse(&resp, resolver, basePath) // b, _ := resp.MarshalJSON() // log.Printf(string(b)) // b, _ = expected.MarshalJSON() // log.Printf(string(b)) assert.NoError(t, err) assert.Equal(t, expected, resp) resp2 := spec.Paths.Paths["/"].Get.Responses.Default expected = spec.Responses["stringResponse"] err = expandResponse(resp2, resolver, basePath) assert.NoError(t, err) assert.Equal(t, expected, *resp2) resp = spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200] expected = spec.Responses["petResponse"] err = expandResponse(&resp, resolver, basePath) assert.NoError(t, err) // assert.Equal(t, expected, resp) } // test the exported version of ExpandResponse func TestExportedResponseExpansion(t *testing.T) { specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") assert.NoError(t, err) basePath, err := absPath("fixtures/expansion/all-the-things.json") assert.NoError(t, err) spec := new(Swagger) err = json.Unmarshal(specDoc, spec) assert.NoError(t, err) resp := spec.Responses["anotherPet"] r := spec.Responses["petResponse"] err = ExpandResponse(&r, basePath) assert.NoError(t, err) expected := r err = ExpandResponse(&resp, basePath) // b, _ := resp.MarshalJSON() // log.Printf(string(b)) // b, _ = expected.MarshalJSON() // log.Printf(string(b)) assert.NoError(t, err) assert.Equal(t, expected, resp) resp2 := spec.Paths.Paths["/"].Get.Responses.Default expected = spec.Responses["stringResponse"] err = ExpandResponse(resp2, basePath) assert.NoError(t, err) assert.Equal(t, expected, *resp2) resp = spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200] expected = spec.Responses["petResponse"] err = ExpandResponse(&resp, basePath) assert.NoError(t, err) // assert.Equal(t, expected, resp) } func TestIssue3(t *testing.T) { spec := new(Swagger) specDoc, err := jsonDoc("fixtures/expansion/overflow.json") assert.NoError(t, err) specPath, _ := absPath("fixtures/expansion/overflow.json") opts := &ExpandOptions{ RelativeBase: specPath, } err = json.Unmarshal(specDoc, spec) assert.NoError(t, err) assert.NotPanics(t, func() { err = ExpandSpec(spec, opts) assert.NoError(t, err) }, "Calling expand spec with circular refs, should not panic!") } func TestParameterExpansion(t *testing.T) { paramDoc, err := jsonDoc("fixtures/expansion/params.json") assert.NoError(t, err) spec := new(Swagger) err = json.Unmarshal(paramDoc, spec) assert.NoError(t, err) basePath, err := absPath("fixtures/expansion/params.json") assert.NoError(t, err) resolver, err := defaultSchemaLoader(spec, nil, nil) assert.NoError(t, err) param := spec.Parameters["query"] expected := spec.Parameters["tag"] err = expandParameter(&param, resolver, basePath) assert.NoError(t, err) assert.Equal(t, expected, param) param = spec.Paths.Paths["/cars/{id}"].Parameters[0] expected = spec.Parameters["id"] err = expandParameter(&param, resolver, basePath) assert.NoError(t, err) assert.Equal(t, expected, param) } func TestExportedParameterExpansion(t *testing.T) { paramDoc, err := jsonDoc("fixtures/expansion/params.json") assert.NoError(t, err) spec := new(Swagger) err = json.Unmarshal(paramDoc, spec) assert.NoError(t, err) basePath, err := absPath("fixtures/expansion/params.json") assert.NoError(t, err) param := spec.Parameters["query"] expected := spec.Parameters["tag"] err = ExpandParameter(&param, basePath) assert.NoError(t, err) assert.Equal(t, expected, param) param = spec.Paths.Paths["/cars/{id}"].Parameters[0] expected = spec.Parameters["id"] err = ExpandParameter(&param, basePath) assert.NoError(t, err) assert.Equal(t, expected, param) } func TestCircularRefsExpansion(t *testing.T) { carsDoc, err := jsonDoc("fixtures/expansion/circularRefs.json") assert.NoError(t, err) basePath, _ := absPath("fixtures/expansion/circularRefs.json") spec := new(Swagger) err = json.Unmarshal(carsDoc, spec) assert.NoError(t, err) resolver, err := defaultSchemaLoader(spec, nil, nil) assert.NoError(t, err) schema := spec.Definitions["car"] assert.NotPanics(t, func() { _, err = expandSchema(schema, []string{"#/definitions/car"}, resolver, basePath) assert.NoError(t, err) }, "Calling expand schema with circular refs, should not panic!") } func TestContinueOnErrorExpansion(t *testing.T) { missingRefDoc, err := jsonDoc("fixtures/expansion/missingRef.json") assert.NoError(t, err) specPath, _ := absPath("fixtures/expansion/missingRef.json") testCase := struct { Input *Swagger `json:"input"` Expected *Swagger `json:"expected"` }{} err = json.Unmarshal(missingRefDoc, &testCase) assert.NoError(t, err) opts := &ExpandOptions{ ContinueOnError: true, RelativeBase: specPath, } err = ExpandSpec(testCase.Input, opts) assert.NoError(t, err) // b, _ := testCase.Input.MarshalJSON() // log.Printf(string(b)) assert.Equal(t, testCase.Input, testCase.Expected, "Should continue expanding spec when a definition can't be found.") doc, err := jsonDoc("fixtures/expansion/missingItemRef.json") spec := new(Swagger) err = json.Unmarshal(doc, spec) assert.NoError(t, err) assert.NotPanics(t, func() { err = ExpandSpec(spec, opts) assert.NoError(t, err) }, "Array of missing refs should not cause a panic, and continue to expand spec.") } func TestIssue415(t *testing.T) { doc, err := jsonDoc("fixtures/expansion/clickmeter.json") assert.NoError(t, err) specPath, _ := absPath("fixtures/expansion/clickmeter.json") opts := &ExpandOptions{ RelativeBase: specPath, } spec := new(Swagger) err = json.Unmarshal(doc, spec) assert.NoError(t, err) assert.NotPanics(t, func() { err = ExpandSpec(spec, opts) assert.NoError(t, err) }, "Calling expand spec with response schemas that have circular refs, should not panic!") } func TestCircularSpecExpansion(t *testing.T) { doc, err := jsonDoc("fixtures/expansion/circularSpec.json") assert.NoError(t, err) specPath, _ := absPath("fixtures/expansion/circularSpec.json") opts := &ExpandOptions{ RelativeBase: specPath, } spec := new(Swagger) err = json.Unmarshal(doc, spec) assert.NoError(t, err) assert.NotPanics(t, func() { err = ExpandSpec(spec, opts) assert.NoError(t, err) }, "Calling expand spec with circular refs, should not panic!") } func TestItemsExpansion(t *testing.T) { carsDoc, err := jsonDoc("fixtures/expansion/schemas2.json") assert.NoError(t, err) basePath, _ := absPath("fixtures/expansion/schemas2.json") spec := new(Swagger) err = json.Unmarshal(carsDoc, spec) assert.NoError(t, err) resolver, err := defaultSchemaLoader(spec, nil, nil) assert.NoError(t, err) schema := spec.Definitions["car"] oldBrand := schema.Properties["brand"] assert.NotEmpty(t, oldBrand.Items.Schema.Ref.String()) assert.NotEqual(t, spec.Definitions["brand"], oldBrand) _, err = expandSchema(schema, []string{"#/definitions/car"}, resolver, basePath) assert.NoError(t, err) newBrand := schema.Properties["brand"] assert.Empty(t, newBrand.Items.Schema.Ref.String()) assert.Equal(t, spec.Definitions["brand"], *newBrand.Items.Schema) schema = spec.Definitions["truck"] assert.NotEmpty(t, schema.Items.Schema.Ref.String()) s, err := expandSchema(schema, []string{"#/definitions/truck"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.Items.Schema.Ref.String()) assert.Equal(t, spec.Definitions["car"], *schema.Items.Schema) sch := new(Schema) _, err = expandSchema(*sch, []string{""}, resolver, basePath) assert.NoError(t, err) schema = spec.Definitions["batch"] s, err = expandSchema(schema, []string{"#/definitions/batch"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.Items.Schema.Items.Schema.Ref.String()) assert.Equal(t, *schema.Items.Schema.Items.Schema, spec.Definitions["brand"]) schema = spec.Definitions["batch2"] s, err = expandSchema(schema, []string{"#/definitions/batch2"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.Items.Schemas[0].Items.Schema.Ref.String()) assert.Empty(t, schema.Items.Schemas[1].Items.Schema.Ref.String()) assert.Equal(t, *schema.Items.Schemas[0].Items.Schema, spec.Definitions["brand"]) assert.Equal(t, *schema.Items.Schemas[1].Items.Schema, spec.Definitions["tag"]) schema = spec.Definitions["allofBoth"] s, err = expandSchema(schema, []string{"#/definitions/allofBoth"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.AllOf[0].Items.Schema.Ref.String()) assert.Empty(t, schema.AllOf[1].Items.Schema.Ref.String()) assert.Equal(t, *schema.AllOf[0].Items.Schema, spec.Definitions["brand"]) assert.Equal(t, *schema.AllOf[1].Items.Schema, spec.Definitions["tag"]) schema = spec.Definitions["anyofBoth"] s, err = expandSchema(schema, []string{"#/definitions/anyofBoth"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.AnyOf[0].Items.Schema.Ref.String()) assert.Empty(t, schema.AnyOf[1].Items.Schema.Ref.String()) assert.Equal(t, *schema.AnyOf[0].Items.Schema, spec.Definitions["brand"]) assert.Equal(t, *schema.AnyOf[1].Items.Schema, spec.Definitions["tag"]) schema = spec.Definitions["oneofBoth"] s, err = expandSchema(schema, []string{"#/definitions/oneofBoth"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.OneOf[0].Items.Schema.Ref.String()) assert.Empty(t, schema.OneOf[1].Items.Schema.Ref.String()) assert.Equal(t, *schema.OneOf[0].Items.Schema, spec.Definitions["brand"]) assert.Equal(t, *schema.OneOf[1].Items.Schema, spec.Definitions["tag"]) schema = spec.Definitions["notSomething"] s, err = expandSchema(schema, []string{"#/definitions/notSomething"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.Not.Items.Schema.Ref.String()) assert.Equal(t, *schema.Not.Items.Schema, spec.Definitions["tag"]) schema = spec.Definitions["withAdditional"] s, err = expandSchema(schema, []string{"#/definitions/withAdditional"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.AdditionalProperties.Schema.Items.Schema.Ref.String()) assert.Equal(t, *schema.AdditionalProperties.Schema.Items.Schema, spec.Definitions["tag"]) schema = spec.Definitions["withAdditionalItems"] s, err = expandSchema(schema, []string{"#/definitions/withAdditionalItems"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.AdditionalItems.Schema.Items.Schema.Ref.String()) assert.Equal(t, *schema.AdditionalItems.Schema.Items.Schema, spec.Definitions["tag"]) schema = spec.Definitions["withPattern"] s, err = expandSchema(schema, []string{"#/definitions/withPattern"}, resolver, basePath) schema = *s assert.NoError(t, err) prop := schema.PatternProperties["^x-ab"] assert.Empty(t, prop.Items.Schema.Ref.String()) assert.Equal(t, *prop.Items.Schema, spec.Definitions["tag"]) schema = spec.Definitions["deps"] s, err = expandSchema(schema, []string{"#/definitions/deps"}, resolver, basePath) schema = *s assert.NoError(t, err) prop2 := schema.Dependencies["something"] assert.Empty(t, prop2.Schema.Items.Schema.Ref.String()) assert.Equal(t, *prop2.Schema.Items.Schema, spec.Definitions["tag"]) schema = spec.Definitions["defined"] s, err = expandSchema(schema, []string{"#/definitions/defined"}, resolver, basePath) schema = *s assert.NoError(t, err) prop = schema.Definitions["something"] assert.Empty(t, prop.Items.Schema.Ref.String()) assert.Equal(t, *prop.Items.Schema, spec.Definitions["tag"]) } func TestSchemaExpansion(t *testing.T) { carsDoc, err := jsonDoc("fixtures/expansion/schemas1.json") assert.NoError(t, err) basePath, _ := absPath("fixtures/expansion/schemas1.json") spec := new(Swagger) err = json.Unmarshal(carsDoc, spec) assert.NoError(t, err) resolver, err := defaultSchemaLoader(spec, nil, nil) assert.NoError(t, err) schema := spec.Definitions["car"] oldBrand := schema.Properties["brand"] assert.NotEmpty(t, oldBrand.Ref.String()) assert.NotEqual(t, spec.Definitions["brand"], oldBrand) s, err := expandSchema(schema, []string{"#/definitions/car"}, resolver, basePath) schema = *s assert.NoError(t, err) newBrand := schema.Properties["brand"] assert.Empty(t, newBrand.Ref.String()) assert.Equal(t, spec.Definitions["brand"], newBrand) schema = spec.Definitions["truck"] assert.NotEmpty(t, schema.Ref.String()) s, err = expandSchema(schema, []string{"#/definitions/truck"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.Ref.String()) assert.Equal(t, spec.Definitions["car"], schema) sch := new(Schema) _, err = expandSchema(*sch, []string{""}, resolver, basePath) assert.NoError(t, err) schema = spec.Definitions["batch"] s, err = expandSchema(schema, []string{"#/definitions/batch"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.Items.Schema.Ref.String()) assert.Equal(t, *schema.Items.Schema, spec.Definitions["brand"]) schema = spec.Definitions["batch2"] s, err = expandSchema(schema, []string{"#/definitions/batch2"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.Items.Schemas[0].Ref.String()) assert.Empty(t, schema.Items.Schemas[1].Ref.String()) assert.Equal(t, schema.Items.Schemas[0], spec.Definitions["brand"]) assert.Equal(t, schema.Items.Schemas[1], spec.Definitions["tag"]) schema = spec.Definitions["allofBoth"] s, err = expandSchema(schema, []string{"#/definitions/allofBoth"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.AllOf[0].Ref.String()) assert.Empty(t, schema.AllOf[1].Ref.String()) assert.Equal(t, schema.AllOf[0], spec.Definitions["brand"]) assert.Equal(t, schema.AllOf[1], spec.Definitions["tag"]) schema = spec.Definitions["anyofBoth"] s, err = expandSchema(schema, []string{"#/definitions/anyofBoth"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.AnyOf[0].Ref.String()) assert.Empty(t, schema.AnyOf[1].Ref.String()) assert.Equal(t, schema.AnyOf[0], spec.Definitions["brand"]) assert.Equal(t, schema.AnyOf[1], spec.Definitions["tag"]) schema = spec.Definitions["oneofBoth"] s, err = expandSchema(schema, []string{"#/definitions/oneofBoth"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.OneOf[0].Ref.String()) assert.Empty(t, schema.OneOf[1].Ref.String()) assert.Equal(t, schema.OneOf[0], spec.Definitions["brand"]) assert.Equal(t, schema.OneOf[1], spec.Definitions["tag"]) schema = spec.Definitions["notSomething"] s, err = expandSchema(schema, []string{"#/definitions/notSomething"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.Not.Ref.String()) assert.Equal(t, *schema.Not, spec.Definitions["tag"]) schema = spec.Definitions["withAdditional"] s, err = expandSchema(schema, []string{"#/definitions/withAdditional"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.AdditionalProperties.Schema.Ref.String()) assert.Equal(t, *schema.AdditionalProperties.Schema, spec.Definitions["tag"]) schema = spec.Definitions["withAdditionalItems"] s, err = expandSchema(schema, []string{"#/definitions/withAdditionalItems"}, resolver, basePath) schema = *s assert.NoError(t, err) assert.Empty(t, schema.AdditionalItems.Schema.Ref.String()) assert.Equal(t, *schema.AdditionalItems.Schema, spec.Definitions["tag"]) schema = spec.Definitions["withPattern"] s, err = expandSchema(schema, []string{"#/definitions/withPattern"}, resolver, basePath) schema = *s assert.NoError(t, err) prop := schema.PatternProperties["^x-ab"] assert.Empty(t, prop.Ref.String()) assert.Equal(t, prop, spec.Definitions["tag"]) schema = spec.Definitions["deps"] s, err = expandSchema(schema, []string{"#/definitions/deps"}, resolver, basePath) schema = *s assert.NoError(t, err) prop2 := schema.Dependencies["something"] assert.Empty(t, prop2.Schema.Ref.String()) assert.Equal(t, *prop2.Schema, spec.Definitions["tag"]) schema = spec.Definitions["defined"] s, err = expandSchema(schema, []string{"#/definitions/defined"}, resolver, basePath) schema = *s assert.NoError(t, err) prop = schema.Definitions["something"] assert.Empty(t, prop.Ref.String()) assert.Equal(t, prop, spec.Definitions["tag"]) } func TestDefaultResolutionCache(t *testing.T) { cache := initResolutionCache() sch, ok := cache.Get("not there") assert.False(t, ok) assert.Nil(t, sch) sch, ok = cache.Get("http://swagger.io/v2/schema.json") assert.True(t, ok) assert.Equal(t, swaggerSchema, sch) sch, ok = cache.Get("http://json-schema.org/draft-04/schema") assert.True(t, ok) assert.Equal(t, jsonSchema, sch) cache.Set("something", "here") sch, ok = cache.Get("something") assert.True(t, ok) assert.Equal(t, "here", sch) } func TestRelativeBaseURI(t *testing.T) { server := httptest.NewServer(http.FileServer(http.Dir("fixtures/remote"))) defer server.Close() spec := new(Swagger) // resolver, err := defaultSchemaLoader(spec, nil, nil) // assert.NoError(t, err) err := ExpandSpec(spec, nil) assert.NoError(t, err) specDoc, err := jsonDoc("fixtures/remote/all-the-things.json") assert.NoError(t, err) opts := &ExpandOptions{ RelativeBase: server.URL + "/all-the-things.json", } spec = new(Swagger) err = json.Unmarshal(specDoc, spec) assert.NoError(t, err) pet := spec.Definitions["pet"] errorModel := spec.Definitions["errorModel"] petResponse := spec.Responses["petResponse"] petResponse.Schema = &pet stringResponse := spec.Responses["stringResponse"] tagParam := spec.Parameters["tag"] idParam := spec.Parameters["idParam"] anotherPet := spec.Responses["anotherPet"] anotherPet.Ref = MustCreateRef(server.URL + "/" + anotherPet.Ref.String()) err = ExpandResponse(&anotherPet, opts.RelativeBase) assert.NoError(t, err) spec.Responses["anotherPet"] = anotherPet circularA := spec.Responses["circularA"] circularA.Ref = MustCreateRef(server.URL + "/" + circularA.Ref.String()) err = ExpandResponse(&circularA, opts.RelativeBase) assert.NoError(t, err) spec.Responses["circularA"] = circularA err = ExpandSpec(spec, opts) assert.NoError(t, err) assert.Equal(t, tagParam, spec.Parameters["query"]) assert.Equal(t, petResponse, spec.Responses["petResponse"]) assert.Equal(t, petResponse, spec.Responses["anotherPet"]) assert.Equal(t, pet, *spec.Responses["petResponse"].Schema) assert.Equal(t, stringResponse, *spec.Paths.Paths["/"].Get.Responses.Default) assert.Equal(t, petResponse, spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200]) assert.Equal(t, pet, *spec.Paths.Paths["/pets"].Get.Responses.StatusCodeResponses[200].Schema.Items.Schema) assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Get.Responses.Default.Schema) assert.Equal(t, pet, spec.Definitions["petInput"].AllOf[0]) assert.Equal(t, spec.Definitions["petInput"], *spec.Paths.Paths["/pets"].Post.Parameters[0].Schema) assert.Equal(t, petResponse, spec.Paths.Paths["/pets"].Post.Responses.StatusCodeResponses[200]) assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Post.Responses.Default.Schema) pi := spec.Paths.Paths["/pets/{id}"] assert.Equal(t, idParam, pi.Get.Parameters[0]) assert.Equal(t, petResponse, pi.Get.Responses.StatusCodeResponses[200]) assert.Equal(t, errorModel, *pi.Get.Responses.Default.Schema) assert.Equal(t, idParam, pi.Delete.Parameters[0]) assert.Equal(t, errorModel, *pi.Delete.Responses.Default.Schema) } func resolutionContextServer() *httptest.Server { var servedAt string server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { // fmt.Println("got a request for", req.URL.String()) if req.URL.Path == "/resolution.json" { b, _ := ioutil.ReadFile("fixtures/specs/resolution.json") var ctnt map[string]interface{} json.Unmarshal(b, &ctnt) ctnt["id"] = servedAt rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(200) bb, _ := json.Marshal(ctnt) rw.Write(bb) return } if req.URL.Path == "/resolution2.json" { b, _ := ioutil.ReadFile("fixtures/specs/resolution2.json") var ctnt map[string]interface{} json.Unmarshal(b, &ctnt) ctnt["id"] = servedAt rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(200) bb, _ := json.Marshal(ctnt) rw.Write(bb) return } if req.URL.Path == "/boolProp.json" { rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(200) b, _ := json.Marshal(map[string]interface{}{ "type": "boolean", }) _, _ = rw.Write(b) return } if req.URL.Path == "/deeper/stringProp.json" { rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(200) b, _ := json.Marshal(map[string]interface{}{ "type": "string", }) rw.Write(b) return } if req.URL.Path == "/deeper/arrayProp.json" { rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(200) b, _ := json.Marshal(map[string]interface{}{ "type": "array", "items": map[string]interface{}{ "type": "file", }, }) rw.Write(b) return } rw.WriteHeader(http.StatusNotFound) })) servedAt = server.URL return server } func TestResolveRemoteRef_RootSame(t *testing.T) { specs := "fixtures/specs/" fileserver := http.FileServer(http.Dir(specs)) server := httptest.NewServer(fileserver) defer server.Close() rootDoc := new(Swagger) b, err := ioutil.ReadFile("fixtures/specs/refed.json") // the filename doesn't matter because ref will eventually point to refed.json specBase, _ := absPath("fixtures/specs/anyotherfile.json") if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { var result_0 Swagger ref_0, _ := NewRef(server.URL + "/refed.json#") resolver_0, _ := defaultSchemaLoader(rootDoc, nil, nil) if assert.NoError(t, resolver_0.Resolve(&ref_0, &result_0, "")) { assertSpecs(t, result_0, *rootDoc) } var result_1 Swagger ref_1, _ := NewRef("./refed.json") resolver_1, _ := defaultSchemaLoader(rootDoc, &ExpandOptions{ RelativeBase: specBase, }, nil) if assert.NoError(t, resolver_1.Resolve(&ref_1, &result_1, specBase)) { assertSpecs(t, result_1, *rootDoc) } } } func TestResolveRemoteRef_FromFragment(t *testing.T) { specs := "fixtures/specs" fileserver := http.FileServer(http.Dir(specs)) server := httptest.NewServer(fileserver) defer server.Close() rootDoc := new(Swagger) b, err := ioutil.ReadFile("fixtures/specs/refed.json") if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { var tgt Schema ref, err := NewRef(server.URL + "/refed.json#/definitions/pet") if assert.NoError(t, err) { resolver := &schemaLoader{root: rootDoc, cache: initResolutionCache(), loadDoc: jsonDoc} if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { assert.Equal(t, []string{"id", "name"}, tgt.Required) } } } } func TestResolveRemoteRef_FromInvalidFragment(t *testing.T) { specs := "fixtures/specs" fileserver := http.FileServer(http.Dir(specs)) server := httptest.NewServer(fileserver) defer server.Close() rootDoc := new(Swagger) b, err := ioutil.ReadFile("fixtures/specs/refed.json") if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { var tgt Schema ref, err := NewRef(server.URL + "/refed.json#/definitions/NotThere") if assert.NoError(t, err) { resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) assert.Error(t, resolver.Resolve(&ref, &tgt, "")) } } } func TestResolveRemoteRef_WithResolutionContext(t *testing.T) { server := resolutionContextServer() defer server.Close() var tgt Schema ref, err := NewRef(server.URL + "/resolution.json#/definitions/bool") if assert.NoError(t, err) { tgt.Ref = ref ExpandSchema(&tgt, nil, nil) assert.Equal(t, StringOrArray([]string{"boolean"}), tgt.Type) } } func TestResolveRemoteRef_WithNestedResolutionContext(t *testing.T) { server := resolutionContextServer() defer server.Close() var tgt Schema ref, err := NewRef(server.URL + "/resolution.json#/items") if assert.NoError(t, err) { tgt.Ref = ref ExpandSchema(&tgt, nil, nil) assert.Equal(t, StringOrArray([]string{"string"}), tgt.Items.Schema.Type) } } /* This next test will have to wait until we do full $ID analysis for every subschema on every file that is referenced */ /* For now, TestResolveRemoteRef_WithNestedResolutionContext replaces this next test */ // func TestResolveRemoteRef_WithNestedResolutionContext_WithParentID(t *testing.T) { // server := resolutionContextServer() // defer server.Close() // var tgt Schema // ref, err := NewRef(server.URL + "/resolution.json#/items/items") // if assert.NoError(t, err) { // tgt.Ref = ref // ExpandSchema(&tgt, nil, nil) // assert.Equal(t, StringOrArray([]string{"string"}), tgt.Type) // } // } func TestResolveRemoteRef_WithNestedResolutionContextWithFragment(t *testing.T) { server := resolutionContextServer() defer server.Close() var tgt Schema ref, err := NewRef(server.URL + "/resolution2.json#/items") if assert.NoError(t, err) { tgt.Ref = ref ExpandSchema(&tgt, nil, nil) assert.Equal(t, StringOrArray([]string{"file"}), tgt.Items.Schema.Type) } } /* This next test will have to wait until we do full $ID analysis for every subschema on every file that is referenced */ /* For now, TestResolveRemoteRef_WithNestedResolutionContext replaces this next test */ // func TestResolveRemoteRef_WithNestedResolutionContextWithFragment_WithParentID(t *testing.T) { // server := resolutionContextServer() // defer server.Close() // rootDoc := new(Swagger) // b, err := ioutil.ReadFile("fixtures/specs/refed.json") // if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { // var tgt Schema // ref, err := NewRef(server.URL + "/resolution2.json#/items/items") // if assert.NoError(t, err) { // resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) // if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { // assert.Equal(t, StringOrArray([]string{"file"}), tgt.Type) // } // } // } // } func TestResolveRemoteRef_ToParameter(t *testing.T) { specs := "fixtures/specs" fileserver := http.FileServer(http.Dir(specs)) server := httptest.NewServer(fileserver) defer server.Close() rootDoc := new(Swagger) b, err := ioutil.ReadFile("fixtures/specs/refed.json") if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { var tgt Parameter ref, err := NewRef(server.URL + "/refed.json#/parameters/idParam") if assert.NoError(t, err) { resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { assert.Equal(t, "id", tgt.Name) assert.Equal(t, "path", tgt.In) assert.Equal(t, "ID of pet to fetch", tgt.Description) assert.True(t, tgt.Required) assert.Equal(t, "integer", tgt.Type) assert.Equal(t, "int64", tgt.Format) } } } } func TestResolveRemoteRef_ToPathItem(t *testing.T) { specs := "fixtures/specs" fileserver := http.FileServer(http.Dir(specs)) server := httptest.NewServer(fileserver) defer server.Close() rootDoc := new(Swagger) b, err := ioutil.ReadFile("fixtures/specs/refed.json") if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { var tgt PathItem ref, err := NewRef(server.URL + "/refed.json#/paths/" + jsonpointer.Escape("/pets/{id}")) if assert.NoError(t, err) { resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { assert.Equal(t, rootDoc.Paths.Paths["/pets/{id}"].Get, tgt.Get) } } } } func TestResolveRemoteRef_ToResponse(t *testing.T) { specs := "fixtures/specs" fileserver := http.FileServer(http.Dir(specs)) server := httptest.NewServer(fileserver) defer server.Close() rootDoc := new(Swagger) b, err := ioutil.ReadFile("fixtures/specs/refed.json") if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { var tgt Response ref, err := NewRef(server.URL + "/refed.json#/responses/petResponse") if assert.NoError(t, err) { resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { assert.Equal(t, rootDoc.Responses["petResponse"], tgt) } } } } func TestResolveLocalRef_SameRoot(t *testing.T) { rootDoc := new(Swagger) json.Unmarshal(PetStoreJSONMessage, rootDoc) result := new(Swagger) ref, _ := NewRef("#") resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) err := resolver.Resolve(&ref, result, "") if assert.NoError(t, err) { assert.Equal(t, rootDoc, result) } } func TestResolveLocalRef_FromFragment(t *testing.T) { rootDoc := new(Swagger) json.Unmarshal(PetStoreJSONMessage, rootDoc) var tgt Schema ref, err := NewRef("#/definitions/Category") if assert.NoError(t, err) { resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) err := resolver.Resolve(&ref, &tgt, "") if assert.NoError(t, err) { assert.Equal(t, "Category", tgt.ID) } } } func TestResolveLocalRef_FromInvalidFragment(t *testing.T) { rootDoc := new(Swagger) json.Unmarshal(PetStoreJSONMessage, rootDoc) var tgt Schema ref, err := NewRef("#/definitions/NotThere") if assert.NoError(t, err) { resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) err := resolver.Resolve(&ref, &tgt, "") assert.Error(t, err) } } func TestResolveLocalRef_Parameter(t *testing.T) { rootDoc := new(Swagger) b, err := ioutil.ReadFile("fixtures/specs/refed.json") basePath, _ := absPath("fixtures/specs/refed.json") if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { var tgt Parameter ref, err := NewRef("#/parameters/idParam") if assert.NoError(t, err) { resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) if assert.NoError(t, resolver.Resolve(&ref, &tgt, basePath)) { assert.Equal(t, "id", tgt.Name) assert.Equal(t, "path", tgt.In) assert.Equal(t, "ID of pet to fetch", tgt.Description) assert.True(t, tgt.Required) assert.Equal(t, "integer", tgt.Type) assert.Equal(t, "int64", tgt.Format) } } } } func TestResolveLocalRef_PathItem(t *testing.T) { rootDoc := new(Swagger) b, err := ioutil.ReadFile("fixtures/specs/refed.json") basePath, _ := absPath("fixtures/specs/refed.json") if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { var tgt PathItem ref, err := NewRef("#/paths/" + jsonpointer.Escape("/pets/{id}")) if assert.NoError(t, err) { resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) if assert.NoError(t, resolver.Resolve(&ref, &tgt, basePath)) { assert.Equal(t, rootDoc.Paths.Paths["/pets/{id}"].Get, tgt.Get) } } } } func TestResolveLocalRef_Response(t *testing.T) { rootDoc := new(Swagger) b, err := ioutil.ReadFile("fixtures/specs/refed.json") basePath, _ := absPath("fixtures/specs/refed.json") if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { var tgt Response ref, err := NewRef("#/responses/petResponse") if assert.NoError(t, err) { resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) if assert.NoError(t, resolver.Resolve(&ref, &tgt, basePath)) { assert.Equal(t, rootDoc.Responses["petResponse"], tgt) } } } } func TestResolveForTransitiveRefs(t *testing.T) { var spec *Swagger rawSpec, err := ioutil.ReadFile("fixtures/specs/todos.json") assert.NoError(t, err) basePath, err := absPath("fixtures/specs/todos.json") assert.NoError(t, err) opts := &ExpandOptions{ RelativeBase: basePath, } err = json.Unmarshal(rawSpec, &spec) assert.NoError(t, err) err = ExpandSpec(spec, opts) assert.NoError(t, err) } // PetStoreJSONMessage json raw message for Petstore20 var PetStoreJSONMessage = json.RawMessage([]byte(PetStore20)) // PetStore20 json doc for swagger 2.0 pet store const PetStore20 = `{ "swagger": "2.0", "info": { "version": "1.0.0", "title": "Swagger Petstore", "contact": { "name": "Wordnik API Team", "url": "http://developer.wordnik.com" }, "license": { "name": "Creative Commons 4.0 International", "url": "http://creativecommons.org/licenses/by/4.0/" } }, "host": "petstore.swagger.wordnik.com", "basePath": "/api", "schemes": [ "http" ], "paths": { "/pets": { "get": { "security": [ { "basic": [] } ], "tags": [ "Pet Operations" ], "operationId": "getAllPets", "parameters": [ { "name": "status", "in": "query", "description": "The status to filter by", "type": "string" }, { "name": "limit", "in": "query", "description": "The maximum number of results to return", "type": "integer", "format": "int64" } ], "summary": "Finds all pets in the system", "responses": { "200": { "description": "Pet response", "schema": { "type": "array", "items": { "$ref": "#/definitions/Pet" } } }, "default": { "description": "Unexpected error", "schema": { "$ref": "#/definitions/Error" } } } }, "post": { "security": [ { "basic": [] } ], "tags": [ "Pet Operations" ], "operationId": "createPet", "summary": "Creates a new pet", "consumes": ["application/x-yaml"], "produces": ["application/x-yaml"], "parameters": [ { "name": "pet", "in": "body", "description": "The Pet to create", "required": true, "schema": { "$ref": "#/definitions/newPet" } } ], "responses": { "200": { "description": "Created Pet response", "schema": { "$ref": "#/definitions/Pet" } }, "default": { "description": "Unexpected error", "schema": { "$ref": "#/definitions/Error" } } } } }, "/pets/{id}": { "delete": { "security": [ { "apiKey": [] } ], "description": "Deletes the Pet by id", "operationId": "deletePet", "parameters": [ { "name": "id", "in": "path", "description": "ID of pet to delete", "required": true, "type": "integer", "format": "int64" } ], "responses": { "204": { "description": "pet deleted" }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/Error" } } } }, "get": { "tags": [ "Pet Operations" ], "operationId": "getPetById", "summary": "Finds the pet by id", "responses": { "200": { "description": "Pet response", "schema": { "$ref": "#/definitions/Pet" } }, "default": { "description": "Unexpected error", "schema": { "$ref": "#/definitions/Error" } } } }, "parameters": [ { "name": "id", "in": "path", "description": "ID of pet", "required": true, "type": "integer", "format": "int64" } ] } }, "definitions": { "Category": { "id": "Category", "properties": { "id": { "format": "int64", "type": "integer" }, "name": { "type": "string" } } }, "Pet": { "id": "Pet", "properties": { "category": { "$ref": "#/definitions/Category" }, "id": { "description": "unique identifier for the pet", "format": "int64", "maximum": 100.0, "minimum": 0.0, "type": "integer" }, "name": { "type": "string" }, "photoUrls": { "items": { "type": "string" }, "type": "array" }, "status": { "description": "pet status in the store", "enum": [ "available", "pending", "sold" ], "type": "string" }, "tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "id", "name" ] }, "newPet": { "anyOf": [ { "$ref": "#/definitions/Pet" }, { "required": [ "name" ] } ] }, "Tag": { "id": "Tag", "properties": { "id": { "format": "int64", "type": "integer" }, "name": { "type": "string" } } }, "Error": { "required": [ "code", "message" ], "properties": { "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" } } } }, "consumes": [ "application/json", "application/xml" ], "produces": [ "application/json", "application/xml", "text/plain", "text/html" ], "securityDefinitions": { "basic": { "type": "basic" }, "apiKey": { "type": "apiKey", "in": "header", "name": "X-API-KEY" } } } `
apache-2.0
googleads/google-ads-dotnet
src/V9/Types/AccountLink.g.cs
56591
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/resources/account_link.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Holder for reflection information generated from google/ads/googleads/v9/resources/account_link.proto</summary> public static partial class AccountLinkReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v9/resources/account_link.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AccountLinkReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjRnb29nbGUvYWRzL2dvb2dsZWFkcy92OS9yZXNvdXJjZXMvYWNjb3VudF9s", "aW5rLnByb3RvEiFnb29nbGUuYWRzLmdvb2dsZWFkcy52OS5yZXNvdXJjZXMa", "N2dvb2dsZS9hZHMvZ29vZ2xlYWRzL3Y5L2VudW1zL2FjY291bnRfbGlua19z", "dGF0dXMucHJvdG8aN2dvb2dsZS9hZHMvZ29vZ2xlYWRzL3Y5L2VudW1zL2xp", "bmtlZF9hY2NvdW50X3R5cGUucHJvdG8aNWdvb2dsZS9hZHMvZ29vZ2xlYWRz", "L3Y5L2VudW1zL21vYmlsZV9hcHBfdmVuZG9yLnByb3RvGh9nb29nbGUvYXBp", "L2ZpZWxkX2JlaGF2aW9yLnByb3RvGhlnb29nbGUvYXBpL3Jlc291cmNlLnBy", "b3RvGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvItYFCgtBY2NvdW50", "TGluaxJDCg1yZXNvdXJjZV9uYW1lGAEgASgJQizgQQX6QSYKJGdvb2dsZWFk", "cy5nb29nbGVhcGlzLmNvbS9BY2NvdW50TGluaxIhCg9hY2NvdW50X2xpbmtf", "aWQYCCABKANCA+BBA0gBiAEBElYKBnN0YXR1cxgDIAEoDjJGLmdvb2dsZS5h", "ZHMuZ29vZ2xlYWRzLnY5LmVudW1zLkFjY291bnRMaW5rU3RhdHVzRW51bS5B", "Y2NvdW50TGlua1N0YXR1cxJZCgR0eXBlGAQgASgOMkYuZ29vZ2xlLmFkcy5n", "b29nbGVhZHMudjkuZW51bXMuTGlua2VkQWNjb3VudFR5cGVFbnVtLkxpbmtl", "ZEFjY291bnRUeXBlQgPgQQMScQoZdGhpcmRfcGFydHlfYXBwX2FuYWx5dGlj", "cxgFIAEoCzJHLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY5LnJlc291cmNlcy5U", "aGlyZFBhcnR5QXBwQW5hbHl0aWNzTGlua0lkZW50aWZpZXJCA+BBBUgAElkK", "DGRhdGFfcGFydG5lchgGIAEoCzI8Lmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY5", "LnJlc291cmNlcy5EYXRhUGFydG5lckxpbmtJZGVudGlmaWVyQgPgQQNIABJV", "Cgpnb29nbGVfYWRzGAcgASgLMjouZ29vZ2xlLmFkcy5nb29nbGVhZHMudjku", "cmVzb3VyY2VzLkdvb2dsZUFkc0xpbmtJZGVudGlmaWVyQgPgQQNIADph6kFe", "CiRnb29nbGVhZHMuZ29vZ2xlYXBpcy5jb20vQWNjb3VudExpbmsSNmN1c3Rv", "bWVycy97Y3VzdG9tZXJfaWR9L2FjY291bnRMaW5rcy97YWNjb3VudF9saW5r", "X2lkfUIQCg5saW5rZWRfYWNjb3VudEISChBfYWNjb3VudF9saW5rX2lkIvMB", "CiRUaGlyZFBhcnR5QXBwQW5hbHl0aWNzTGlua0lkZW50aWZpZXISKwoZYXBw", "X2FuYWx5dGljc19wcm92aWRlcl9pZBgEIAEoA0ID4EEFSACIAQESGAoGYXBw", "X2lkGAUgASgJQgPgQQVIAYgBARJbCgphcHBfdmVuZG9yGAMgASgOMkIuZ29v", "Z2xlLmFkcy5nb29nbGVhZHMudjkuZW51bXMuTW9iaWxlQXBwVmVuZG9yRW51", "bS5Nb2JpbGVBcHBWZW5kb3JCA+BBBUIcChpfYXBwX2FuYWx5dGljc19wcm92", "aWRlcl9pZEIJCgdfYXBwX2lkIlIKGURhdGFQYXJ0bmVyTGlua0lkZW50aWZp", "ZXISIQoPZGF0YV9wYXJ0bmVyX2lkGAEgASgDQgPgQQVIAIgBAUISChBfZGF0", "YV9wYXJ0bmVyX2lkImgKF0dvb2dsZUFkc0xpbmtJZGVudGlmaWVyEkAKCGN1", "c3RvbWVyGAMgASgJQingQQX6QSMKIWdvb2dsZWFkcy5nb29nbGVhcGlzLmNv", "bS9DdXN0b21lckgAiAEBQgsKCV9jdXN0b21lckL9AQolY29tLmdvb2dsZS5h", "ZHMuZ29vZ2xlYWRzLnY5LnJlc291cmNlc0IQQWNjb3VudExpbmtQcm90b1AB", "Wkpnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9n", "b29nbGVhZHMvdjkvcmVzb3VyY2VzO3Jlc291cmNlc6ICA0dBQaoCIUdvb2ds", "ZS5BZHMuR29vZ2xlQWRzLlY5LlJlc291cmNlc8oCIUdvb2dsZVxBZHNcR29v", "Z2xlQWRzXFY5XFJlc291cmNlc+oCJUdvb2dsZTo6QWRzOjpHb29nbGVBZHM6", "OlY5OjpSZXNvdXJjZXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusReflection.Descriptor, global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeReflection.Descriptor, global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Resources.AccountLink), global::Google.Ads.GoogleAds.V9.Resources.AccountLink.Parser, new[]{ "ResourceName", "AccountLinkId", "Status", "Type", "ThirdPartyAppAnalytics", "DataPartner", "GoogleAds" }, new[]{ "LinkedAccount", "AccountLinkId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Resources.ThirdPartyAppAnalyticsLinkIdentifier), global::Google.Ads.GoogleAds.V9.Resources.ThirdPartyAppAnalyticsLinkIdentifier.Parser, new[]{ "AppAnalyticsProviderId", "AppId", "AppVendor" }, new[]{ "AppAnalyticsProviderId", "AppId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Resources.DataPartnerLinkIdentifier), global::Google.Ads.GoogleAds.V9.Resources.DataPartnerLinkIdentifier.Parser, new[]{ "DataPartnerId" }, new[]{ "DataPartnerId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Resources.GoogleAdsLinkIdentifier), global::Google.Ads.GoogleAds.V9.Resources.GoogleAdsLinkIdentifier.Parser, new[]{ "Customer" }, new[]{ "Customer" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Represents the data sharing connection between a Google Ads account and /// another account /// </summary> public sealed partial class AccountLink : pb::IMessage<AccountLink> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<AccountLink> _parser = new pb::MessageParser<AccountLink>(() => new AccountLink()); private pb::UnknownFieldSet _unknownFields; private int _hasBits0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<AccountLink> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V9.Resources.AccountLinkReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AccountLink() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AccountLink(AccountLink other) : this() { _hasBits0 = other._hasBits0; resourceName_ = other.resourceName_; accountLinkId_ = other.accountLinkId_; status_ = other.status_; type_ = other.type_; switch (other.LinkedAccountCase) { case LinkedAccountOneofCase.ThirdPartyAppAnalytics: ThirdPartyAppAnalytics = other.ThirdPartyAppAnalytics.Clone(); break; case LinkedAccountOneofCase.DataPartner: DataPartner = other.DataPartner.Clone(); break; case LinkedAccountOneofCase.GoogleAds: GoogleAds = other.GoogleAds.Clone(); break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AccountLink Clone() { return new AccountLink(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// Immutable. Resource name of the account link. /// AccountLink resource names have the form: /// `customers/{customer_id}/accountLinks/{account_link_id}` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "account_link_id" field.</summary> public const int AccountLinkIdFieldNumber = 8; private long accountLinkId_; /// <summary> /// Output only. The ID of the link. /// This field is read only. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public long AccountLinkId { get { if ((_hasBits0 & 1) != 0) { return accountLinkId_; } else { return 0L; } } set { _hasBits0 |= 1; accountLinkId_ = value; } } /// <summary>Gets whether the "account_link_id" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasAccountLinkId { get { return (_hasBits0 & 1) != 0; } } /// <summary>Clears the value of the "account_link_id" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearAccountLinkId() { _hasBits0 &= ~1; } /// <summary>Field number for the "status" field.</summary> public const int StatusFieldNumber = 3; private global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus status_ = global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus.Unspecified; /// <summary> /// The status of the link. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus Status { get { return status_; } set { status_ = value; } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 4; private global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType type_ = global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified; /// <summary> /// Output only. The type of the linked account. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType Type { get { return type_; } set { type_ = value; } } /// <summary>Field number for the "third_party_app_analytics" field.</summary> public const int ThirdPartyAppAnalyticsFieldNumber = 5; /// <summary> /// Immutable. A third party app analytics link. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Resources.ThirdPartyAppAnalyticsLinkIdentifier ThirdPartyAppAnalytics { get { return linkedAccountCase_ == LinkedAccountOneofCase.ThirdPartyAppAnalytics ? (global::Google.Ads.GoogleAds.V9.Resources.ThirdPartyAppAnalyticsLinkIdentifier) linkedAccount_ : null; } set { linkedAccount_ = value; linkedAccountCase_ = value == null ? LinkedAccountOneofCase.None : LinkedAccountOneofCase.ThirdPartyAppAnalytics; } } /// <summary>Field number for the "data_partner" field.</summary> public const int DataPartnerFieldNumber = 6; /// <summary> /// Output only. Data partner link. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Resources.DataPartnerLinkIdentifier DataPartner { get { return linkedAccountCase_ == LinkedAccountOneofCase.DataPartner ? (global::Google.Ads.GoogleAds.V9.Resources.DataPartnerLinkIdentifier) linkedAccount_ : null; } set { linkedAccount_ = value; linkedAccountCase_ = value == null ? LinkedAccountOneofCase.None : LinkedAccountOneofCase.DataPartner; } } /// <summary>Field number for the "google_ads" field.</summary> public const int GoogleAdsFieldNumber = 7; /// <summary> /// Output only. Google Ads link. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Resources.GoogleAdsLinkIdentifier GoogleAds { get { return linkedAccountCase_ == LinkedAccountOneofCase.GoogleAds ? (global::Google.Ads.GoogleAds.V9.Resources.GoogleAdsLinkIdentifier) linkedAccount_ : null; } set { linkedAccount_ = value; linkedAccountCase_ = value == null ? LinkedAccountOneofCase.None : LinkedAccountOneofCase.GoogleAds; } } private object linkedAccount_; /// <summary>Enum of possible cases for the "linked_account" oneof.</summary> public enum LinkedAccountOneofCase { None = 0, ThirdPartyAppAnalytics = 5, DataPartner = 6, GoogleAds = 7, } private LinkedAccountOneofCase linkedAccountCase_ = LinkedAccountOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LinkedAccountOneofCase LinkedAccountCase { get { return linkedAccountCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearLinkedAccount() { linkedAccountCase_ = LinkedAccountOneofCase.None; linkedAccount_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as AccountLink); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(AccountLink other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; if (AccountLinkId != other.AccountLinkId) return false; if (Status != other.Status) return false; if (Type != other.Type) return false; if (!object.Equals(ThirdPartyAppAnalytics, other.ThirdPartyAppAnalytics)) return false; if (!object.Equals(DataPartner, other.DataPartner)) return false; if (!object.Equals(GoogleAds, other.GoogleAds)) return false; if (LinkedAccountCase != other.LinkedAccountCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (HasAccountLinkId) hash ^= AccountLinkId.GetHashCode(); if (Status != global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus.Unspecified) hash ^= Status.GetHashCode(); if (Type != global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified) hash ^= Type.GetHashCode(); if (linkedAccountCase_ == LinkedAccountOneofCase.ThirdPartyAppAnalytics) hash ^= ThirdPartyAppAnalytics.GetHashCode(); if (linkedAccountCase_ == LinkedAccountOneofCase.DataPartner) hash ^= DataPartner.GetHashCode(); if (linkedAccountCase_ == LinkedAccountOneofCase.GoogleAds) hash ^= GoogleAds.GetHashCode(); hash ^= (int) linkedAccountCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (Status != global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) Status); } if (Type != global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) Type); } if (linkedAccountCase_ == LinkedAccountOneofCase.ThirdPartyAppAnalytics) { output.WriteRawTag(42); output.WriteMessage(ThirdPartyAppAnalytics); } if (linkedAccountCase_ == LinkedAccountOneofCase.DataPartner) { output.WriteRawTag(50); output.WriteMessage(DataPartner); } if (linkedAccountCase_ == LinkedAccountOneofCase.GoogleAds) { output.WriteRawTag(58); output.WriteMessage(GoogleAds); } if (HasAccountLinkId) { output.WriteRawTag(64); output.WriteInt64(AccountLinkId); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (Status != global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) Status); } if (Type != global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) Type); } if (linkedAccountCase_ == LinkedAccountOneofCase.ThirdPartyAppAnalytics) { output.WriteRawTag(42); output.WriteMessage(ThirdPartyAppAnalytics); } if (linkedAccountCase_ == LinkedAccountOneofCase.DataPartner) { output.WriteRawTag(50); output.WriteMessage(DataPartner); } if (linkedAccountCase_ == LinkedAccountOneofCase.GoogleAds) { output.WriteRawTag(58); output.WriteMessage(GoogleAds); } if (HasAccountLinkId) { output.WriteRawTag(64); output.WriteInt64(AccountLinkId); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (HasAccountLinkId) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(AccountLinkId); } if (Status != global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status); } if (Type != global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } if (linkedAccountCase_ == LinkedAccountOneofCase.ThirdPartyAppAnalytics) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ThirdPartyAppAnalytics); } if (linkedAccountCase_ == LinkedAccountOneofCase.DataPartner) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DataPartner); } if (linkedAccountCase_ == LinkedAccountOneofCase.GoogleAds) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(GoogleAds); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(AccountLink other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } if (other.HasAccountLinkId) { AccountLinkId = other.AccountLinkId; } if (other.Status != global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus.Unspecified) { Status = other.Status; } if (other.Type != global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType.Unspecified) { Type = other.Type; } switch (other.LinkedAccountCase) { case LinkedAccountOneofCase.ThirdPartyAppAnalytics: if (ThirdPartyAppAnalytics == null) { ThirdPartyAppAnalytics = new global::Google.Ads.GoogleAds.V9.Resources.ThirdPartyAppAnalyticsLinkIdentifier(); } ThirdPartyAppAnalytics.MergeFrom(other.ThirdPartyAppAnalytics); break; case LinkedAccountOneofCase.DataPartner: if (DataPartner == null) { DataPartner = new global::Google.Ads.GoogleAds.V9.Resources.DataPartnerLinkIdentifier(); } DataPartner.MergeFrom(other.DataPartner); break; case LinkedAccountOneofCase.GoogleAds: if (GoogleAds == null) { GoogleAds = new global::Google.Ads.GoogleAds.V9.Resources.GoogleAdsLinkIdentifier(); } GoogleAds.MergeFrom(other.GoogleAds); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } case 24: { Status = (global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus) input.ReadEnum(); break; } case 32: { Type = (global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType) input.ReadEnum(); break; } case 42: { global::Google.Ads.GoogleAds.V9.Resources.ThirdPartyAppAnalyticsLinkIdentifier subBuilder = new global::Google.Ads.GoogleAds.V9.Resources.ThirdPartyAppAnalyticsLinkIdentifier(); if (linkedAccountCase_ == LinkedAccountOneofCase.ThirdPartyAppAnalytics) { subBuilder.MergeFrom(ThirdPartyAppAnalytics); } input.ReadMessage(subBuilder); ThirdPartyAppAnalytics = subBuilder; break; } case 50: { global::Google.Ads.GoogleAds.V9.Resources.DataPartnerLinkIdentifier subBuilder = new global::Google.Ads.GoogleAds.V9.Resources.DataPartnerLinkIdentifier(); if (linkedAccountCase_ == LinkedAccountOneofCase.DataPartner) { subBuilder.MergeFrom(DataPartner); } input.ReadMessage(subBuilder); DataPartner = subBuilder; break; } case 58: { global::Google.Ads.GoogleAds.V9.Resources.GoogleAdsLinkIdentifier subBuilder = new global::Google.Ads.GoogleAds.V9.Resources.GoogleAdsLinkIdentifier(); if (linkedAccountCase_ == LinkedAccountOneofCase.GoogleAds) { subBuilder.MergeFrom(GoogleAds); } input.ReadMessage(subBuilder); GoogleAds = subBuilder; break; } case 64: { AccountLinkId = input.ReadInt64(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { ResourceName = input.ReadString(); break; } case 24: { Status = (global::Google.Ads.GoogleAds.V9.Enums.AccountLinkStatusEnum.Types.AccountLinkStatus) input.ReadEnum(); break; } case 32: { Type = (global::Google.Ads.GoogleAds.V9.Enums.LinkedAccountTypeEnum.Types.LinkedAccountType) input.ReadEnum(); break; } case 42: { global::Google.Ads.GoogleAds.V9.Resources.ThirdPartyAppAnalyticsLinkIdentifier subBuilder = new global::Google.Ads.GoogleAds.V9.Resources.ThirdPartyAppAnalyticsLinkIdentifier(); if (linkedAccountCase_ == LinkedAccountOneofCase.ThirdPartyAppAnalytics) { subBuilder.MergeFrom(ThirdPartyAppAnalytics); } input.ReadMessage(subBuilder); ThirdPartyAppAnalytics = subBuilder; break; } case 50: { global::Google.Ads.GoogleAds.V9.Resources.DataPartnerLinkIdentifier subBuilder = new global::Google.Ads.GoogleAds.V9.Resources.DataPartnerLinkIdentifier(); if (linkedAccountCase_ == LinkedAccountOneofCase.DataPartner) { subBuilder.MergeFrom(DataPartner); } input.ReadMessage(subBuilder); DataPartner = subBuilder; break; } case 58: { global::Google.Ads.GoogleAds.V9.Resources.GoogleAdsLinkIdentifier subBuilder = new global::Google.Ads.GoogleAds.V9.Resources.GoogleAdsLinkIdentifier(); if (linkedAccountCase_ == LinkedAccountOneofCase.GoogleAds) { subBuilder.MergeFrom(GoogleAds); } input.ReadMessage(subBuilder); GoogleAds = subBuilder; break; } case 64: { AccountLinkId = input.ReadInt64(); break; } } } } #endif } /// <summary> /// The identifiers of a Third Party App Analytics Link. /// </summary> public sealed partial class ThirdPartyAppAnalyticsLinkIdentifier : pb::IMessage<ThirdPartyAppAnalyticsLinkIdentifier> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<ThirdPartyAppAnalyticsLinkIdentifier> _parser = new pb::MessageParser<ThirdPartyAppAnalyticsLinkIdentifier>(() => new ThirdPartyAppAnalyticsLinkIdentifier()); private pb::UnknownFieldSet _unknownFields; private int _hasBits0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<ThirdPartyAppAnalyticsLinkIdentifier> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V9.Resources.AccountLinkReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ThirdPartyAppAnalyticsLinkIdentifier() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ThirdPartyAppAnalyticsLinkIdentifier(ThirdPartyAppAnalyticsLinkIdentifier other) : this() { _hasBits0 = other._hasBits0; appAnalyticsProviderId_ = other.appAnalyticsProviderId_; appId_ = other.appId_; appVendor_ = other.appVendor_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public ThirdPartyAppAnalyticsLinkIdentifier Clone() { return new ThirdPartyAppAnalyticsLinkIdentifier(this); } /// <summary>Field number for the "app_analytics_provider_id" field.</summary> public const int AppAnalyticsProviderIdFieldNumber = 4; private long appAnalyticsProviderId_; /// <summary> /// Immutable. The ID of the app analytics provider. /// This field should not be empty when creating a new third /// party app analytics link. It is unable to be modified after the creation of /// the link. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public long AppAnalyticsProviderId { get { if ((_hasBits0 & 1) != 0) { return appAnalyticsProviderId_; } else { return 0L; } } set { _hasBits0 |= 1; appAnalyticsProviderId_ = value; } } /// <summary>Gets whether the "app_analytics_provider_id" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasAppAnalyticsProviderId { get { return (_hasBits0 & 1) != 0; } } /// <summary>Clears the value of the "app_analytics_provider_id" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearAppAnalyticsProviderId() { _hasBits0 &= ~1; } /// <summary>Field number for the "app_id" field.</summary> public const int AppIdFieldNumber = 5; private string appId_; /// <summary> /// Immutable. A string that uniquely identifies a mobile application from which the data /// was collected to the Google Ads API. For iOS, the ID string is the 9 digit /// string that appears at the end of an App Store URL (e.g., "422689480" for /// "Gmail" whose App Store link is /// https://apps.apple.com/us/app/gmail-email-by-google/id422689480). For /// Android, the ID string is the application's package name (e.g., /// "com.google.android.gm" for "Gmail" given Google Play link /// https://play.google.com/store/apps/details?id=com.google.android.gm) /// This field should not be empty when creating a new third /// party app analytics link. It is unable to be modified after the creation of /// the link. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string AppId { get { return appId_ ?? ""; } set { appId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Gets whether the "app_id" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasAppId { get { return appId_ != null; } } /// <summary>Clears the value of the "app_id" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearAppId() { appId_ = null; } /// <summary>Field number for the "app_vendor" field.</summary> public const int AppVendorFieldNumber = 3; private global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor appVendor_ = global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor.Unspecified; /// <summary> /// Immutable. The vendor of the app. /// This field should not be empty when creating a new third /// party app analytics link. It is unable to be modified after the creation of /// the link. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor AppVendor { get { return appVendor_; } set { appVendor_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as ThirdPartyAppAnalyticsLinkIdentifier); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(ThirdPartyAppAnalyticsLinkIdentifier other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (AppAnalyticsProviderId != other.AppAnalyticsProviderId) return false; if (AppId != other.AppId) return false; if (AppVendor != other.AppVendor) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (HasAppAnalyticsProviderId) hash ^= AppAnalyticsProviderId.GetHashCode(); if (HasAppId) hash ^= AppId.GetHashCode(); if (AppVendor != global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor.Unspecified) hash ^= AppVendor.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (AppVendor != global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) AppVendor); } if (HasAppAnalyticsProviderId) { output.WriteRawTag(32); output.WriteInt64(AppAnalyticsProviderId); } if (HasAppId) { output.WriteRawTag(42); output.WriteString(AppId); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (AppVendor != global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) AppVendor); } if (HasAppAnalyticsProviderId) { output.WriteRawTag(32); output.WriteInt64(AppAnalyticsProviderId); } if (HasAppId) { output.WriteRawTag(42); output.WriteString(AppId); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (HasAppAnalyticsProviderId) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(AppAnalyticsProviderId); } if (HasAppId) { size += 1 + pb::CodedOutputStream.ComputeStringSize(AppId); } if (AppVendor != global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) AppVendor); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(ThirdPartyAppAnalyticsLinkIdentifier other) { if (other == null) { return; } if (other.HasAppAnalyticsProviderId) { AppAnalyticsProviderId = other.AppAnalyticsProviderId; } if (other.HasAppId) { AppId = other.AppId; } if (other.AppVendor != global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor.Unspecified) { AppVendor = other.AppVendor; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 24: { AppVendor = (global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor) input.ReadEnum(); break; } case 32: { AppAnalyticsProviderId = input.ReadInt64(); break; } case 42: { AppId = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 24: { AppVendor = (global::Google.Ads.GoogleAds.V9.Enums.MobileAppVendorEnum.Types.MobileAppVendor) input.ReadEnum(); break; } case 32: { AppAnalyticsProviderId = input.ReadInt64(); break; } case 42: { AppId = input.ReadString(); break; } } } } #endif } /// <summary> /// The identifier for Data Partner account. /// </summary> public sealed partial class DataPartnerLinkIdentifier : pb::IMessage<DataPartnerLinkIdentifier> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<DataPartnerLinkIdentifier> _parser = new pb::MessageParser<DataPartnerLinkIdentifier>(() => new DataPartnerLinkIdentifier()); private pb::UnknownFieldSet _unknownFields; private int _hasBits0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<DataPartnerLinkIdentifier> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V9.Resources.AccountLinkReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public DataPartnerLinkIdentifier() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public DataPartnerLinkIdentifier(DataPartnerLinkIdentifier other) : this() { _hasBits0 = other._hasBits0; dataPartnerId_ = other.dataPartnerId_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public DataPartnerLinkIdentifier Clone() { return new DataPartnerLinkIdentifier(this); } /// <summary>Field number for the "data_partner_id" field.</summary> public const int DataPartnerIdFieldNumber = 1; private long dataPartnerId_; /// <summary> /// Immutable. The customer ID of the Data partner account. /// This field is required and should not be empty when creating a new /// data partner link. It is unable to be modified after the creation of /// the link. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public long DataPartnerId { get { if ((_hasBits0 & 1) != 0) { return dataPartnerId_; } else { return 0L; } } set { _hasBits0 |= 1; dataPartnerId_ = value; } } /// <summary>Gets whether the "data_partner_id" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasDataPartnerId { get { return (_hasBits0 & 1) != 0; } } /// <summary>Clears the value of the "data_partner_id" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearDataPartnerId() { _hasBits0 &= ~1; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as DataPartnerLinkIdentifier); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(DataPartnerLinkIdentifier other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (DataPartnerId != other.DataPartnerId) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (HasDataPartnerId) hash ^= DataPartnerId.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (HasDataPartnerId) { output.WriteRawTag(8); output.WriteInt64(DataPartnerId); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (HasDataPartnerId) { output.WriteRawTag(8); output.WriteInt64(DataPartnerId); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (HasDataPartnerId) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(DataPartnerId); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(DataPartnerLinkIdentifier other) { if (other == null) { return; } if (other.HasDataPartnerId) { DataPartnerId = other.DataPartnerId; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { DataPartnerId = input.ReadInt64(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { DataPartnerId = input.ReadInt64(); break; } } } } #endif } /// <summary> /// The identifier for Google Ads account. /// </summary> public sealed partial class GoogleAdsLinkIdentifier : pb::IMessage<GoogleAdsLinkIdentifier> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GoogleAdsLinkIdentifier> _parser = new pb::MessageParser<GoogleAdsLinkIdentifier>(() => new GoogleAdsLinkIdentifier()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<GoogleAdsLinkIdentifier> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V9.Resources.AccountLinkReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GoogleAdsLinkIdentifier() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GoogleAdsLinkIdentifier(GoogleAdsLinkIdentifier other) : this() { customer_ = other.customer_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GoogleAdsLinkIdentifier Clone() { return new GoogleAdsLinkIdentifier(this); } /// <summary>Field number for the "customer" field.</summary> public const int CustomerFieldNumber = 3; private string customer_; /// <summary> /// Immutable. The resource name of the Google Ads account. /// This field is required and should not be empty when creating a new /// Google Ads link. It is unable to be modified after the creation of /// the link. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Customer { get { return customer_ ?? ""; } set { customer_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Gets whether the "customer" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasCustomer { get { return customer_ != null; } } /// <summary>Clears the value of the "customer" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearCustomer() { customer_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as GoogleAdsLinkIdentifier); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(GoogleAdsLinkIdentifier other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Customer != other.Customer) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (HasCustomer) hash ^= Customer.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (HasCustomer) { output.WriteRawTag(26); output.WriteString(Customer); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (HasCustomer) { output.WriteRawTag(26); output.WriteString(Customer); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (HasCustomer) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Customer); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(GoogleAdsLinkIdentifier other) { if (other == null) { return; } if (other.HasCustomer) { Customer = other.Customer; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 26: { Customer = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 26: { Customer = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
apache-2.0
googleads/googleads-java-lib
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201809/cm/ManualCpcBiddingScheme.java
6147
// Copyright 2018 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 // // 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. /** * ManualCpcBiddingScheme.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201809.cm; /** * Manual click based bidding where user pays per click. * <span class="constraint AdxEnabled">This is disabled for * AdX.</span> */ public class ManualCpcBiddingScheme extends com.google.api.ads.adwords.axis.v201809.cm.BiddingScheme implements java.io.Serializable { /* The enhanced CPC bidding option for the campaign, which enables * bids to be enhanced based on conversion optimizer data. For more * information about enhanced CPC, see the * <a href="//support.google.com/adwords/answer/2464964" * >AdWords Help Center</a>. */ private java.lang.Boolean enhancedCpcEnabled; public ManualCpcBiddingScheme() { } public ManualCpcBiddingScheme( java.lang.String biddingSchemeType, java.lang.Boolean enhancedCpcEnabled) { super( biddingSchemeType); this.enhancedCpcEnabled = enhancedCpcEnabled; } @Override public String toString() { return com.google.common.base.MoreObjects.toStringHelper(this.getClass()) .omitNullValues() .add("biddingSchemeType", getBiddingSchemeType()) .add("enhancedCpcEnabled", getEnhancedCpcEnabled()) .toString(); } /** * Gets the enhancedCpcEnabled value for this ManualCpcBiddingScheme. * * @return enhancedCpcEnabled * The enhanced CPC bidding option for the campaign, which enables * bids to be enhanced based on conversion optimizer data. For more * information about enhanced CPC, see the * <a href="//support.google.com/adwords/answer/2464964" * >AdWords Help Center</a>. */ public java.lang.Boolean getEnhancedCpcEnabled() { return enhancedCpcEnabled; } /** * Sets the enhancedCpcEnabled value for this ManualCpcBiddingScheme. * * @param enhancedCpcEnabled * The enhanced CPC bidding option for the campaign, which enables * bids to be enhanced based on conversion optimizer data. For more * information about enhanced CPC, see the * <a href="//support.google.com/adwords/answer/2464964" * >AdWords Help Center</a>. */ public void setEnhancedCpcEnabled(java.lang.Boolean enhancedCpcEnabled) { this.enhancedCpcEnabled = enhancedCpcEnabled; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof ManualCpcBiddingScheme)) return false; ManualCpcBiddingScheme other = (ManualCpcBiddingScheme) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.enhancedCpcEnabled==null && other.getEnhancedCpcEnabled()==null) || (this.enhancedCpcEnabled!=null && this.enhancedCpcEnabled.equals(other.getEnhancedCpcEnabled()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getEnhancedCpcEnabled() != null) { _hashCode += getEnhancedCpcEnabled().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ManualCpcBiddingScheme.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "ManualCpcBiddingScheme")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("enhancedCpcEnabled"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "enhancedCpcEnabled")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
mydataspace/mydataspace.github.io
js/entity-form.js
44916
/** * @class */ function EntityForm() { var self = this; self.editing = false; self.loadedListeners = []; window.addEventListener('message', function (e) { if ([ 'MDSWizard.upload', 'MDSWizard.getFields', 'MDSWizard.getData', 'MDSWizard.save' ].indexOf(e.data.message) == -1) { return; } var formData = Identity.dataFromId(self.getCurrentId()); var iframeWindow = (document.getElementById('entity_form_iframe') || {}).contentWindow; switch (e.data.message) { case 'MDSWizard.upload': $$('add_resource_window').showWithData({ callback: function (res, err) { if (err) { iframeWindow.postMessage({ message: 'MDSWizard.upload.err', error: err }, '*'); return; } iframeWindow.postMessage({ message: 'MDSWizard.upload.res', name: res.resources[0] }, '*'); } }); break; case 'MDSWizard.getData': break; case 'MDSWizard.getFields': Mydataspace.entities.get(formData).then(function (data) { iframeWindow.postMessage({ message: 'MDSWizard.getFields.res', fields: data.fields, path: data.path, root: data.root }, '*'); }).catch(function (err) { iframeWindow.postMessage({ message: 'MDSWizard.getFields.err', error: err }, '*'); }); break; case 'MDSWizard.save': if (!e.data.token || e.data.token !== self.saveToken) { throw new Error('Invalid save token'); } delete self.saveToken; var iframeLock = document.getElementById('entity_form_iframe_lock'); iframeLock.style.display = 'block'; Mydataspace.request('entities.change', { root: formData.root, path: formData.path, fields: e.data.fields }).then(function () { iframeLock.style.display = 'none'; }).catch(function (err) { iframeLock.style.display = 'none'; iframeWindow.postMessage({ message: 'MDSWizard.save.err', token: e.data.token, error: err }, '*'); }); break; } }); } EntityForm.prototype.onLoaded = function(listener) { this.loadedListeners.push(listener); }; EntityForm.prototype.emitLoaded = function(data) { this.loadedListeners.forEach(function(listener) { listener(data); }); }; /** * Switch Entity Form to edit/view mode. */ EntityForm.prototype.setEditing = function(editing) { if (this.currentId == null) { return; } this.editing = editing; delete self.saveToken; UI.entityForm.hideScriptEditWindow(); var entityType = UIHelper.getEntityTypeByPath(Identity.dataFromId(this.currentId).path); UIHelper.setVisible('entity_form__toolbar', editing); UIHelper.setVisible(['SAVE_ENTITY_LABEL', 'CANCEL_ENTITY_LABEL', 'ADD_FIELD_LABEL'], editing); if (editing) { webix.html.addCss($$('edit_script_window__toolbar').getNode(), 'entity_form__toolbar--edit'); webix.html.addCss($$('entity_form__toolbar').getNode(), 'entity_form__toolbar--edit'); $$('edit_script_window__editor').getEditor().setReadOnly(false); } else { webix.html.removeCss($$('edit_script_window__toolbar').getNode(), 'entity_form__toolbar--edit'); webix.html.removeCss($$('entity_form__toolbar').getNode(), 'entity_form__toolbar--edit'); $$('edit_script_window__editor').getEditor().setReadOnly(true); } }; EntityForm.prototype.isEditing = function() { return this.editing; }; EntityForm.prototype.listen = function() { var self = this; Mydataspace.on('entities.delete.res', function() { $$('entity_form').disable(); }); Mydataspace.on('entities.change.res', function(data) { if (self.isEditing()) { return; } if (Identity.idFromData(data) !== self.getCurrentId()) { return; } if (MDSCommon.isBlank(data.path)) { self.setViewTitle(MDSCommon.findValueByName(data.fields, 'name') || MDSCommon.getEntityName(data.root)); } }); }; EntityForm.prototype.isProto = function() { return UIHelper.isProto(this.currentId); }; EntityForm.prototype.getCurrentId = function () { return this.currentId; }; EntityForm.prototype.setCurrentId = function(id) { if (this.currentId === id) { return; } this.currentId = id; UI.entityForm.hideScriptEditWindow(); this.refresh(); }; EntityForm.prototype.setLogRecords = function(fields, ignoredFieldNames, addLabelIfNoFieldsExists) { if (!Array.isArray(ignoredFieldNames)) { ignoredFieldNames = []; } if (addLabelIfNoFieldsExists == null) { addLabelIfNoFieldsExists = true; } var viewFields = document.getElementById('view__fields'); if (MDSCommon.isBlank(fields.filter(function (field) { return field.name.indexOf('$') != 0; }))) { viewFields.innerHTML = addLabelIfNoFieldsExists ? '<div class="view__no_fields_exists">' + STRINGS.NO_FIELDS + '</div>' : ''; } else { viewFields.innerHTML = ''; var numberOfChildren = 0; for (var i in fields) { var field = fields[i]; if (ignoredFieldNames.indexOf(field.name) >= 0) { continue; } numberOfChildren++; var html = MDSCommon.textToHtml(field.value); var status = field.name.split('_')[1]; var recordClass = 'view__log_record--' + status; if (MDSCommon.isBlank(html)) { switch (status) { case 'success': html = 'Script executed successfully'; break; case 'fail': html = 'Script failed'; break; } } var divFd = $('<div class="view__log_record ' + recordClass + '">' + html + '</div>').appendTo(viewFields); } } if (numberOfChildren === 0) { viewFields.innerHTML = addLabelIfNoFieldsExists ? '<div class="view__no_fields_exists">' + STRINGS.NO_FIELDS + '</div>' : ''; } return viewFields; }; EntityForm.getNoFieldsLabel = function(data) { return '<div class="view__no_fields_exists">' + STRINGS.NO_FIELDS + '</div>'; }; EntityForm.prototype.setViewFields = function(data, ignoredFieldNames, addLabelIfNoFieldsExists, comparer, classResolver) { var fields = data.fields.filter(function (field) { return field.name.indexOf('.') === -1; }); if (!Array.isArray(ignoredFieldNames)) { ignoredFieldNames = []; } if (addLabelIfNoFieldsExists == null) { addLabelIfNoFieldsExists = true; } var viewFields = document.getElementById('view__fields'); if (MDSCommon.isBlank(fields.filter(function (field) { return field.name !== 'description' && field.name.indexOf('$') != 0; }))) { viewFields.classList.add('view__fields--empty'); viewFields.innerHTML = addLabelIfNoFieldsExists ? EntityForm.getNoFieldsLabel(data) : ''; } else { viewFields.classList.add('view__fields--filled'); viewFields.innerHTML = ''; var numberOfChildren = 0; if (comparer) { fields.sort(comparer); } for (var i in fields) { var field = fields[i]; if (field.name.indexOf('$') !== -1 || ignoredFieldNames.indexOf(field.name) >= 0 || MDSCommon.isBlank(data.path) && UIConstants.ROOT_FIELDS.indexOf(field.name) >= 0 && MDSCommon.isBlank(field.value)) { continue; } numberOfChildren++; var html = MDSCommon.textToHtml(field.value); var multiline = html.indexOf('\n') >= 0; var multilineClass = multiline ? 'view__field_value--multiline' : ''; var multilineEnd = multiline ? ' <div class="view__field_value__end"></div>\n' : ''; var fieldClass = classResolver ? classResolver(field) : ''; var divFd = $('<div class="view__field ' + fieldClass + '">\n' + ' <div class="view__field_name">\n' + ' <div class="view__field_name_box">\n' + field.name + ' </div>\n' + ' </div>\n' + ' <div class="view__field_value ' + multilineClass + '">\n' + ' <div class="view__field_value_box">\n' + (MDSCommon.isPresent(field.value) ? html : '&mdash;') + ' </div>\n' + multilineEnd + ' </div>\n' + '</div>').appendTo(viewFields); if (multiline) { divFd.data('value', field.value); } } } if (numberOfChildren === 0) { viewFields.innerHTML = addLabelIfNoFieldsExists ? EntityForm.getNoFieldsLabel(data) : ''; } return viewFields; }; EntityForm.prototype.startEditing = function () { var self = this; self.setEditing(true); self.refresh(); }; EntityForm.prototype.setViewTitle = function (title) { var viewTitle = document.getElementById('view__title'); viewTitle.innerText = title; viewTitle.innerHTML += '<i style="margin-left: 5px;" class="fa fa-caret-down"></i>'; viewTitle.addEventListener('click', function () { $$('entity_form_menu').show(this) }); }; EntityForm.prototype.clearTimeouts = function () { if (this.viewWebsiteLinkDisabledTimeout) { clearTimeout(this.viewWebsiteLinkDisabledTimeout); delete this.viewWebsiteLinkDisabledTimeout; } if (this.viewWebsiteLinkDisabledCountdown) { clearTimeout(this.viewWebsiteLinkDisabledCountdown); delete this.viewWebsiteLinkDisabledCountdown; } }; EntityForm.prototype.setRootView = function(data) { var self = this; var language = (getCurrentLanguage() || 'en').toLowerCase(); var languagePrefix = language === 'en' ? '' : '/' + language; self.clearTimeouts(); $.ajax({ url: languagePrefix + '/fragments/root-view.html', method: 'get' }).then(function(html) { var view = document.getElementById('view'); var description = MDSCommon.findValueByName(data.fields, 'description'); var readme = MDSCommon.findValueByName(data.fields, 'readme'); var tags = (MDSCommon.findValueByName(data.fields, 'tags') || '').split(' ').filter(function(tag) { return tag != null && tag !== ''; }).map(function(tag) { return '<a class="view__tag" href="search?q=%23' + tag + '" target="_blank">' + tag + '</a>'; }).join(' '); var languageAbbr = MDSCommon.findValueByName(data.fields, 'language'); var countryAbbr = MDSCommon.findValueByName(data.fields, 'country'); var category = MDSCommon.findValueByName(data.fields, 'category'); var country = COUNTRIES[countryAbbr]; var language = COUNTRIES[languageAbbr]; if (category) { tags = '<span class="view__tag"><i class="view__tag_icon fa fa-' + CATEGORY_ICONS[category] + '"></i><span>' + tr$('categories.' + category) + '</span></span> ' + tags; } if (country && (languageAbbr === countryAbbr || (language.same || []).indexOf(countryAbbr) != -1)) { tags = '<span class="view__tag view__tag--flag view__tag--multi_link">' + '<img class="view__tag_icon view__tag_icon--flag" src="/images/square_flags/' + country.name + '.svg" />' + '<span class="view__tag_link">' + tr$('languagesShort.' + languageAbbr) + '</span> / ' + '<span class="view__tag_link">' + tr$('countries.' + countryAbbr) + '</span></span> ' + tags; } else { if (country) { tags = '<span class="view__tag view__tag--flag">' + '<img class="view__tag_icon view__tag_icon--flag" src="/images/square_flags/' + country.name + '.svg" />' + tr$('countries.' + countryAbbr) + '</span> ' + tags; } if (language) { tags = '<span class="view__tag view__tag--flag">' + '<img class="view__tag_icon view__tag_icon--flag" src="/images/square_flags/' + language.name + '.svg" />' + tr$('languagesShort.' + languageAbbr) + '</span> ' + tags; } } var license = MDSCommon.findValueByName(data.fields, 'license'); if (MDSCommon.isPresent(license)) { var licenseOrig = license; license = getLicenseWithoutVersion(license); if (license !== 'none') { tags = '<span class="view__tag view__tag--license' + ' data-license="' + licenseOrig + '"' + ' data-root="' + data.root + '"' + '><i class="view__tag_icon fa fa-balance-scale"></i>' + tr$('licenses.' + licenseOrig) + '</span> ' + tags; } } view.innerHTML = html; var ava = MDSCommon.findValueByName(data.fields, 'avatar'); if (MDSCommon.isPresent(ava)) { ava = Mydataspace.options.cdnURL + '/avatars/sm/' + ava + '.png'; } document.getElementById('view__overview_image').src = ava || '/images/icons/root.svg'; self.setViewTitle(MDSCommon.findValueByName(data.fields, 'name') || MDSCommon.getEntityName(data.root)); UIHelper.setInnerContentOrRemove('view__tags', tags, 'html'); if ((data.children || []).filter(function (child) { return child.path === 'website' }).length > 0) { var websiteLink = document.getElementById('view__website_link'); websiteLink.href = 'https://' + data.root + SITE_SUPER_DOMAIN; websiteLink.classList.remove('hidden'); websiteLink.setAttribute('data-root', data.root); } if (MDSCommon.isBlank(description) && MDSCommon.isBlank(tags)) { document.getElementById('view__description').innerHTML = '<i>' + STRINGS.NO_README + '</i>'; } else { document.getElementById('view__description').innerText = description; UIHelper.setInnerContentOrRemove('view__description', description); } // TODO: Uncomment for skeletons // document.getElementById('view__counters_likes_count').innerText = // MDSCommon.findValueByName(data.fields, '$likes'); // document.getElementById('view__counters_comments_count').innerText = // MDSCommon.findValueByName(data.fields, '$comments'); UIHelper.setInnerContentOrRemove('view__readme', md.render(readme || ''), 'html'); var viewFields = self.setViewFields(data, UIConstants.INVISIBLE_ROOT_FIELDS, false); if (viewFields.childNodes.length === 0) { viewFields.parentNode.removeChild(viewFields); } $(viewFields).on('click', '.view__field', function() { $(viewFields).find('.view__field--active').removeClass('view__field--active'); $(this).addClass('view__field--active'); var value = $(this).data('value'); UI.entityForm.showScriptViewWindow(value); }); data.children.forEach(function (child) { switch (child.path) { case 'statistics': document.getElementById('view_stat_website_visits_month').innerText = MDSCommon.humanizeNumber(MDSCommon.findValueByName(child.fields, 'websiteVisitsTotal') || 0); document.getElementById('view_stat_website_visitors_month').innerText = MDSCommon.humanizeNumber(MDSCommon.findValueByName(child.fields, 'websiteVisitorsTotal') || 0); document.getElementById('view_stat_api_calls_month').innerText = MDSCommon.humanizeNumber(MDSCommon.findValueByName(child.fields, 'apiCallsTotal') || 0); document.getElementById('view_stat_users_month').innerText = MDSCommon.humanizeNumber(MDSCommon.findValueByName(child.fields, 'userRegsTotal') || 0); break; } }); }); }; EntityForm.prototype.setTaskView = function(data) { var self = this; var language = (getCurrentLanguage() || 'en').toLowerCase(); var languagePrefix = language === 'en' ? '' : '/' + language; self.clearTimeouts(); $.ajax({ url: languagePrefix + '/fragments/task-view.html', method: 'get' }).then(function(html) { var view = document.getElementById('view'); view.innerHTML = html; document.getElementById('view__overview_icon').className = 'view__overview_icon fa fa-' + UIHelper.getIconByPath(data.path, data.numberOfChildren === 0, false); self.setViewTitle(MDSCommon.getEntityName(data.path)); var viewFields = this.setViewFields(data, ['status', 'statusText', 'interval'], false, function(x, y) { if (x.name === 'main.js') { return 1; } if (y.name === 'main.js') { return -1; } var isScriptX = /.*\.js$/.test(x.name); var isScriptY = /.*\.js$/.test(y.name); if (isScriptX && isScriptY || !isScriptX && !isScriptY) { if (x < y) { return -1; } else if (x.name > y.name) { return 1; } else { return 0; } } if (isScriptX) { return 1; } else { return -1; } }, function(x) { if (x.name === 'main.js') { return 'view__field--script view__field--script--main'; } if (/.*\.js$/.test(x.name)) { return 'view__field--script'; } return ''; }); var status = MDSCommon.findValueByName(data.fields, 'status'); if (status != null) { var statusClass; switch (status) { case 'success': statusClass = 'view__status--success'; break; case 'fail': statusClass = 'view__status--fail'; break; } if (statusClass) { document.getElementById('view__status').classList.add(statusClass); } var statusText = MDSCommon.findValueByName(data.fields, 'statusText'); if (!statusText) { switch (status) { case 'success': statusText = 'Script executed successfully'; break; case 'fail': statusText = 'Script failed'; break; } } document.getElementById('view__status').innerText = statusText; } var interval = MDSCommon.findValueByName(data.fields, 'interval') || 'paused'; document.getElementById('view__interval_' + interval).classList.add('view__check--checked'); $(viewFields).on('click', '.view__field', function() { $(viewFields).find('.view__field--active').removeClass('view__field--active'); $(this).addClass('view__field--active'); var value = $(this).data('value'); UI.entityForm.showScriptViewWindow(value); }); }.bind(this)); }; /** * * @param options * @param options.res * @param options.data * @param options.pageName * @param options.host * @param options.path * @param [options.target] */ EntityForm.prototype.setCmsIframe = function (options) { var self = this; var ok = false; for (var i in options.res.fields) { if ([options.pageName + '.html', options.pageName + '.pug'].indexOf(options.res.fields[i].name) >= 0) { ok = true; break; } } if (!ok) { throw new Error(options.pageName + '.html not found'); } var url = 'https://' + options.host + options.path + '/' + options.pageName + '.html?' + MDSCommon.guid(); self.setEntityView(options.data, true).then(function () { document.getElementById(options.target ? options.target : 'view__fields').innerHTML = '<iframe id="entity_form_iframe" class="view__iframe" src="' + url + '"></iframe><div id="entity_form_iframe_lock" class="view__iframe_lock"></div>'; }); }; EntityForm.prototype.setEntityCmsView = function (data) { var self = this; if (data.path !== 'data' && data.path.indexOf('data/') !== 0) { self.setEntityView(data); return; } var host = data.root + '.wiz.fastlix.com'; var path = data.path.substr('data'.length); var wizardsPath = 'website/wizards' + path; Mydataspace.entities.get({ root: data.root, path: wizardsPath }).then(function (res) { self.setCmsIframe({ data: data, res: res, host: host, path: path, pageName: 'view' }); }).catch(function () { return Mydataspace.entities.get({ root: data.root, path: MDSCommon.getParentPath(wizardsPath) }); }).then(function (res) { if (res) { self.setCmsIframe({ data: data, res: res, host: host, path: MDSCommon.getParentPath(path), pageName: 'view-item' }); } }).catch(function () { self.setEntityView(data); }); }; EntityForm.prototype.setEntityView = function(data, ignoreFields) { var self = this; if (self.currentId == null) { return; } self.clearTimeouts(); var entityType = UIHelper.getEntityTypeByPath(Identity.dataFromId(self.currentId).path); var language = (getCurrentLanguage() || 'en').toLowerCase(); var languagePrefix = language === 'en' ? '' : '/' + language; return $.ajax({ url: languagePrefix + '/fragments/entity-view.html', method: 'get' }).then(function(html) { var view = document.getElementById('view'); view.innerHTML = html; if (entityType === 'resource') { var resourceType = MDSCommon.findValueByName(data.fields, 'type'); var resourceName = MDSCommon.getPathName(data.path); switch (resourceType) { case 'avatar': document.getElementById('view__overview_icon').parentNode.innerHTML = '<img src="' + Mydataspace.options.cdnURL + '/avatars/sm/' + resourceName + '.png" class="view__overview_image" />'; break; case 'image': document.getElementById('view__overview_icon').parentNode.innerHTML = '<img src="' + Mydataspace.options.cdnURL + '/images/sm/' + resourceName + '.jpg" class="view__overview_image" />'; break; default: document.getElementById('view__overview_icon').className = 'view__overview_icon fa fa-' + UIHelper.getIconByPath(data.path, true, false); } } else { document.getElementById('view__overview_icon').className = 'view__overview_icon fa fa-' + UIHelper.getIconByPath(data.path, data.numberOfChildren === 0, false); } self.setViewTitle(MDSCommon.getEntityName(data.path)); if (ignoreFields) { return; } var viewFields = self.setViewFields(data); $(viewFields).on('click', '.view__field', function() { $(viewFields).find('.view__field--active').removeClass('view__field--active'); $(this).addClass('view__field--active'); var value = $(this).data('value'); var field = $(this).find('.view__field_name').text().trim(); if (value) { UI.entityForm.showScriptViewWindow(value, field); } }); }); }; EntityForm.prototype.setLogView = function(data) { var self = this; var language = (getCurrentLanguage() || 'en').toLowerCase(); var languagePrefix = language === 'en' ? '' : '/' + language; self.clearTimeouts(); $.ajax({ url: languagePrefix + '/fragments/log-view.html', method: 'get' }).then(function(html) { var view = document.getElementById('view'); view.innerHTML = html; document.getElementById('view__overview_icon').className = 'view__overview_icon fa fa-' + UIHelper.getIconByPath(data.path, data.numberOfChildren === 0, false); document.getElementById('view__title').innerText = MDSCommon.getPathName(data.path); var viewFields = self.setLogRecords(data.fields); $(viewFields).on('click', '.view__field', function() { $(viewFields).find('.view__field--active').removeClass('view__field--active'); $(this).addClass('view__field--active'); var value = $(this).data('value'); UI.entityForm.showScriptViewWindow(value); }); }); }; EntityForm.prototype.setView = function(data) { var self = this; self.clearTimeouts(); $('#view').append('<div class="view__loading"></div>'); if (MDSCommon.isBlank(data.path)) { self.setRootView(data); } else if (UIHelper.getEntityTypeByPath(data.path) === 'task') { self.setTaskView(data); } else if (UIHelper.getEntityTypeByPath(data.path) === 'log') { self.setLogView(data); } else { switch (UI.getMode()) { case 'dev': self.setEntityView(data); break; case 'cms': self.setEntityCmsView(data); break; } } $$('entity_form').hide(); $$('entity_view').show(); }; EntityForm.prototype.setNoFieldLabelVisible = function(visible) { var label = $$('NO_FIELDS_LABEL'); if (!label) { return; } if (visible) { label.show(); } else { label.hide(); } }; EntityForm.prototype.setCmsData = function(data) { var self = this; self.clear(); if (data.path !== 'data' && data.path.indexOf('data/') !== 0) { document.getElementById('view').innerHTML = '<div class="view__fields view__fields--empty"><div class="view__no_fields_exists">You can\'t edit this item in CMS mode</div></div>'; return; } var host = data.root + '.wiz.fastlix.com'; var path = data.path.substr('data'.length); var wizardsPath = 'website/wizards' + path; Mydataspace.entities.get({ root: data.root, path: wizardsPath }).then(function (res) { self.setCmsIframe({ data: data, res: res, host: host, path: path, pageName: 'edit' }); }).catch(function () { return Mydataspace.entities.get({ root: data.root, path: MDSCommon.getParentPath(wizardsPath) }); }).then(function (res) { if (res) { self.setCmsIframe({ data: data, res: res, host: host, path: MDSCommon.getParentPath(path), pageName: 'edit-item', target: 'view' }); } }).catch(function (err) { document.getElementById('view').innerHTML = '<div class="view__fields view__fields--empty"><div class="view__no_fields_exists">You can\'t edit this item in CMS mode</div></div>'; }); self.setClean(); $$('entity_form').hide(); $$('entity_view').show(); }; EntityForm.prototype.setData = function(data) { var formData = { name: Identity.nameFromData(data), othersCan: data.othersCan, maxNumberOfChildren: data.maxNumberOfChildren, isFixed: data.isFixed, childPrototype: Identity.idFromChildProtoData(data.childPrototype) }; this.clear(); $$('entity_form').setValues(formData); var fields = data.fields.filter(function (field) { return field.name.indexOf('.') === -1; }); if (MDSCommon.isBlank(data.path)) { // root entity // add fields from ROOT_FIELDS if not exists in data.fields for (var i in UIConstants.ROOT_FIELDS) { var field = UIConstants.ROOT_FIELDS[i]; if (!MDSCommon.findByName(data.fields, field)) { fields.push({ name: field, value: '', type: UIConstants.ROOT_FIELDS_TYPES[field] }); } } this.addRootFields({ fields: fields, type: data.type }); } else { this.setNoFieldLabelVisible(true); this.addFields(fields, false, UIHelper.getEntityTypeByPath(data.path)); } this.setClean(); $$('entity_view').hide(); $$('entity_form').show(); }; EntityForm.prototype.refresh = function() { var self = this; if (this.currentId == null) { return; } var entityType = UIHelper.getEntityTypeByPath(Identity.dataFromId(self.currentId).path); var isWithMeta = self.isEditing(); $$('entity_form').disable(); var req = !isWithMeta ? 'entities.get' : 'entities.getWithMeta'; Mydataspace.request(req, MDSCommon.extend(Identity.dataFromId(self.currentId), { children: true }), function(data) { if (!isWithMeta || entityType === 'resource') { self.setView(data); } else if (UI.getMode() === 'cms') { self.setCmsData(data); $$('entity_form').enable(); } else { self.setData(data); if (self.isProto()) { $('.entity_form__first_input').addClass('entity_form__first_input--proto'); $$('PROTO_IS_FIXED_LABEL').show(); } else { $('.entity_form__first_input').removeClass('entity_form__first_input--proto'); $$('PROTO_IS_FIXED_LABEL').hide(); } $$('entity_form').enable(); } self.emitLoaded(data); }, function(err) { UI.error(err); $$('entity_form').enable(); }); }; ///** // * Creates new entity by data received from the 'New Entity' form. // * @param formData data received from form by method getValues. // */ //EntityForm.prototype.createByFormData = function(formData) { // var newEntityId = Identity.childId(this.currentId, formData.name); // var data = Identity.dataFromId(newEntityId); // data.fields = []; // data.type = formData.type; // Mydataspace.emit('entities.create', data); //}; EntityForm.prototype.export = function () { Mydataspace.request('entities.export', Identity.dataFromId(this.currentId)); }; EntityForm.prototype.clone = function(entityId) { $$('clone_entity_window').showWithData({ entityId: entityId }); }; EntityForm.prototype.askDelete = function(entityId) { webix.confirm({ title: STRINGS.DELETE_ENTITY, text: STRINGS.REALLY_DELETE, ok: STRINGS.YES, cancel: STRINGS.NO, callback: function(result) { if (result) { UI.entityForm.delete(entityId); } } }); }; EntityForm.prototype.delete = function(entityId) { if (entityId == null) { entityId = this.currentId; } if (this.currentId == null) { return; } $$('entity_form').disable(); UI.deleteEntity(entityId); Mydataspace.request('entities.delete', Identity.dataFromId(entityId), function(data) { // do nothing because selected item already deleted. // this.selectedId = null; }, function(err) { UI.error(err); $$('entity_form').enable(); }); }; EntityForm.prototype.updateToolbar = function() { // if (!$$('entity_form').isDirty()) { // $$('SAVE_ENTITY_LABEL').disable(); // } else { // $$('SAVE_ENTITY_LABEL').enable(); // } }; /** * Marks entity form as unchanged. */ EntityForm.prototype.setClean = function() { $$('entity_form').setDirty(false); this.updateToolbar(); $$('entity_form').enable(); }; /** * Marks entity form as changed. */ EntityForm.prototype.setDirty = function() { $$('entity_form').setDirty(true); this.updateToolbar(); }; EntityForm.prototype.save = function() { var self = this; if (self.currentId == null) { return; } if (UI.getMode() === 'cms') { var saveToken = MDSCommon.guid(); document.getElementById('entity_form_iframe').contentWindow.postMessage({ message: 'MDSWizard.saveRequest', token: saveToken }, '*'); self.saveToken = saveToken; return; } var dirtyData = webix.CodeParser.expandNames($$('entity_form').getDirtyValues()); var existingData = webix.CodeParser.expandNames( Object.keys($$('entity_form').elements).reduce(function(ret, current) { ret[current] = ''; return ret; }, {})); var oldData = webix.CodeParser.expandNames($$('entity_form')._values); MDSCommon.extendOf(dirtyData, Identity.dataFromId(self.currentId)); dirtyData.fields = Fields.expandFields( Fields.getFieldsForSave(Fields.expandFields(dirtyData.fields), // dirty fields Object.keys(Fields.expandFields(existingData.fields) || {}), // current exists field names Fields.expandFields(oldData.fields))); // old fields $$('entity_form').disable(); if (typeof dirtyData.childPrototype !== 'undefined') { dirtyData.childPrototype = Identity.dataFromChildProtoId(dirtyData.childPrototype); } Mydataspace.request('entities.change', dirtyData, function(res) { if (dirtyData.name != null) { if (Identity.isRootId(self.currentId)) { self.selectedId = Identity.idFromData(MDSCommon.extend(res, { root: dirtyData.name })); } else { self.selectedId = Identity.idFromData(MDSCommon.extend(res, { path: MDSCommon.getChildPath(MDSCommon.getParentPath(res.path), dirtyData.name) })); } } self.refresh(); $$('entity_form').enable(); }, function(err) { UI.error(err); $$('entity_form').enable(); }); }; /** * Removes all fields from the form. */ EntityForm.prototype.clear = function() { var rows = $$('entity_form').getChildViews(); for (var i = rows.length - 1; i >= UIHelper.NUMBER_OF_FIXED_INPUTS_IN_FIELDS_FORM; i--) { var row = rows[i]; if (typeof row !== 'undefined') { $$('entity_form').removeView(row.config.id); } } }; EntityForm.prototype.addFields = function(fields, setDirty, type) { for (var i in fields) { var field = fields[i]; if (field.name.indexOf('$') === 0 || field.name.indexOf('.') >= 0) { continue; } switch (type) { case 'task': switch (field.name) { case 'status': case 'statusText': break; case 'interval': this.addTaskIntervalField(field, setDirty); break; default: this.addField(field, setDirty, type === 'proto'); break; } break; default: this.addField(field, setDirty, type === 'proto'); break; } } }; EntityForm.prototype.addRootFields = function(options) { var fields = options.fields; var setDirty = options.setDirty; fields.sort (function(x, y) { var xIndex = UIConstants.ROOT_FIELDS.indexOf(x.name); var yIndex = UIConstants.ROOT_FIELDS.indexOf(y.name); if (xIndex >= 0 && yIndex < 0) { return -1; } if (xIndex < 0 && yIndex >= 0) { return 1; } if (xIndex < 0 && yIndex < 0) { if (x.name < y.name) { return -1; } else if (x.name > y.name) { return 1; } else { return 0; } } if (xIndex < yIndex) { return -1; } else if (xIndex > yIndex) { return 1; } else { return 0; } }); for (var i in fields) { var field = fields[i]; if (field.name.indexOf('$') === 0) { continue; } if (UIConstants.OBSOLETE_ROOT_FIELDS.indexOf(field.name) >= 0) { continue; } // if (options.type === 'd' && UIConstants.HIDDEN_WEBSITE_FIELDS.indexOf(field.name) >= 0) { // continue; // } if (UIConstants.ROOT_FIELDS.indexOf(field.name) >= 0) { this.addRootField(field, setDirty); } else { this.addField(field, setDirty, false); } } }; EntityForm.prototype.onUploadAvatar = function(event) { UI.uploadResource( event.target.files[0], Identity.dataFromId(this.currentId).root, 'image', function(res) { var entityName = res.resources[0]; $$('entity_form__root_avatar_value').setValue(entityName); setTimeout(function () { $('#entity_form__root_img').prop('src', Mydataspace.options.cdnURL + '/avatars/sm/' + entityName + '.png'); }, 1000); }, function(err) { console.log(err); } ); }; EntityForm.prototype.addTaskIntervalField = function(data) { if (typeof $$('entity_form__' + data.name) !== 'undefined') { throw new Error('Field with this name already exists'); } this.setNoFieldLabelVisible(false); $$('entity_form').addView(UIControls.getRootFieldView('select', data, STRINGS.intervals), UIHelper.NUMBER_OF_FIXED_INPUTS_IN_FIELDS_FORM); }; EntityForm.prototype.addRootField = function(data) { if (typeof $$('entity_form__' + data.name) !== 'undefined') { throw new Error('Field with this name already exists'); } this.setNoFieldLabelVisible(false); switch (data.name) { case 'avatar': $$('entity_form').addView({ id: 'entity_form__' + data.name, css: 'entity_form__field entity_form__field--without-overflow', cols: [ { view: 'text', value: data.name, name: 'fields.' + data.name + '.name', hidden: true }, { view: 'text', value: data.type, id: 'entity_form__' + data.name + '_type', name: 'fields.' + data.name + '.type', hidden: true }, { view: 'text', value: data.value, name: 'fields.' + data.name + '.value', id: 'entity_form__root_avatar_value', hidden: true }, { view: 'label', css: 'entity_form__field_label_avatar', label: '<div style="visibility: hidden">fake</div>' + '<div class="entity_form__field_label">' + STRINGS.ROOT_FIELDS[data.name] + '</div>' + '<div class="entity_form__field_label_ellipse_right"></div>' + '<div class="entity_form__field_label_ellipse"></div>', width: UIHelper.LABEL_WIDTH, height: 38 }, { borderless: true, css: 'entity_form__root_img_template', template: '<img id="entity_form__root_img" class="entity_form__root_img" src="' + (MDSCommon.isPresent(data.value) ? Mydataspace.options.cdnURL + '/avatars/sm/' + data.value + '.png' : '/images/icons/root.svg') + '" alt="Icon" />', width: 32 }, { width: 16 }, { borderless: true, css: 'entity_form__root_img_upload_template', template: '<label class="entity_form__root_img_upload_lbl">' + ' <input type="file" ' + ' onchange="UI.entityForm.onUploadAvatar(event);"' + ' required />' + ' <span>' + STRINGS.ROOT_AVATAR_UPLOAD + '</span>' + '</label>' }, { width: 6 }, { view: 'button', label: STRINGS.ROOT_AVATAR_REMOVE, id: 'ROOT_AVATAR_REMOVE_LABEL', click: function() { $$('entity_form__root_avatar_value').setValue(''); document.getElementById('entity_form__root_img').setAttribute('src', '/images/icons/root.svg'); } } ] }); break; // case 'datasource': // var datasourceInitialOptions = {}; // if (MDSCommon.isPresent(data.value)) { // datasourceInitialOptions[data.value] = data.value; // } // $$('entity_form').addView(UIControls.getRootFieldView('select', data, datasourceInitialOptions)); // UIHelper.loadDatasourcesToCombo('entity_form__' + data.name + '_value'); // break; case 'license': $$('entity_form').addView(UIControls.getRootFieldView('list', data, STRINGS.licenses)); break; case 'category': $$('entity_form').addView(UIControls.getRootFieldView('list', data, STRINGS.categories, CATEGORY_ICONS)); break; case 'language': $$('entity_form').addView(UIControls.getRootFieldView('select', data, STRINGS.languages)); break; case 'country': $$('entity_form').addView(UIControls.getRootFieldView('select', data, STRINGS.countries)); break; case 'readme': case 'licenseText': $$('entity_form').addView(UIControls.getRootFieldView('textarea', data)); break; default: $$('entity_form').addView(UIControls.getRootFieldView('text', data)); break; } }; /** * Add new field to form. * @param {object} data Data of field * @param {boolean} setDirty Mark form as modified after field added. * @param {boolean} isProto Is field of prototype-entity. */ EntityForm.prototype.addField = function(data, setDirty, isProto) { var self = this; if (typeof $$('entity_form__' + data.name) !== 'undefined') { throw new Error('Field with this name already exists'); } this.setNoFieldLabelVisible(false); if (typeof setDirty === 'undefined') { setDirty = false; } if (setDirty) { var values = webix.copy($$('entity_form')._values); } $$('entity_form').addView({ id: 'entity_form__' + data.name, css: 'entity_form__field entity_form__field--text', cols: [ { view: 'text', value: data.name, name: 'fields.' + data.name + '.name', hidden: true }, { view: 'text', value: data.type, id: 'entity_form__' + data.name + '_type', name: 'fields.' + data.name + '.type', hidden: true }, { view: 'text', value: data.indexed, id: 'entity_form__' + data.name + '_indexed', name: 'fields.' + data.name + '.indexed', hidden: true }, { view: data.type === 'j' ? 'textarea' : 'text', type: data.type === '*' ? 'password': 'text', label: '<div style="visibility: hidden">fake</div>' + '<div class="entity_form__field_label">' + data.name + '</div>' + '<div class="entity_form__field_label_ellipse_right"></div>' + '<div class="entity_form__field_label_ellipse"></div>', labelWidth: UIHelper.LABEL_WIDTH, name: 'fields.' + data.name + '.value', id: 'entity_form__' + data.name + '_value', value: data.type === 'j' ? UIHelper.escapeHTML(data.value) : data.value, height: 32, css: 'entity_form__text_label', readonly: data.type === 'j', on: { onBlur: function() { // if (self.editScriptFieldId == 'entity_form__' + data.name + '_value') { // self.editScriptFieldId = null; // } }, onFocus: function() { if (data.type === 'j') { UI.entityForm.showScriptEditWindow(data.name); } else { UI.entityForm.hideScriptEditWindow(); } } } }, { view: 'button', width: 30, type: 'iconButton', icon: Fields.FIELD_TYPE_ICONS[data.type], css: 'entity_form__field_type_button', popup: 'entity_form__field_type_popup', options: Fields.getFieldTypesAsArrayOfIdValue(), id: 'entity_form__' + data.name + '_type_button', on: { onItemClick: function() { self.currentFieldName = data.name; $$('entity_form__field_type_popup_list').unselectAll(); } } }, { view: 'button', type: 'icon', css: 'entity_form__field_delete', icon: 'remove', width: 10, click: function() { self.deleteField(data.name); } }, { view: 'button', width: 10, type: 'iconButton', icon: !isProto ? null : Fields.FIELD_INDEXED_ICONS[(data.indexed || 'off').toString()], css: 'entity_form__field_indexed_button', popup: 'entity_form__field_indexed_popup', disabled: !isProto, id: 'entity_form__' + data.name + '_indexed_button', on: { onItemClick: function() { self.currentFieldName = data.name; $$('entity_form__field_indexed_list').unselectAll(); } } } ] }); if (setDirty) { $$('entity_form')._values = values; self.updateToolbar(); } }; EntityForm.prototype.deleteField = function(name) { var values = webix.copy($$('entity_form')._values); $$('entity_form').removeView('entity_form__' + name); $$('entity_form')._values = values; this.setDirty(); var rows = $$('entity_form').getChildViews(); if (rows.length === UIHelper.NUMBER_OF_FIXED_INPUTS_IN_FIELDS_FORM) { this.setNoFieldLabelVisible(true); } }; EntityForm.prototype.selectEditScriptTab = function (id, hideOthers) { Object.keys(UILayout.editScriptTabs).forEach(function (id2) { var tab = $$('edit_script_window__toolbar_' + id2 + '_button'); var classList = tab.getNode().classList; if (id == id2) { classList.add('webix_el_button--active'); tab.show(); } else { classList.remove('webix_el_button--active'); if (hideOthers) { tab.hide(); } else { tab.show(); } } }); var editor = $$('edit_script_window__editor').getEditor(); var editorTab = UILayout.editScriptTabs[id] || UILayout.editScriptTabs['text']; editor.getSession().setMode('ace/mode/' + editorTab.aceMode); editor.getValue(); }; EntityForm.prototype.showScriptViewWindow = function (text, fieldName) { $$('edit_script_window').showWithData({ text: text, readonly: true, fieldName: fieldName }); }; EntityForm.prototype.showScriptEditWindow = function (fieldName) { $$('edit_script_window').showWithData({ fieldName: fieldName }); }; EntityForm.prototype.hideScriptEditWindow = function() { $$('edit_script_window').hide(); };
apache-2.0
mbrown6944/LilSass
src/app/nav/navbar.component.js
1949
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var auth_service_1 = require('../user/auth.service'); var index_1 = require('../events/index'); var NavBarComponent = (function () { function NavBarComponent(auth, eventService) { this.auth = auth; this.eventService = eventService; this.searchTerm = ""; } NavBarComponent.prototype.searchSessions = function (searchTerm) { var _this = this; this.eventService.searchSessions(searchTerm).subscribe(function (sessions) { _this.foundSessions = sessions; }); }; NavBarComponent = __decorate([ core_1.Component({ selector: 'nav-bar', templateUrl: 'app/nav/navbar.component.html', styles: ["\n .nav.navbar-nav {font-size:15px} \n #searchForm {margin-right:100px; } \n @media (max-width: 1200px) {#searchForm {display:none}}\n li > a.active { color: #F97924; }\n "], }), __metadata('design:paramtypes', [auth_service_1.AuthService, index_1.EventService]) ], NavBarComponent); return NavBarComponent; }()); exports.NavBarComponent = NavBarComponent; //# sourceMappingURL=navbar.component.js.map
apache-2.0
tophua/spark1.52
tools/src/main/scala/org/apache/spark/tools/JavaAPICompletenessChecker.scala
16370
/* * 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.spark.tools import java.lang.reflect.{Type, Method} import scala.collection.mutable.ArrayBuffer import scala.language.existentials import org.apache.spark._ import org.apache.spark.api.java._ import org.apache.spark.rdd.{RDD, DoubleRDDFunctions, PairRDDFunctions, OrderedRDDFunctions} import org.apache.spark.streaming.StreamingContext import org.apache.spark.streaming.api.java.{JavaPairDStream, JavaDStream, JavaStreamingContext} import org.apache.spark.streaming.dstream.{DStream, PairDStreamFunctions} private[spark] abstract class SparkType(val name: String) private[spark] case class BaseType(override val name: String) extends SparkType(name) { override def toString: String = { name } } private[spark] case class ParameterizedType(override val name: String, parameters: Seq[SparkType], typebounds: String = "") extends SparkType(name) { override def toString: String = { if (typebounds != "") { typebounds + " " + name + "<" + parameters.mkString(", ") + ">" } else { name + "<" + parameters.mkString(", ") + ">" } } } private[spark] case class SparkMethod(name: String, returnType: SparkType, parameters: Seq[SparkType]) { override def toString: String = { returnType + " " + name + "(" + parameters.mkString(", ") + ")" } } /** * A tool for identifying methods that need to be ported from Scala to the Java API. * 用于识别需要从Scala移植到Java API的方法的工具 * * It uses reflection to find methods in the Scala API and rewrites those methods' signatures * into appropriate Java equivalents. If those equivalent methods have not been implemented in * the Java API, they are printed. * 它使用反射来查找Scala API中的方法,并将这些方法的签名重写为适当的Java等价物, * 如果Java API中尚未实现这些等效方法,则会打印它们。 */ object JavaAPICompletenessChecker { private def parseType(typeStr: String): SparkType = { if (!typeStr.contains("<")) { // Base types might begin with "class" or "interface", so we have to strip that off: //基类型可能以“class”或“interface”开头,所以我们必须剥离它: BaseType(typeStr.trim.split(" ").last) } else if (typeStr.endsWith("[]")) { //stripSuffix去掉<string>字串中结尾的字符 ParameterizedType("Array", Seq(parseType(typeStr.stripSuffix("[]")))) } else { val parts = typeStr.split("<", 2) val name = parts(0).trim assert (parts(1).last == '>') val parameters = parts(1).dropRight(1) ParameterizedType(name, parseTypeList(parameters)) } } private def parseTypeList(typeStr: String): Seq[SparkType] = { val types: ArrayBuffer[SparkType] = new ArrayBuffer[SparkType] var stack = 0 var token: StringBuffer = new StringBuffer() for (c <- typeStr.trim) { if (c == ',' && stack == 0) { types += parseType(token.toString) token = new StringBuffer() } else if (c == ' ' && stack != 0) { // continue } else { if (c == '<') { stack += 1 } else if (c == '>') { stack -= 1 } token.append(c) } } assert (stack == 0) if (token.toString != "") { types += parseType(token.toString) } types.toSeq } private def parseReturnType(typeStr: String): SparkType = { if (typeStr(0) == '<') { val parts = typeStr.drop(0).split(">", 2) val parsed = parseType(parts(1)).asInstanceOf[ParameterizedType] ParameterizedType(parsed.name, parsed.parameters, parts(0)) } else { parseType(typeStr) } } private def toSparkMethod(method: Method): SparkMethod = { val returnType = parseReturnType(method.getGenericReturnType.toString) val name = method.getName val parameters = method.getGenericParameterTypes.map(t => parseType(t.toString)) SparkMethod(name, returnType, parameters) } private def toJavaType(scalaType: SparkType, isReturnType: Boolean): SparkType = { val renameSubstitutions = Map( "scala.collection.Map" -> "java.util.Map", // TODO: the JavaStreamingContext API accepts Array arguments // instead of Lists, so this isn't a trivial translation / sub: "scala.collection.Seq" -> "java.util.List", "scala.Function2" -> "org.apache.spark.api.java.function.Function2", "scala.collection.Iterator" -> "java.util.Iterator", "scala.collection.mutable.Queue" -> "java.util.Queue", "double" -> "java.lang.Double" ) // Keep applying the substitutions until we've reached a fixedpoint. def applySubs(scalaType: SparkType): SparkType = { scalaType match { case ParameterizedType(name, parameters, typebounds) => name match { case "org.apache.spark.rdd.RDD" => if (parameters(0).name == classOf[Tuple2[_, _]].getName) { val tupleParams = parameters(0).asInstanceOf[ParameterizedType].parameters.map(applySubs) ParameterizedType(classOf[JavaPairRDD[_, _]].getName, tupleParams) } else { ParameterizedType(classOf[JavaRDD[_]].getName, parameters.map(applySubs)) } case "org.apache.spark.streaming.dstream.DStream" => if (parameters(0).name == classOf[Tuple2[_, _]].getName) { val tupleParams = parameters(0).asInstanceOf[ParameterizedType].parameters.map(applySubs) ParameterizedType("org.apache.spark.streaming.api.java.JavaPairDStream", tupleParams) } else { ParameterizedType("org.apache.spark.streaming.api.java.JavaDStream", parameters.map(applySubs)) } case "scala.Option" => { if (isReturnType) { ParameterizedType("com.google.common.base.Optional", parameters.map(applySubs)) } else { applySubs(parameters(0)) } } case "scala.Function1" => val firstParamName = parameters.last.name if (firstParamName.startsWith("scala.collection.Traversable") || firstParamName.startsWith("scala.collection.Iterator")) { ParameterizedType("org.apache.spark.api.java.function.FlatMapFunction", Seq(parameters(0), parameters.last.asInstanceOf[ParameterizedType].parameters(0)).map(applySubs)) } else if (firstParamName == "scala.runtime.BoxedUnit") { ParameterizedType("org.apache.spark.api.java.function.VoidFunction", parameters.dropRight(1).map(applySubs)) } else { ParameterizedType("org.apache.spark.api.java.function.Function", parameters.map(applySubs)) } case _ => ParameterizedType(renameSubstitutions.getOrElse(name, name), parameters.map(applySubs)) } case BaseType(name) => if (renameSubstitutions.contains(name)) { BaseType(renameSubstitutions(name)) } else { scalaType } } } var oldType = scalaType var newType = applySubs(scalaType) while (oldType != newType) { oldType = newType newType = applySubs(scalaType) } newType } private def toJavaMethod(method: SparkMethod): SparkMethod = { val params = method.parameters .filterNot(_.name == "scala.reflect.ClassTag") .map(toJavaType(_, isReturnType = false)) SparkMethod(method.name, toJavaType(method.returnType, isReturnType = true), params) } private def isExcludedByName(method: Method): Boolean = { val name = method.getDeclaringClass.getName + "." + method.getName // Scala methods that are declared as private[mypackage] become public in the resulting // Java bytecode. As a result, we need to manually exclude those methods here. // This list also includes a few methods that are only used by the web UI or other // internal Spark components. val excludedNames = Seq( "org.apache.spark.rdd.RDD.origin", "org.apache.spark.rdd.RDD.elementClassTag", "org.apache.spark.rdd.RDD.checkpointData", "org.apache.spark.rdd.RDD.partitioner", "org.apache.spark.rdd.RDD.partitions", "org.apache.spark.rdd.RDD.firstParent", "org.apache.spark.rdd.RDD.doCheckpoint", "org.apache.spark.rdd.RDD.markCheckpointed", "org.apache.spark.rdd.RDD.clearDependencies", "org.apache.spark.rdd.RDD.getDependencies", "org.apache.spark.rdd.RDD.getPartitions", "org.apache.spark.rdd.RDD.dependencies", "org.apache.spark.rdd.RDD.getPreferredLocations", "org.apache.spark.rdd.RDD.collectPartitions", "org.apache.spark.rdd.RDD.computeOrReadCheckpoint", "org.apache.spark.rdd.PairRDDFunctions.getKeyClass", "org.apache.spark.rdd.PairRDDFunctions.getValueClass", "org.apache.spark.SparkContext.stringToText", "org.apache.spark.SparkContext.makeRDD", "org.apache.spark.SparkContext.runJob", "org.apache.spark.SparkContext.runApproximateJob", "org.apache.spark.SparkContext.clean", "org.apache.spark.SparkContext.metadataCleaner", "org.apache.spark.SparkContext.ui", "org.apache.spark.SparkContext.newShuffleId", "org.apache.spark.SparkContext.newRddId", "org.apache.spark.SparkContext.cleanup", "org.apache.spark.SparkContext.receiverJobThread", "org.apache.spark.SparkContext.getRDDStorageInfo", "org.apache.spark.SparkContext.addedFiles", "org.apache.spark.SparkContext.addedJars", "org.apache.spark.SparkContext.persistentRdds", "org.apache.spark.SparkContext.executorEnvs", "org.apache.spark.SparkContext.checkpointDir", "org.apache.spark.SparkContext.getSparkHome", "org.apache.spark.SparkContext.executorMemoryRequested", "org.apache.spark.SparkContext.getExecutorStorageStatus", "org.apache.spark.streaming.dstream.DStream.generatedRDDs", "org.apache.spark.streaming.dstream.DStream.zeroTime", "org.apache.spark.streaming.dstream.DStream.rememberDuration", "org.apache.spark.streaming.dstream.DStream.storageLevel", "org.apache.spark.streaming.dstream.DStream.mustCheckpoint", "org.apache.spark.streaming.dstream.DStream.checkpointDuration", "org.apache.spark.streaming.dstream.DStream.checkpointData", "org.apache.spark.streaming.dstream.DStream.graph", "org.apache.spark.streaming.dstream.DStream.isInitialized", "org.apache.spark.streaming.dstream.DStream.parentRememberDuration", "org.apache.spark.streaming.dstream.DStream.initialize", "org.apache.spark.streaming.dstream.DStream.validate", "org.apache.spark.streaming.dstream.DStream.setContext", "org.apache.spark.streaming.dstream.DStream.setGraph", "org.apache.spark.streaming.dstream.DStream.remember", "org.apache.spark.streaming.dstream.DStream.getOrCompute", "org.apache.spark.streaming.dstream.DStream.generateJob", "org.apache.spark.streaming.dstream.DStream.clearOldMetadata", "org.apache.spark.streaming.dstream.DStream.addMetadata", "org.apache.spark.streaming.dstream.DStream.updateCheckpointData", "org.apache.spark.streaming.dstream.DStream.restoreCheckpointData", "org.apache.spark.streaming.dstream.DStream.isTimeValid", "org.apache.spark.streaming.StreamingContext.nextNetworkInputStreamId", "org.apache.spark.streaming.StreamingContext.checkpointDir", "org.apache.spark.streaming.StreamingContext.checkpointDuration", "org.apache.spark.streaming.StreamingContext.receiverJobThread", "org.apache.spark.streaming.StreamingContext.scheduler", "org.apache.spark.streaming.StreamingContext.initialCheckpoint", "org.apache.spark.streaming.StreamingContext.getNewNetworkStreamId", "org.apache.spark.streaming.StreamingContext.validate", "org.apache.spark.streaming.StreamingContext.createNewSparkContext", "org.apache.spark.streaming.StreamingContext.rddToFileName", "org.apache.spark.streaming.StreamingContext.getSparkCheckpointDir", "org.apache.spark.streaming.StreamingContext.env", "org.apache.spark.streaming.StreamingContext.graph", "org.apache.spark.streaming.StreamingContext.isCheckpointPresent" ) val excludedPatterns = Seq( """^org\.apache\.spark\.SparkContext\..*To.*Functions""", """^org\.apache\.spark\.SparkContext\..*WritableConverter""", """^org\.apache\.spark\.SparkContext\..*To.*Writable""" ).map(_.r) lazy val excludedByPattern = !excludedPatterns.map(_.findFirstIn(name)).filter(_.isDefined).isEmpty name.contains("$") || excludedNames.contains(name) || excludedByPattern } private def isExcludedByInterface(method: Method): Boolean = { val excludedInterfaces = Set("org.apache.spark.Logging", "org.apache.hadoop.mapreduce.HadoopMapReduceUtil") def toComparisionKey(method: Method): (Class[_], String, Type) = (method.getReturnType, method.getName, method.getGenericReturnType) val interfaces = method.getDeclaringClass.getInterfaces.filter { i => excludedInterfaces.contains(i.getName) } val excludedMethods = interfaces.flatMap(_.getMethods.map(toComparisionKey)) excludedMethods.contains(toComparisionKey(method)) } private def printMissingMethods(scalaClass: Class[_], javaClass: Class[_]) { val methods = scalaClass.getMethods .filterNot(_.isAccessible) .filterNot(isExcludedByName) .filterNot(isExcludedByInterface) val javaEquivalents = methods.map(m => toJavaMethod(toSparkMethod(m))).toSet val javaMethods = javaClass.getMethods.map(toSparkMethod).toSet val missingMethods = javaEquivalents -- javaMethods for (method <- missingMethods) { // scalastyle:off println println(method) // scalastyle:on println } } def main(args: Array[String]) { // scalastyle:off println //缺少RDD方法 println("Missing RDD methods") printMissingMethods(classOf[RDD[_]], classOf[JavaRDD[_]]) println() //缺少PairRDD方法 println("Missing PairRDD methods") printMissingMethods(classOf[PairRDDFunctions[_, _]], classOf[JavaPairRDD[_, _]]) println() //缺少DoubleRDD方法 println("Missing DoubleRDD methods") printMissingMethods(classOf[DoubleRDDFunctions], classOf[JavaDoubleRDD]) println() //缺少OrderedRDD方法 println("Missing OrderedRDD methods") printMissingMethods(classOf[OrderedRDDFunctions[_, _, _]], classOf[JavaPairRDD[_, _]]) println() //缺少SparkContext方法 println("Missing SparkContext methods") printMissingMethods(classOf[SparkContext], classOf[JavaSparkContext]) println() //缺少StreamingContext方法 println("Missing StreamingContext methods") printMissingMethods(classOf[StreamingContext], classOf[JavaStreamingContext]) println() // 缺少DStream方法 println("Missing DStream methods") printMissingMethods(classOf[DStream[_]], classOf[JavaDStream[_]]) println() //缺少PairDStream方法 println("Missing PairDStream methods") printMissingMethods(classOf[PairDStreamFunctions[_, _]], classOf[JavaPairDStream[_, _]]) println() // scalastyle:on println } }
apache-2.0
improbable-io/etcd
storage/kvstore.go
11960
// Copyright 2015 CoreOS, 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 storage import ( "errors" "log" "math" "math/rand" "sync" "time" "github.com/coreos/etcd/storage/backend" "github.com/coreos/etcd/storage/storagepb" ) var ( batchLimit = 10000 batchInterval = 100 * time.Millisecond keyBucketName = []byte("key") metaBucketName = []byte("meta") scheduledCompactKeyName = []byte("scheduledCompactRev") finishedCompactKeyName = []byte("finishedCompactRev") ErrTxnIDMismatch = errors.New("storage: txn id mismatch") ErrCompacted = errors.New("storage: required revision has been compacted") ErrFutureRev = errors.New("storage: required revision is a future revision") ErrCanceled = errors.New("storage: watcher is canceled") ) type store struct { mu sync.RWMutex b backend.Backend kvindex index currentRev revision // the main revision of the last compaction compactMainRev int64 tmu sync.Mutex // protect the txnID field txnID int64 // tracks the current txnID to verify txn operations wg sync.WaitGroup stopc chan struct{} } func New(path string) KV { return newStore(path) } func newStore(path string) *store { s := &store{ b: backend.New(path, batchInterval, batchLimit), kvindex: newTreeIndex(), currentRev: revision{}, compactMainRev: -1, stopc: make(chan struct{}), } tx := s.b.BatchTx() tx.Lock() tx.UnsafeCreateBucket(keyBucketName) tx.UnsafeCreateBucket(metaBucketName) tx.Unlock() s.b.ForceCommit() return s } func (s *store) Rev() int64 { s.mu.RLock() defer s.mu.RUnlock() return s.currentRev.main } func (s *store) Put(key, value []byte) int64 { id := s.TxnBegin() s.put(key, value) s.txnEnd(id) putCounter.Inc() return int64(s.currentRev.main) } func (s *store) Range(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) { id := s.TxnBegin() kvs, rev, err = s.rangeKeys(key, end, limit, rangeRev) s.txnEnd(id) rangeCounter.Inc() return kvs, rev, err } func (s *store) DeleteRange(key, end []byte) (n, rev int64) { id := s.TxnBegin() n = s.deleteRange(key, end) s.txnEnd(id) deleteCounter.Inc() return n, int64(s.currentRev.main) } func (s *store) TxnBegin() int64 { s.mu.Lock() s.currentRev.sub = 0 s.tmu.Lock() defer s.tmu.Unlock() s.txnID = rand.Int63() return s.txnID } func (s *store) TxnEnd(txnID int64) error { err := s.txnEnd(txnID) if err != nil { return err } txnCounter.Inc() return nil } // txnEnd is used for unlocking an internal txn. It does // not increase the txnCounter. func (s *store) txnEnd(txnID int64) error { s.tmu.Lock() defer s.tmu.Unlock() if txnID != s.txnID { return ErrTxnIDMismatch } if s.currentRev.sub != 0 { s.currentRev.main += 1 } s.currentRev.sub = 0 s.mu.Unlock() return nil } func (s *store) TxnRange(txnID int64, key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) { s.tmu.Lock() defer s.tmu.Unlock() if txnID != s.txnID { return nil, 0, ErrTxnIDMismatch } return s.rangeKeys(key, end, limit, rangeRev) } func (s *store) TxnPut(txnID int64, key, value []byte) (rev int64, err error) { s.tmu.Lock() defer s.tmu.Unlock() if txnID != s.txnID { return 0, ErrTxnIDMismatch } s.put(key, value) return int64(s.currentRev.main + 1), nil } func (s *store) TxnDeleteRange(txnID int64, key, end []byte) (n, rev int64, err error) { s.tmu.Lock() defer s.tmu.Unlock() if txnID != s.txnID { return 0, 0, ErrTxnIDMismatch } n = s.deleteRange(key, end) if n != 0 || s.currentRev.sub != 0 { rev = int64(s.currentRev.main + 1) } else { rev = int64(s.currentRev.main) } return n, rev, nil } // RangeEvents gets the events from key to end in [startRev, endRev). // If `end` is nil, the request only observes the events on key. // If `end` is not nil, it observes the events on key range [key, range_end). // Limit limits the number of events returned. // If startRev <=0, rangeEvents returns events from the beginning of uncompacted history. // If endRev <=0, it indicates there is no end revision. // // If the required start rev is compacted, ErrCompacted will be returned. // If the required start rev has not happened, ErrFutureRev will be returned. // // RangeEvents returns events that satisfy the requirement (0 <= n <= limit). // If events in the revision range have not all happened, it returns immeidately // what is available. // It also returns nextRev which indicates the start revision used for the following // RangeEvents call. The nextRev could be smaller than the given endRev if the store // has not progressed so far or it hits the event limit. // // TODO: return byte slices instead of events to avoid meaningless encode and decode. func (s *store) RangeEvents(key, end []byte, limit, startRev, endRev int64) (evs []storagepb.Event, nextRev int64, err error) { s.mu.Lock() defer s.mu.Unlock() if startRev > 0 && startRev <= s.compactMainRev { return nil, 0, ErrCompacted } if startRev > s.currentRev.main { return nil, 0, ErrFutureRev } revs := s.kvindex.RangeEvents(key, end, startRev) if len(revs) == 0 { return nil, s.currentRev.main + 1, nil } tx := s.b.BatchTx() tx.Lock() defer tx.Unlock() // fetch events from the backend using revisions for _, rev := range revs { if endRev > 0 && rev.main >= endRev { return evs, rev.main, nil } revbytes := newRevBytes() revToBytes(rev, revbytes) _, vs := tx.UnsafeRange(keyBucketName, revbytes, nil, 0) if len(vs) != 1 { log.Fatalf("storage: range cannot find rev (%d,%d)", rev.main, rev.sub) } e := storagepb.Event{} if err := e.Unmarshal(vs[0]); err != nil { log.Fatalf("storage: cannot unmarshal event: %v", err) } evs = append(evs, e) if limit > 0 && len(evs) >= int(limit) { return evs, rev.main + 1, nil } } return evs, s.currentRev.main + 1, nil } func (s *store) Compact(rev int64) error { s.mu.Lock() defer s.mu.Unlock() if rev <= s.compactMainRev { return ErrCompacted } if rev > s.currentRev.main { return ErrFutureRev } start := time.Now() s.compactMainRev = rev rbytes := newRevBytes() revToBytes(revision{main: rev}, rbytes) tx := s.b.BatchTx() tx.Lock() tx.UnsafePut(metaBucketName, scheduledCompactKeyName, rbytes) tx.Unlock() // ensure that desired compaction is persisted s.b.ForceCommit() keep := s.kvindex.Compact(rev) s.wg.Add(1) go s.scheduleCompaction(rev, keep) indexCompactionPauseDurations.Observe(float64(time.Now().Sub(start) / time.Millisecond)) return nil } func (s *store) Hash() (uint32, error) { s.b.ForceCommit() return s.b.Hash() } func (s *store) Snapshot() Snapshot { s.b.ForceCommit() return s.b.Snapshot() } func (s *store) Restore() error { s.mu.Lock() defer s.mu.Unlock() min, max := newRevBytes(), newRevBytes() revToBytes(revision{}, min) revToBytes(revision{main: math.MaxInt64, sub: math.MaxInt64}, max) // restore index tx := s.b.BatchTx() tx.Lock() _, finishedCompactBytes := tx.UnsafeRange(metaBucketName, finishedCompactKeyName, nil, 0) if len(finishedCompactBytes) != 0 { s.compactMainRev = bytesToRev(finishedCompactBytes[0]).main log.Printf("storage: restore compact to %d", s.compactMainRev) } // TODO: limit N to reduce max memory usage keys, vals := tx.UnsafeRange(keyBucketName, min, max, 0) for i, key := range keys { e := &storagepb.Event{} if err := e.Unmarshal(vals[i]); err != nil { log.Fatalf("storage: cannot unmarshal event: %v", err) } rev := bytesToRev(key) // restore index switch e.Type { case storagepb.PUT: s.kvindex.Restore(e.Kv.Key, revision{e.Kv.CreateRevision, 0}, rev, e.Kv.Version) case storagepb.DELETE: s.kvindex.Tombstone(e.Kv.Key, rev) default: log.Panicf("storage: unexpected event type %s", e.Type) } // update revision s.currentRev = rev } _, scheduledCompactBytes := tx.UnsafeRange(metaBucketName, scheduledCompactKeyName, nil, 0) if len(scheduledCompactBytes) != 0 { scheduledCompact := bytesToRev(scheduledCompactBytes[0]).main if scheduledCompact > s.compactMainRev { log.Printf("storage: resume scheduled compaction at %d", scheduledCompact) go s.Compact(scheduledCompact) } } tx.Unlock() return nil } func (s *store) Close() error { close(s.stopc) s.wg.Wait() return s.b.Close() } func (a *store) Equal(b *store) bool { if a.currentRev != b.currentRev { return false } if a.compactMainRev != b.compactMainRev { return false } return a.kvindex.Equal(b.kvindex) } // range is a keyword in Go, add Keys suffix. func (s *store) rangeKeys(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) { curRev := int64(s.currentRev.main) if s.currentRev.sub > 0 { curRev += 1 } if rangeRev > curRev { return nil, s.currentRev.main, ErrFutureRev } if rangeRev <= 0 { rev = curRev } else { rev = rangeRev } if rev <= s.compactMainRev { return nil, 0, ErrCompacted } _, revpairs := s.kvindex.Range(key, end, int64(rev)) if len(revpairs) == 0 { return nil, rev, nil } tx := s.b.BatchTx() tx.Lock() defer tx.Unlock() for _, revpair := range revpairs { revbytes := newRevBytes() revToBytes(revpair, revbytes) _, vs := tx.UnsafeRange(keyBucketName, revbytes, nil, 0) if len(vs) != 1 { log.Fatalf("storage: range cannot find rev (%d,%d)", revpair.main, revpair.sub) } e := &storagepb.Event{} if err := e.Unmarshal(vs[0]); err != nil { log.Fatalf("storage: cannot unmarshal event: %v", err) } kvs = append(kvs, *e.Kv) if limit > 0 && len(kvs) >= int(limit) { break } } return kvs, rev, nil } func (s *store) put(key, value []byte) { rev := s.currentRev.main + 1 c := rev // if the key exists before, use its previous created _, created, ver, err := s.kvindex.Get(key, rev) if err == nil { c = created.main } ibytes := newRevBytes() revToBytes(revision{main: rev, sub: s.currentRev.sub}, ibytes) ver = ver + 1 event := storagepb.Event{ Type: storagepb.PUT, Kv: &storagepb.KeyValue{ Key: key, Value: value, CreateRevision: c, ModRevision: rev, Version: ver, }, } d, err := event.Marshal() if err != nil { log.Fatalf("storage: cannot marshal event: %v", err) } tx := s.b.BatchTx() tx.Lock() defer tx.Unlock() tx.UnsafePut(keyBucketName, ibytes, d) s.kvindex.Put(key, revision{main: rev, sub: s.currentRev.sub}) s.currentRev.sub += 1 } func (s *store) deleteRange(key, end []byte) int64 { rrev := s.currentRev.main if s.currentRev.sub > 0 { rrev += 1 } keys, _ := s.kvindex.Range(key, end, rrev) if len(keys) == 0 { return 0 } for _, key := range keys { s.delete(key) } return int64(len(keys)) } func (s *store) delete(key []byte) { mainrev := s.currentRev.main + 1 tx := s.b.BatchTx() tx.Lock() defer tx.Unlock() ibytes := newRevBytes() revToBytes(revision{main: mainrev, sub: s.currentRev.sub}, ibytes) event := storagepb.Event{ Type: storagepb.DELETE, Kv: &storagepb.KeyValue{ Key: key, }, } d, err := event.Marshal() if err != nil { log.Fatalf("storage: cannot marshal event: %v", err) } tx.UnsafePut(keyBucketName, ibytes, d) err = s.kvindex.Tombstone(key, revision{main: mainrev, sub: s.currentRev.sub}) if err != nil { log.Fatalf("storage: cannot tombstone an existing key (%s): %v", string(key), err) } s.currentRev.sub += 1 }
apache-2.0
opitzconsulting/orcas
orcas_core/build_source/orcas_dbdoc/src/main/java/de/oc/dbdoc/load/DbLoader.java
3168
package de.oc.dbdoc.load; import de.oc.dbdoc.ant.Diagram; import de.oc.dbdoc.ant.Tableregistry; import de.oc.dbdoc.schemadata.Association; import de.oc.dbdoc.schemadata.Column; import de.oc.dbdoc.schemadata.Schema; import de.oc.dbdoc.schemadata.Table; import de.opitzconsulting.orcasDsl.Index; import de.opitzconsulting.orcasDsl.Model; import de.opitzconsulting.orcasDsl.UniqueKey; public class DbLoader { public DbLoader() { } public Schema loadSchema( Diagram pRootDiagram, Model pModel, Tableregistry pTableregistry ) { Schema lSchema = new Schema(); pModel.getModel_elements().stream().filter( p -> p instanceof de.opitzconsulting.orcasDsl.Table ).map( p -> (de.opitzconsulting.orcasDsl.Table) p ).forEach( pTable -> { if( pRootDiagram.isTableIncluded( pTable.getName(), pTableregistry ) ) { Table lTable = new Table( pTable.getName() ); lSchema.addTable( lTable ); pTable.getColumns().forEach( pColumn -> lTable.addColumn( new Column( pColumn.getName(), pColumn.getObject_type() != null ? pColumn.getObject_type() : pColumn.getData_type().getName() ) ) ); } } ); pModel.getModel_elements().stream().filter( p -> p instanceof de.opitzconsulting.orcasDsl.Table ).map( p -> (de.opitzconsulting.orcasDsl.Table) p ).forEach( pTable -> { pTable.getForeign_keys().forEach( pFK -> { Table lTableFrom = lSchema.findTable( pTable.getName() ); Table lTableTo = lSchema.findTable( pFK.getDestTable() ); if( lTableFrom != null && lTableTo != null ) { String lConstraintName = pFK.getConsName(); boolean lIsAllSrcColumnsNullable = !pFK.getSrcColumns().stream().map( pSrcColumnRef -> pTable.getColumns().stream().filter( p -> p.getName().equalsIgnoreCase( pSrcColumnRef.getColumn_name() ) ).findAny().get() ).filter( p -> p.isNotnull() ).findAny().isPresent(); boolean lIsExistsUkForSrcColumns = pFK.getSrcColumns().size() == 1 && pTable.getInd_uks().stream().filter( p -> { if( p instanceof UniqueKey ) { UniqueKey lUniqueKey = (UniqueKey) p; return lUniqueKey.getUk_columns().size() == 1 && lUniqueKey.getUk_columns().get( 0 ).getColumn_name().equalsIgnoreCase( pFK.getSrcColumns().get( 0 ).getColumn_name() ); } else { Index lIndex = (Index) p; return lIndex.getIndex_columns().size() == 1 && lIndex.getIndex_columns().get( 0 ).getColumn_name().equalsIgnoreCase( pFK.getSrcColumns().get( 0 ).getColumn_name() ); } } ).findAny().isPresent(); Association lAssociation = new Association( lConstraintName, lTableFrom, lTableTo, true, 0, lIsExistsUkForSrcColumns ? 1 : Association.MULTIPLICITY_N, lIsAllSrcColumnsNullable ? 0 : 1, 1 ); lSchema.addAssociation( lAssociation ); pFK.getSrcColumns().forEach( pColumn -> lAssociation.addColumnFrom( pColumn.getColumn_name() ) ); pFK.getDestColumns().forEach( pColumn -> lAssociation.addColumnTo( pColumn.getColumn_name() ) ); } } ); } ); return lSchema; } }
apache-2.0
gund/tasktrack
modules/gh_buttons/module.js
350
/** * @author Alex Malkevich * @project tasktrack * @file module.js * @package js * @date 08.08.2013 18:34:12 * @id $js-2013-module.js$ * module.js - Include Module GH-Buttons */ // Module Name const MODULE_GHBTNS = 'gh_buttons'; // Include CSS document.write('<link rel="stylesheet" href="'+MODULE_PATH[MODULE_GHBTNS]+'/css/styles.css">');
apache-2.0
RabbitTeam/RabbitHub
Components/Rabbit.Components.Data.EntityFramework.MySql/MySqlEntityFrameworkDataServicesProvider.cs
849
using MySql.Data.MySqlClient; using Rabbit.Components.Data.EntityFramework.Providers; using Rabbit.Components.Data.MySql; using System.Data.Entity.Core.Common; namespace Rabbit.Components.Data.EntityFramework.MySql { /// <summary> /// MySql EntityFramework 数据服务提供程序。 /// </summary> public class MySqlEntityFrameworkDataServicesProvider : MySqlDataServicesProvider, IEntityFrameworkDataServicesProvider { private static readonly MySqlProviderServices ProviderInstance = new MySqlProviderServices(); #region Implementation of IEntityFrameworkDataServicesProvider /// <summary> /// 数据库提供服务。 /// </summary> public DbProviderServices Instance => ProviderInstance; #endregion Implementation of IEntityFrameworkDataServicesProvider } }
apache-2.0
malmazuke/SnakeTest
Assets/Scripts/CameraFollow.cs
465
using UnityEngine; using System.Collections; public class CameraFollow : MonoBehaviour { public GameObject target; private bool isFollowing; void Start () { isFollowing = true; } // Update is called once per frame void Update () { if (isFollowing) { Vector3 destination = target.transform.position; destination.y = transform.position.y; transform.position = destination; } } }
apache-2.0
hmrc/ct-calculations
src/main/scala/uk/gov/hmrc/ct/computations/CP284.scala
1245
/* * Copyright 2021 HM Revenue & Customs * * 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 uk.gov.hmrc.ct.computations import uk.gov.hmrc.ct.box.{Calculated, CtBoxIdentifier, CtOptionalInteger} import uk.gov.hmrc.ct.computations.calculations.NetTradingProfitCalculator import uk.gov.hmrc.ct.computations.retriever.ComputationsBoxRetriever case class CP284(value: Option[Int]) extends CtBoxIdentifier("Net trading profit") with CtOptionalInteger object CP284 extends Calculated[CP284, ComputationsBoxRetriever] with NetTradingProfitCalculator { override def calculate(fieldValueRetriever: ComputationsBoxRetriever): CP284 = netTradingProfitCalculation(fieldValueRetriever.cp117(), fieldValueRetriever.cp283()) }
apache-2.0
mulleady1/podsy
pods/wsgi.py
383
""" WSGI config for pods project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pods.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
apache-2.0
factoryfx/factoryfx
javafxFactoryEditing/src/main/java/io/github/factoryfx/javafx/widget/factory/masterdetail/DataView.java
249
package io.github.factoryfx.javafx.widget.factory.masterdetail; import io.github.factoryfx.factory.FactoryBase; import javafx.collections.ObservableList; public interface DataView<T extends FactoryBase<?,?>> { ObservableList<T> dataList(); }
apache-2.0
eneiasbrumjr/cogib
app/Http/Controllers/SindicatoController.php
4338
<?php namespace App\Http\Controllers; use Session; use App\Estado; use Datatables; use App\Sindicato; use App\Http\Requests; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Requests\StoreSindicatoRequest; class SindicatoController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct(Estado $estado) { $this->middleware('auth'); $this->estadoModel = $estado; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function getIndex() { $estados = $this->estadoModel->lists('sigla', 'id'); return view('sindicato.index', compact('estados')); } /** * Show details of the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function getShow($id) { $sindicato = Sindicato::findOrFail($id); $estados = $this->estadoModel->lists('sigla', 'id'); return view('sindicato.show', compact('estados'))->withSindicato($sindicato); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function postStore(StoreSindicatoRequest $request) { $input = $request->all(); Sindicato::create($input); Session::flash('flash_message', 'Sindicato adicionado com sucesso!'); return redirect()->back(); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function getEdit($id) { $sindicato = Sindicato::findOrFail($id); $estados = $this->estadoModel->lists('sigla', 'id'); return view('sindicato.edit', compact('estados'))->withSindicato($sindicato); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function putUpdate($id, StoreSindicatoRequest $request) { $sindicato = Sindicato::findOrFail($id); $input = $request->all(); $sindicato->fill($input)->save(); Session::flash('flash_message', 'Sindicato editado com sucesso!'); return redirect('Sindicato'); } /** * Show the form for removing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function getDelete($id) { $sindicato = Sindicato::findOrFail($id); return view('sindicato.delete')->withSindicato($sindicato); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $sindicato = Sindicato::findOrFail($id); $sindicato->delete(); Session::flash('flash_message', 'Sindicato excluído com sucesso!'); return redirect('Sindicato'); } /** * Process datatables ajax request. * * @return \Illuminate\Http\JsonResponse */ public function anyData() { $sindicato = Sindicato::leftJoin('cidade', 'cidade.id', '=', 'sindicato.cidade_id') ->leftJoin('estado', 'estado.id', '=', 'cidade.estado_id') ->select(['sindicato.id', 'sindicato.nome', 'sindicato.razao_social', 'sindicato.cnpj', 'sindicato.data_base', 'cidade.nome as cidade_nome', 'estado.sigla as estado_sigla', 'sindicato.email']); return Datatables::of($sindicato) ->removeColumn('id') ->addColumn('action', function ($sindicato) { return '<a href="Sindicato/show/'.$sindicato->id.'" class="btn btn-xs btn-info"><i class="glyphicon glyphicon-eye-open"></i> Detalhes</a> <a href="Sindicato/edit/'.$sindicato->id.'" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-edit"></i> Editar</a> <a href="Sindicato/delete/'.$sindicato->id.'" class="btn btn-xs btn-danger"><i class="glyphicon glyphicon-trash"></i> Excluir</a>'; }) ->make(true); } }
apache-2.0
mgraffg/simplegp
SimpleGP/utils.py
3721
# Copyright 2013 Mario Graff Guerrero # 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 numpy as np from multiprocessing import Process, cpu_count import time class Pool(object): def __init__(self, cpu=cpu_count()/2): self._cpu = cpu def run(self, func, lst_args): lst_args.reverse() process_lst = [] while len(lst_args): process_lst = filter(lambda x: x.is_alive(), process_lst) for i in range(len(process_lst), self._cpu): if len(lst_args) == 0: continue p = Process(target=func, args=lst_args.pop()) p.start() process_lst.append(p) time.sleep(0.1) class VerifyOutput(object): def __init__(self, max_error=16, forecast=True): self._max_error = max_error self.value = None self._forecast = forecast def get_value(self, ts, vs): self.compute(ts, vs) return self.value def get_value_ts(self, ts, vs): self.compute(ts, vs) return self.value_ts def ratio(self, ts, vs): self.compute(ts, vs) return (self.value + 1) / (self.value_ts + 1) def compute(self, ts, vs): from scipy import optimize if self._forecast: x = np.arange(ts.shape[0] + vs.shape[0]) else: x = np.arange(ts.shape[0]) x = np.concatenate((x, np.arange(vs.shape[0]))) lst = [] for func in [self.line, self.power, self.exp]: try: popt, pcov = optimize.curve_fit(func, x[:ts.shape[0]], ts) except RuntimeError: continue lst.append((self.n_mae(ts, func(x[:ts.shape[0]], *popt)), self.n_mae(np.concatenate((ts, func(x[ts.shape[0]:], *popt))), np.concatenate((ts, vs))))) if len(lst) == 0: self.value = np.inf self.value_ts = 0 else: r = lst[np.argmin(map(lambda x: x[0], lst))] self.value = r[1] self.value_ts = r[0] def verify(self, ts, vs): if ts.shape[0] + vs.shape[0] > 200: if vs.shape[0] > 190: raise Exception("At this moment the forecast cannot be\ greater than 190") cnt = 200 - vs.shape[0] ts = ts[-cnt:] r = self.ratio(ts, vs) if np.isnan(r): r = np.inf if r > self._max_error: return False return True @staticmethod def line(x, a, b): return a*x + b @staticmethod def exp(x, a): return np.exp(a*x) @staticmethod def power(x, a, b, c): return a*x**b + c @staticmethod def n_mae(a, b): try: m, c = np.linalg.solve([[a.min(), 1], [a.max(), 1]], [0, 1]) except np.linalg.LinAlgError: m = 1 c = 0 ap = a * m + c bp = b * m + c return np.fabs(ap - bp).mean()
apache-2.0
oxymoron/azb-finance
app/src/main/java/com/azubkov/azbfinance/model/Rate.java
1413
/* * Copyright 2014 Andrey Zubkov. 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.azubkov.azbfinance.model; import com.azubkov.azbfinance.Curr; import java.util.Date; /** * Created on 09.11.14. * * @author Andrey Zubkov */ public class Rate { private final Curr curr; private final Double value; private final Date date; public Rate(Curr curr, Double value, Date date) { this.curr = curr; this.value = value; this.date = date; } public Curr getCurr() { return curr; } public Double getValue() { return value; } public Date getDate() { return date; } @Override public String toString() { return "Rate{" + "curr=" + curr + ", value=" + value + ", date=" + date + '}'; } }
apache-2.0
emcvipr/dataservices-sdk-dotnet
AWSSDK/Amazon.IdentityManagement/Model/Internal/MarshallTransformations/GetGroupPolicyRequestMarshaller.cs
1951
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using Amazon.IdentityManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.IdentityManagement.Model.Internal.MarshallTransformations { /// <summary> /// Get Group Policy Request Marshaller /// </summary> public class GetGroupPolicyRequestMarshaller : IMarshaller<IRequest, GetGroupPolicyRequest> { public IRequest Marshall(GetGroupPolicyRequest getGroupPolicyRequest) { IRequest request = new DefaultRequest(getGroupPolicyRequest, "AmazonIdentityManagementService"); request.Parameters.Add("Action", "GetGroupPolicy"); request.Parameters.Add("Version", "2010-05-08"); if (getGroupPolicyRequest != null && getGroupPolicyRequest.IsSetGroupName()) { request.Parameters.Add("GroupName", StringUtils.FromString(getGroupPolicyRequest.GroupName)); } if (getGroupPolicyRequest != null && getGroupPolicyRequest.IsSetPolicyName()) { request.Parameters.Add("PolicyName", StringUtils.FromString(getGroupPolicyRequest.PolicyName)); } return request; } } }
apache-2.0
KAMP-Research/KAMP
bundles/Toometa/de.uka.ipd.sdq.dsexplore.qml.handling/src/de/uka/ipd/sdq/dsexplore/qml/pcm/datastructures/builder/UsageScenarioBasedSatisfactionConstraintBuilder.java
873
package de.uka.ipd.sdq.dsexplore.qml.pcm.datastructures.builder; import org.opt4j.core.Constraint.Direction; import org.opt4j.core.Objective; import org.palladiosimulator.pcm.usagemodel.UsageScenario; import de.uka.ipd.sdq.dsexplore.qml.pcm.datastructures.UsageScenarioBasedSatisfactionConstraint; public class UsageScenarioBasedSatisfactionConstraintBuilder extends SatisfactionConstraintBuilder{ private UsageScenario usageScenario; public UsageScenarioBasedSatisfactionConstraintBuilder( UsageScenario usageScenario) { this.usageScenario = usageScenario; } public UsageScenarioBasedSatisfactionConstraint createSatisfactionConstraint(String id, Direction direction, double limit, Objective objective) { return new UsageScenarioBasedSatisfactionConstraint(id+"_"+this.usageScenario.getId(), direction, limit, objective, this.usageScenario); } }
apache-2.0
lemire/StronglyUniversalStringHashing
include/treehash/generic-treehash.hh
2356
#ifndef GENERIC_TREEHASH #define GENERIC_TREEHASH #include "simple-treehash.hh" // This is like simple_generic_treehash, but works on generic tree // hashing primitives. Here, ALGO's constructor must use a logarithmic // amount of randomness and ALGO::treehash must return a pointer to // its result. template <template<typename> class ALGO, typename T, size_t N> uint64_t generic_treehash(const void *rvoid, const uint64_t *data, const size_t length) { if (T::alignmentRequired && (0 != (reinterpret_cast<size_t>(data) & (T::ATOM_SIZE - 1)))) { return generic_treehash<ALGO, typename T::Unaligned, N>(rvoid, data, length); } typedef typename Wide<T,N>::Atom Atom; static const size_t ATOM_WORD_SIZE = Wide<T,N>::ATOM_SIZE / sizeof(uint64_t); static_assert(sizeof(uint64_t) * ATOM_WORD_SIZE == Wide<T,N>::ATOM_SIZE, "sizeof(Atom) must be a multiple of sizeof(uint64_t)"); if (length < 2 * ATOM_WORD_SIZE) { return short_simple_treehash<2 * ATOM_WORD_SIZE>(rvoid, data, length); } const size_t atom_length = length / ATOM_WORD_SIZE; const Atom *atom_data = reinterpret_cast<const Atom *>(data); // We will reduce atom_length Atoms down to 1 Atom. This requires // ceiling(log2(atom_length)) levels of tree hashing. For x > 1, // __builtin_clzll(x) is 64 - ceiling(log2(x)), unless x is a power // of 2, in which case it is 65 - ceiling(log2(x)). subtracting 1 // from x only changes its __builtin_clzll if x is a power of 2. In // that case, it increases __builtin_clzll by 1. Thus, 64 - // __builtin_clzll(length-1) is ceiling(log2(length)). const size_t levels_count = 64 - __builtin_clzll(atom_length - 1); // The ALGO constructor moves rvoid forward past levels_count levels // of the randomness that T needs. ALGO<Wide<T,N> > hasher(&rvoid, levels_count); const Atom *tree_result = hasher.treehash(atom_data, atom_length); const size_t data_read = ATOM_WORD_SIZE * atom_length; typename T::Atom level[2*N]; const typename T::Atom *result1 = split_generic_simple_treehash_without_length<T, N>( &rvoid, level, *tree_result, &data[data_read], length - data_read); const uint64_t result2 = T::Reduce(&rvoid, *result1); return bigendian(*reinterpret_cast<const ui128 *>(rvoid), result2, length); } #endif // GENERIC_TREEHASH
apache-2.0
NuwanSameera/carbon-device-mgt-plugins
components/mobile-plugins/mobile-base-plugin/org.wso2.carbon.device.mgt.mobile.ui/src/main/resources/jaggeryapps/devicemgt/app/units/mdm.unit.policy.edit/edit.js
1006
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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. */ function onRequest(context) { var log = new Log("policy-view-edit-unit backend js"); log.debug("calling policy-view-edit-unit"); var userModule = require("/app/modules/user.js").userModule; context.roles = userModule.getRoles().content; context.users = userModule.getUsersByUsername().content; return context; }
apache-2.0
romain-intel/bcc
examples/cpp/RecordMySQLQuery.cc
2637
/* * RecordMySQLQuery Record MySQL queries by probing the alloc_query() function * in mysqld. For Linux, uses BCC, eBPF. Embedded C. * * Basic example of BCC and uprobes. * * Copyright (c) Facebook, Inc. * Licensed under the Apache License, Version 2.0 (the "License") */ #include <unistd.h> #include <algorithm> #include <cstdlib> #include <iostream> #include <string> #include "BPF.h" const std::string BPF_PROGRAM = R"( #include <linux/ptrace.h> struct query_probe_t { uint64_t ts; pid_t pid; char query[100]; }; BPF_HASH(queries, struct query_probe_t, int); int probe_mysql_query(struct pt_regs *ctx, void* thd, char* query, size_t len) { if (query) { struct query_probe_t key = {}; key.ts = bpf_ktime_get_ns(); key.pid = bpf_get_current_pid_tgid(); bpf_probe_read_str(&key.query, sizeof(key.query), query); int one = 1; queries.update(&key, &one); } return 0; } )"; const std::string ALLOC_QUERY_FUNC = "_Z11alloc_queryP3THDPKcj"; // Define the same struct to use in user space. struct query_probe_t { uint64_t ts; pid_t pid; char query[100]; }; int main(int argc, char** argv) { if (argc < 2) { std::cout << "USAGE: RecordMySQLQuery PATH_TO_MYSQLD [duration]" << std::endl; exit(1); } std::string mysql_path(argv[1]); std::cout << "Using mysqld path: " << mysql_path << std::endl; ebpf::BPF bpf; auto init_res = bpf.init(BPF_PROGRAM); if (init_res.code() != 0) { std::cerr << init_res.msg() << std::endl; return 1; } auto attach_res = bpf.attach_uprobe(mysql_path, ALLOC_QUERY_FUNC, "probe_mysql_query"); if (attach_res.code() != 0) { std::cerr << attach_res.msg() << std::endl; return 1; } int probe_time = 10; if (argc >= 3) probe_time = atoi(argv[2]); std::cout << "Probing for " << probe_time << " seconds" << std::endl; sleep(probe_time); auto table_handle = bpf.get_hash_table<query_probe_t, int>("queries"); auto table = table_handle.get_table_offline(); std::sort(table.begin(), table.end(), [](std::pair<query_probe_t, int> a, std::pair<query_probe_t, int> b) { return a.first.ts < b.first.ts; }); std::cout << table.size() << " queries recorded:" << std::endl; for (auto it : table) { std::cout << "Time: " << it.first.ts << " PID: " << it.first.pid << " Query: " << it.first.query << std::endl; } auto detach_res = bpf.detach_uprobe(mysql_path, ALLOC_QUERY_FUNC); if (detach_res.code() != 0) { std::cerr << detach_res.msg() << std::endl; return 1; } return 0; }
apache-2.0
akarnokd/various-experiments
src/hu/akarnokd/experiments/concurrent/AtomicResizableArray.java
6155
package hu.akarnokd.experiments.concurrent; import java.util.concurrent.atomic.*; import rx.functions.*; /** * A lock-free append-only resizable array with optimized first bank of 16 elements. */ public final class AtomicResizableArray { final AtomicReferenceArray<AtomicReferenceArray<Object>> arrays; final AtomicInteger count; public AtomicResizableArray() { arrays = new AtomicReferenceArray<>(27); count = new AtomicInteger(); } public AtomicResizableArray(int initialCapacity) { this(); // TODO count.set(0); // StoreLoad barrier } public void add(Object value) { if (value == null) { throw new NullPointerException("value != null required"); } int index = count.getAndIncrement(); AtomicReferenceArray<AtomicReferenceArray<Object>> as = arrays; AtomicReferenceArray<Object> array; if (index < 16) { array = as.get(0); if (array == null) { array = new AtomicReferenceArray<>(16); if (!as.compareAndSet(0, null, array)) { array = as.get(0); } } array.lazySet(index, value); } else { int bankRaw = 32 - Integer.numberOfLeadingZeros(index); int bankCorr = bankRaw - 4; int offset = (index & ((1 << bankRaw) - 1) >> 1); array = as.get(bankCorr); if (array == null) { int bankSize = 1 << (bankRaw - 1); try { array = new AtomicReferenceArray<>(bankSize); if (!as.compareAndSet(bankCorr, null, array)) { array = as.get(bankCorr); } } catch (OutOfMemoryError ex) { int retries = 128; while ((array = as.get(bankCorr)) == null && retries-- > 0); if (array == null) { throw ex; } } } array.lazySet(offset, value); } } public int size() { return count.get(); } public int getAndClear() { int c = count.get(); count.lazySet(0); return c; } /** * Returns the value at the specified index and spins * until the value becomes visible. * @param index * @return */ public Object get(int index) { AtomicReferenceArray<AtomicReferenceArray<Object>> as = arrays; AtomicReferenceArray<Object> array; if (index < 16) { array = as.get(0); if (array != null) { Object o = array.get(index); if (o != null) { return o; } } } else { int bankRaw = 32 - Integer.numberOfLeadingZeros(index); int bankCorr = bankRaw - 4; int offset = (index & ((1 << bankRaw) - 1) >> 1); array = as.get(bankCorr); if (array != null) { Object o = array.get(offset); if (o != null) { return o; } } } throw new IndexOutOfBoundsException(); } /** * Clears the counter to zero and the contents of the arrays to null. * Should not run concurrently with any add. */ public void lazyClear() { AtomicReferenceArray<AtomicReferenceArray<Object>> as = arrays; int n = as.length(); for (int i = 0; i < n; i++) { AtomicReferenceArray<Object> ara = as.get(i); if (ara != null) { int m = ara.length(); if (m < 128) { for (int j = 0; j < m; j += 4) { ara.lazySet(j, null); } } else { for (int j = 0; j < m; j += 4) { if (ara.get(j) == null) { break; } ara.lazySet(j, null); ara.lazySet(j + 1, null); ara.lazySet(j + 2, null); ara.lazySet(j + 3, null); } } } } count.lazySet(0); } /** * Deallocates all arrays and resets the counter to zero. * Should not run concurrently with any add. */ public void lazyReset() { AtomicReferenceArray<AtomicReferenceArray<Object>> as = arrays; int n = as.length(); for (int i = 0; i < n; i++) { as.lazySet(i, null); } count.lazySet(0); } public void lazyForEach(Action1<Object> action) { AtomicReferenceArray<AtomicReferenceArray<Object>> as = arrays; int n = as.length(); for (int i = 0; i < n; i++) { AtomicReferenceArray<Object> ara = as.get(i); if (ara != null) { int m = ara.length(); for (int j = 0; j < m; j++) { Object t1 = ara.get(j); if (t1 == null) { return; } action.call(t1); } } } } public interface Pred1<T> { boolean accept(T t); } public boolean lazyConsumeWhile(Pred1<Object> action) { AtomicReferenceArray<AtomicReferenceArray<Object>> as = arrays; int n = as.length(); for (int i = 0; i < n; i++) { AtomicReferenceArray<Object> ara = as.get(i); if (ara != null) { int m = ara.length(); for (int j = 0; j < m; j++) { Object t1 = ara.get(j); if (t1 == null) { return true; } boolean a = action.accept(t1); ara.lazySet(j, null); if (!a) { return false; } } } } return true; } }
apache-2.0
Blind-Striker/infinityfiction
Core/ServiceContracts/IKeyResourceService.cs
298
using CodeFiction.InfinityFiction.Core.CommonTypes; using CodeFiction.InfinityFiction.Core.Resources.Key; namespace CodeFiction.InfinityFiction.Core.ServiceContracts { public interface IKeyResourceService { KeyResource GetKeyResource(GameEnum gameEnum, string keyfilePath); } }
apache-2.0
Top-Q/jsystem
jsystem-core-projects/jsystemApp/src/main/java/jsystem/treeui/exceleditor/ExcelScenarioEditor.java
13787
/* * Created on 01/06/2006 * * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. */ package jsystem.treeui.exceleditor; public class ExcelScenarioEditor { /*implements ScenarioEditor // public void executeSenarioEditor(Scenario scenario) throws Exception { // File file = File.createTempFile(scenario.getName().replace( // '\\', '_').replace("/", "_"), ".xls"); // ExcelFile excel = ExcelFile.getInstance(file.getAbsolutePath(), false, // false); // // Vector<JTest> s = scenario.getRootTests(); // // String excelCommand = JSystemProperties.getInstance().getPreference( // FrameworkOptions.EXCEL_COMMAND); // // String[] excelCommands = null; // String[] commands = null; // // if (excelCommand != null) { // excelCommands = excelCommand.split(" "); // commands = new String[excelCommands.length + 1]; // System.arraycopy(excelCommands, 0, commands, 0, // excelCommands.length); // } // // String lastTestClass = null; // String lastTestMethod = null; // // if (s.size() == 0) { // excel.addRow(getHeader(null, null), ExcelFile.FORMAT_HEADER); // } else { // for (int i = 0; i < s.size(); i++) { // JTest jtest = s.elementAt(i); // if (jtest instanceof RunnerTest) { // if (jtest instanceof RunnerFixture) { // RunnerFixture fixture = (RunnerFixture) jtest; // Parameter[] parameters = fixture.getParameters(); // Properties otherFields = fixture.getAllXmlFields(); // // if (fixture.getClassName().equals(lastTestClass) // && fixture.getMethodName().equals( // lastTestMethod)) { // } else { // if (i != 0) { // excel.addRow(new String[] { "" }, // ExcelFile.FORMAT_1); // } // excel.addRow(getFixtureHeader(parameters, // otherFields), ExcelFile.FORMAT_HEADER); // } // excel.addRow(getRow(fixture.getClassName(),fixture.getMethodName(), parameters, // otherFields), ExcelFile.FORMAT_1); // // } else { // RunnerTest test = (RunnerTest) jtest; // Parameter[] parameters = test.getParameters(); // Properties otherFields = test.getAllXmlFields(); // // if (test.getClassName().equals(lastTestClass) // && test.getMethodName().equals(lastTestMethod)) { // } else { // if (i != 0) { // excel.addRow(new String[] { "" }, // ExcelFile.FORMAT_1); // } // excel.addRow(getHeader(parameters, otherFields), // ExcelFile.FORMAT_HEADER); // } // lastTestClass = test.getClassName(); // lastTestMethod = test.getMethodName(); // excel.addRow(getRow(test.getClassName(), test // .getMethodName(), parameters, otherFields), // ExcelFile.FORMAT_1); // } // } else if (jtest instanceof Scenario) { // Scenario sen = (Scenario) jtest; // excel.addRow(new String[] { "" }, ExcelFile.FORMAT_1); // excel.addRow(new String[] { "Scenario", // sen.getName() }, ExcelFile.FORMAT_HEADER); // } else { // ErrorPanel.showErrorDialog("Editing Scenario which includes flow control elements is currently not supported.", "Try editing a scenario without a flow element", ErrorLevel.Info); // return; // // } // } // } // // Command command = new Command(); // String osName = System.getProperty("os.name"); // // if (commands != null) { // commands[commands.length - 1] = file.getAbsolutePath(); // command.setCmd(commands); // } else { // command.setCmd(new String[] { "cmd.exe", "/C", // "\"" + file.getAbsolutePath() + "\"" }); // // if (osName.toLowerCase().startsWith("windows")) { // command.setCmd(new String[] { "cmd.exe", "/C", // "\"" + file.getAbsolutePath() + "\"" }); // } else { // // /** // * support for Linux // */ // String location = JSystemProperties.getInstance() // .getPreference( // FrameworkOptions.SCENARIO_EDITOR_LOCATION); // if (location == null) { // location = "/usr/bin/"; // } // String app = JSystemProperties.getInstance().getPreference( // FrameworkOptions.SCENARIO_EDITOR_APP); // // if (app == null) { // app = "oocalc"; // } // // command.setCmd(new String[] { location + app, // file.getAbsolutePath() }); // } // } // // try { // Execute.execute(command, true); //* create the excel file // } catch (Exception e) { // if (osName.toLowerCase().startsWith("linux")) { // String message = "Fail to open scenario editor. \n\n" // + "Notice that you are working in Linux environment.\n" // + "Try to update the scneario editor location and the \n" // + "scenario editor application name at the Jsystem.properties.\n" // + "For Example: scenario.editor.location = /usr/bin/ and \n" // + "scenario.editor.app = oocalc\n\n"; // // throw new Exception(message, e); // } else { // throw e; // } // } // // while (!FileUtils.winRename(file.getAbsolutePath(), file.getName())) { // Thread.sleep(2000); // } // // loadScenario(scenario, excel, JTest.fieldNum); // scenario.update(); // file.delete(); // } // // private String[] getHeader(Parameter[] parameters, Properties otherFields) { // int paramSize = 0; // int fieldsSize = 0; // if (parameters != null) { // paramSize = parameters.length; // } // // if (otherFields != null) { // fieldsSize = otherFields.size(); // } // // String[] header = new String[2 + fieldsSize + paramSize]; // // header[0] = "Class"; // header[1] = "Method"; // // if (fieldsSize > 0) { // String key; // Enumeration<Object> fieldsEnum = otherFields.keys(); // for (int i = 2; i < 2 + fieldsSize; i++) { // key = (String) fieldsEnum.nextElement(); // header[i] = key; // } // } // // /** // * sort parameter array before adding to excel row. // */ // if (parameters != null) { // Arrays.sort(parameters, Parameter.ParameterNameComparator); // } // // int n = fieldsSize + 2; // for (int i = n; i < n + paramSize; i++) { // header[i] = parameters[i - n].getName(); // } // return header; // } // /** // * returns a header for a fixture in the scenario // * @param parameters // * @param otherFields // * @return // */ // private String[] getFixtureHeader(Parameter[] parameters, Properties otherFields) { // int paramSize = 0; // int fieldsSize = 0; // if (parameters != null) { // paramSize = parameters.length; // } // // if (otherFields != null) { // fieldsSize = otherFields.size(); // } // // String[] header = new String[2 + fieldsSize + paramSize]; // // header[0] = "Fixture"; // header[1] = "Method"; // // if (fieldsSize > 0) { // String key; // Enumeration<Object> fieldsEnum = otherFields.keys(); // for (int i = 2; i < 2 + fieldsSize; i++) { // key = (String) fieldsEnum.nextElement(); // header[i] = key; // } // } // // /** // * sort parameter array before adding to excel row. // */ // if (parameters != null) { // Arrays.sort(parameters, Parameter.ParameterNameComparator); // } // // int n = fieldsSize + 2; // for (int i = n; i < n + paramSize; i++) { // header[i] = parameters[i - n].getName(); // } // return header; // } // // // private void loadScenario(Scenario scenario, ExcelFile excel, int fieldNum) // throws Exception { // // scenario.cleanAll(); // HSSFSheet sheet = excel.getSheet(); // String[] keys = null; // /** // * in order to store the header row // */ // String lastClassName=""; // for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { // HSSFRow row = sheet.getRow(i); // if (row == null) { // continue; // } // // String className = getCellValue(row.getCell((short) 0)); // String methodName = getCellValue(row.getCell((short) 1)); // // if (className == null || className.equals("")) { // keys = null; // continue; // } // // if (methodName == null || methodName.equals("")) { // keys = null; // continue; // } // // if (className.equals("Class")) { // found header // // read keys // lastClassName=className; // int rowSize = row.getLastCellNum() + 1; // if (rowSize < 2) { // rowSize = 2; // } // // keys = new String[rowSize - 2]; // for (int j = 2; j < rowSize; j++) { // keys[j - 2] = getCellValue(row.getCell((short) j)); // } // } else if (className.equals("Scenario")) { // lastClassName=className; // Scenario scen = ScenariosManager.getInstance().getScenario( // methodName); // ScenariosManager.getInstance().setCurrentScenario(scen); // scenario.addTest(scen); // ScenariosManager.getInstance().setCurrentScenario(scenario); // } else if (className.equals("Fixture")) { // lastClassName=className; // int rowSize = row.getLastCellNum() + 1; // if (rowSize < 1) { // rowSize = 1; // } // // keys = new String[rowSize - 1]; // for (int j = 1; j < rowSize; j++) { // keys[j - 1] = getCellValue(row.getCell((short) (j+1))); // } // } else { // read values // if (keys == null) { // continue; // } // if (lastClassName.equalsIgnoreCase("fixture")) { // RunnerFixture rf = new RunnerFixture (className); // if (keys.length > 0) { // Properties fields = new Properties(); // for (int j = 0; j < fieldNum && keys.length > j; j++) { // String value = getCellValue(row // .getCell((short) (j + 2))); // if (value == null || keys[j] == null) { // continue; // } // fields.setProperty(keys[j], value); // } // rf.setXmlFields(fields); // Properties p = new Properties(); // for (int j = 0; j < keys.length; j++) { // String value = getCellValue(row // .getCell((short) (j + 2))); // if (value == null || keys[j] == null) { // continue; // } // try { // Double.parseDouble(value); // if (value.endsWith(".0")) { // value = value.substring(0, // value.length() - 2); // } // } catch (Throwable t) { // // } // p.setProperty(keys[j], value); // } // rf.setProperties(p); // } // scenario.addTest(rf); // } else { // RunnerTest rt = new RunnerTest(className,methodName); // if (keys.length > 0) { // Properties fields = new Properties(); // for (int j = 0; j < fieldNum && keys.length > j; j++) { // String value = getCellValue(row // .getCell((short) (j + 2))); // if (value == null || keys[j] == null) { // continue; // } // fields.setProperty(keys[j], value); // } // rt.setXmlFields(fields); // Properties p = new Properties(); // for (int j = 0; j < keys.length; j++) { // String value = getCellValue(row // .getCell((short) (j + 2))); // if (value == null || keys[j] == null) { // continue; // } // try { // Double.parseDouble(value); // if (value.endsWith(".0")) { // value = value.substring(0, // value.length() - 2); // } // } catch (Throwable t) { // // } // p.setProperty(keys[j], value); // } // rt.setProperties(p); // } // scenario.addTest(rt); // } // } // } // // Scenario s = ScenariosManager.getInstance().getScenario( // scenario.getName()); // ScenariosManager.getInstance().setCurrentScenario(s); // } // // private static String getCellValue(HSSFCell cell) { // if (cell == null) { // return null; // } // // String cellValue = null; // // if (cell != null) { // switch (cell.getCellType()) { // case HSSFCell.CELL_TYPE_NUMERIC: // cellValue = Double.toString(cell.getNumericCellValue()); // break; // case HSSFCell.CELL_TYPE_STRING: // cellValue = cell.getRichStringCellValue().getString(); // break; // case HSSFCell.CELL_TYPE_FORMULA: // cellValue = Double.toString(cell.getNumericCellValue()); // break; // case HSSFCell.CELL_TYPE_BLANK: // cellValue = ""; // break; // case HSSFCell.CELL_TYPE_BOOLEAN: // cellValue = Boolean.toString(cell.getBooleanCellValue()); // break; // default: // System.out.println("Unsupported cell type: " // + cell.getCellType()); // } // } // return cellValue; // } // // /** // * returns an Object Array to be writen as Excel row. // * // * @param className // * test class name // * @param methodName // * test method name // * @param parameters // * Parameter[] of test parameters // * @return // */ // private Object[] getRow(String className, String methodName, // Parameter[] parameters, Properties otherFields) { // int paramSize = 0; // int fieldsSize = 0; // if (parameters != null) { // paramSize = parameters.length; // } // // if (otherFields != null) { // fieldsSize = otherFields.size(); // } // // /** // * init row (Class Name, Method name, fields , params) // */ // Object[] row = new Object[2 + fieldsSize + paramSize]; // // row[0] = className; // row[1] = methodName; // // if (fieldsSize > 0) { // String key; // Enumeration<Object> fieldsEnum = otherFields.keys(); // for (int i = 2; i < 2 + fieldsSize; i++) { // key = (String) fieldsEnum.nextElement(); // row[i] = otherFields.getProperty(key); // } // } // // /** // * sort parameter array before adding to excel row. // */ // if (parameters != null) { // Arrays.sort(parameters, Parameter.ParameterNameComparator); // } // // /** // * add all params // */ // int n = fieldsSize + 2; // for (int i = n; i < n + paramSize; i++) { // // Object o = parameters[i - n].getValue(); // // if (o == null) { // o = ""; // } // // try { // Double d = new Double(o.toString()); // row[i] = d; // } catch (Throwable ex) { // row[i] = o.toString(); // } // } // // return row; // } }
apache-2.0
roebi/BehaviorDrivenDevelopmentBDD
src/test/java/pageobject/SearchResultsPage.java
544
package pageobject; import net.serenitybdd.core.pages.PageObject; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.List; import java.util.stream.Collectors; /** * @author Roebi */ public class SearchResultsPage extends PageObject { @FindBy(css=".listing-card") List<WebElement> listingCards; public List<String> getResultTitles() { return listingCards.stream() .map(element -> element.getText()) .collect(Collectors.toList()); } }
apache-2.0
red6/serenity-js
packages/serenity-js/src/serenity-protractor/screenplay/interactions/clear.ts
527
import { Interaction, UsesAbilities } from '../../../serenity/screenplay'; import { BrowseTheWeb } from '../abilities/browse_the_web'; import { Target } from '../ui/target'; export class Clear implements Interaction { static theValueOf = (field: Target): Interaction => new Clear(field); performAs(actor: UsesAbilities): PromiseLike<void> { return BrowseTheWeb.as(actor).locate(this.target).clear(); } constructor(private target: Target) { } toString = () => `{0} clears ${this.target}`; }
apache-2.0
android-art-intel/Nougat
art-extension/opttests/src/OptimizationTests/ShortMethodsInliningNonVirtualInvokes/InvokeStaticRangeIShort_001/Main.java
1395
/* * Copyright (C) 2016 Intel Corporation * * 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 OptimizationTests.ShortMethodsInliningNonVirtualInvokes.InvokeStaticRangeIShort_001; class Main { final static int iterations = 10; public static void main(String[] args) { Test test = new Test(); short nextThingy = 0; short t1 = -32768; short t2 = -32767; short t3 = -32766; short t4 = -32765; short t5 = -32764; short t6 = -32763; System.out.println("Initial nextThingy value is " + nextThingy); for(int i = 0; i < iterations; i++) { nextThingy = (short)(Test.getThingies(test, t1, t2, t3, t4, t5, t6) + 1); Test.setThingies(test, nextThingy, t1, t2, t3, t4, t5, t6); } System.out.println("Final nextThingy value is " + nextThingy); } }
apache-2.0
indashnet/InDashNet.Open.UN2000
android/cts/tests/src/android/renderscript/cts/asinh_f32_relaxed.rs
46
#include "asinh_f32.rs" #pragma rs_fp_relaxed
apache-2.0
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/spi/RoundedMoneyProducer.java
2218
/* Copyright (c) 2012, 2014, Credit Suisse (Anatole Tresch), Werner Keil and others by the @author tag. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.javamoney.moneta.spi; import java.util.Objects; import javax.money.CurrencyUnit; import javax.money.MonetaryAmount; import javax.money.MonetaryOperator; import org.javamoney.moneta.RoundedMoney; import org.javamoney.moneta.function.MonetaryOperators; /** * The implementation of {@link MonetaryAmountProducer} that creates {@link MonetaryAmount} * using {@link RoundedMoney} using the {@link MonetaryOperator} as rounding operator * @see RoundedMoneyProducer#RoundedMoneyProducer(MonetaryOperator) * @author Otavio Santana */ public final class RoundedMoneyProducer implements MonetaryAmountProducer { private final MonetaryOperator operator; /** * Creates this producer using this operator * as rounding operator in all MonetaryAmount produced. * @param operator the rounding, not null * @throws NullPointerException if operator is null */ public RoundedMoneyProducer(MonetaryOperator operator) { this.operator = Objects.requireNonNull(operator); } /** * Returns the {@link MonetaryAmountProducer} that creates {@link MonetaryAmount} * using the {@link RoundedMoney} implementation using {@link MonetaryOperators#rounding()} * as rounding operator * @see RoundedMoneyProducer */ public RoundedMoneyProducer() { this.operator = MonetaryOperators.rounding(); } @Override public MonetaryAmount create(CurrencyUnit currency, Number number) { return RoundedMoney.of(Objects.requireNonNull(number), Objects.requireNonNull(currency), operator); } public MonetaryOperator getOperator() { return operator; } }
apache-2.0
garethr/garethr-kubernetes
lib/puppet/provider/kubernetes_http_get_action/swagger.rb
2173
# This file is automatically generated by puppet-swagger-generator and # any manual changes are likely to be clobbered when the files # are regenerated. require_relative '../../../puppet_x/puppetlabs/kubernetes/provider' Puppet::Type.type(:kubernetes_http_get_action).provide(:swagger, :parent => PuppetX::Puppetlabs::Kubernetes::Provider) do mk_resource_methods def self.instance_to_hash(instance) { ensure: :present, name: instance.metadata.name, path: instance.path.respond_to?(:to_hash) ? instance.path.to_hash : instance.path, port: instance.port.respond_to?(:to_hash) ? instance.port.to_hash : instance.port, host: instance.host.respond_to?(:to_hash) ? instance.host.to_hash : instance.host, scheme: instance.scheme.respond_to?(:to_hash) ? instance.scheme.to_hash : instance.scheme, http_headers: instance.httpHeaders.respond_to?(:to_hash) ? instance.httpHeaders.to_hash : instance.httpHeaders, object: instance, } end def create Puppet.info("Creating kubernetes_http_get_action #{name}") create_instance_of('http_get_action', name, build_params) end def flush unless @property_hash.empty? unless resource[:ensure] == :absent flush_instance_of('http_get_action', name, @property_hash[:object], build_params) end end end def destroy Puppet.info("Deleting kubernetes_http_get_action #{name}") destroy_instance_of('http_get_action', name) @property_hash[:ensure] = :absent end private def self.list_instances list_instances_of('http_get_action') end def build_params params = { path: resource[:path], port: resource[:port], host: resource[:host], scheme: resource[:scheme], httpHeaders: resource[:http_headers], } params.delete_if { |key, value| value.nil? } params end end
apache-2.0
boneman1231/org.apache.felix
trunk/framework/src/main/java/org/apache/felix/framework/util/StringMap.java
3133
/* * 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.felix.framework.util; import java.util.*; /** * Simple utility class that creates a map for string-based keys. * This map can be set to use case-sensitive or case-insensitive * comparison when searching for the key. Any keys put into this * map will be converted to a <tt>String</tt> using the * <tt>toString()</tt> method, since it is only intended to * compare strings. **/ public class StringMap implements Map { private TreeMap m_map; public StringMap() { this(true); } public StringMap(boolean caseSensitive) { m_map = new TreeMap(new StringComparator(caseSensitive)); } public StringMap(Map map, boolean caseSensitive) { this(caseSensitive); putAll(map); } public boolean isCaseSensitive() { return ((StringComparator) m_map.comparator()).isCaseSensitive(); } public void setCaseSensitive(boolean b) { if (isCaseSensitive() != b) { TreeMap map = new TreeMap(new StringComparator(b)); map.putAll(m_map); m_map = map; } } public int size() { return m_map.size(); } public boolean isEmpty() { return m_map.isEmpty(); } public boolean containsKey(Object arg0) { return m_map.containsKey(arg0); } public boolean containsValue(Object arg0) { return m_map.containsValue(arg0); } public Object get(Object arg0) { return m_map.get(arg0); } public Object put(Object key, Object value) { return m_map.put(key.toString(), value); } public void putAll(Map map) { for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); put(entry.getKey(), entry.getValue()); } } public Object remove(Object arg0) { return m_map.remove(arg0); } public void clear() { m_map.clear(); } public Set keySet() { return m_map.keySet(); } public Collection values() { return m_map.values(); } public Set entrySet() { return m_map.entrySet(); } public String toString() { return m_map.toString(); } }
apache-2.0
Hai-Lin/chef
cookbooks/postgresql91/recipes/client.rb
82
case node[:platform] when "ubuntu" include_recipe "postgresql::client_debian" end
apache-2.0
KITSABHIJIT/Ihalkhata-WebService
IhalkhataWebService/src/com/exp/cemk/controller/GridExpenditureProcessor.java
4982
package com.exp.cemk.controller; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import test.Test; import domainmodel.Expenditure; public class GridExpenditureProcessor { private static GridExpenditureProcessor _instance = new GridExpenditureProcessor(); private static final Logger logger = Logger.getLogger(GridExpenditureProcessor.class); public static GridExpenditureProcessor getInstance() { //log.debug("AutoFillDemo::getInstance "); return _instance; } public JSONObject getGridExpenditureData(int start,int limit,String month,String year,String endmonth,String endYear,String type, String groupId) { logger.info("Controller-->getGridExpenditureData-->Controller-->getSelectedExpenditureGrid"); JSONObject JSONExpenditure= new JSONObject(); JSONExpenditure = getSelectedExpenditureGrid(start,limit,month,year,endmonth,endYear,type,groupId); return JSONExpenditure; } public JSONObject getSelectedExpenditureGrid(int start,int limit,String month,String year,String endmonth,String endYear,String type, String groupId) { int reccnt = 0; //Connection con = null; //Statement stmt = null; //ResultSet rs = null; int end = start + limit; logger.info("Controller-->getSelectedExpenditureGrid-->Spring Data Access-->getExpenditureData"); try { JSONObject jsonItems = null; JSONObject jsonObjectTotalCount = null; JSONArray arrayObj = new JSONArray(); jsonItems = new JSONObject(); jsonObjectTotalCount= new JSONObject(); List<Expenditure> expenditureList = new ArrayList<Expenditure>(); Test expenditureData=new Test(); expenditureList=expenditureData.getExpenditureData(month,year,endmonth,endYear,type,groupId); for(int i=0;i<expenditureList.size();i++){ jsonItems.put("userId",expenditureList.get(i).getUserId()); jsonItems.put("amount",(expenditureList.get(i).getAmount()).toString()); reccnt = reccnt + 1; arrayObj.add(jsonItems); } JSONArray arrayObjFinal = new JSONArray(); for(int p=start;p<end;p++){ if(p<=arrayObj.size()-1){ arrayObjFinal.add(arrayObj.get(p)) ; } } jsonObjectTotalCount.put("totalCount",reccnt); jsonObjectTotalCount.put("items",arrayObjFinal); // System.out.println("Data found in ID Query = "+checkFlag); //logger.debug("Controller-->getSelectedExpenditureGrid-->"+jsonObjectTotalCount.toString()); return jsonObjectTotalCount; } catch (Exception e) { // TODO Auto-generated catch block //log.debug("getClientsCache Query Is q1 [ ] Failed"); e.printStackTrace(); } finally { // BaseDBUtil.closeDbResources(con, stmt, rs); } return null; } public JSONArray getGridPieExpenditureData(String month,String year,String endmonth,String endYear,String type,String groupId){ logger.info("Controller-->getGridPieExpenditureData-->Spring Data Access-->getExpenditureData"); try { JSONArray arrayObj = new JSONArray(); List<Expenditure> expenditureList = new ArrayList<Expenditure>(); Test expenditureData=new Test(); expenditureList=expenditureData.getExpenditureData(month,year,endmonth,endYear,type,groupId); for(int i=0;i<expenditureList.size();i++){ JSONObject jsonItems=new JSONObject(); jsonItems.put("userId",expenditureList.get(i).getUserId()); jsonItems.put("amount",(expenditureList.get(i).getAmount()).toString()); arrayObj.add(jsonItems); } //logger.debug("Controller-->getGridPieExpenditureData-->"+arrayObj.toString()); return arrayObj; } catch (Exception e) { // TODO Auto-generated catch block //log.debug("getClientsCache Query Is q1 [ ] Failed"); e.printStackTrace(); return null; } finally { // BaseDBUtil.closeDbResources(con, stmt, rs); } } public JSONArray getExpenditureData(String month,String year,String endmonth,String endYear,String type,String groupId,String userName){ logger.info("Controller-->getExpenditureData-->Spring Data Access-->getExpenditureData"); try { JSONArray arrayObj = new JSONArray(); List<Expenditure> expenditureList = new ArrayList<Expenditure>(); Test expenditureData=new Test(); expenditureList=expenditureData.getExpenditureData(month,year,endmonth,endYear,type,groupId); for(int i=0;i<expenditureList.size();i++){ if(userName.equals(expenditureList.get(i).getUserId())){ JSONObject jsonItems=new JSONObject(); jsonItems.put("amount",(expenditureList.get(i).getAmount()).toString()); arrayObj.add(jsonItems); } } //logger.debug("Controller-->getExpenditureData-->"+arrayObj.toString()); return arrayObj; } catch (Exception e) { // TODO Auto-generated catch block //log.debug("getClientsCache Query Is q1 [ ] Failed"); e.printStackTrace(); return null; } finally { // BaseDBUtil.closeDbResources(con, stmt, rs); } } }
apache-2.0
Gadreel/dcraft
dcraft.core/src/main/java/dcraft/db/doc/QueryRequest.java
907
/* ************************************************************************ # # designCraft.io # # http://designcraft.io/ # # Copyright: # Copyright 2012 eTimeline, LLC. All rights reserved. # # License: # See the license.txt file in the project's top-level directory for details. # # Authors: # * Andy White # ************************************************************************ */ package dcraft.db.doc; import dcraft.struct.RecordStruct; import dcraft.util.StringUtil; public class QueryRequest extends dcraft.db.DataRequest { public QueryRequest(String id) { this(id, null); } public QueryRequest(String id, String path) { super("dcQueryDocument"); RecordStruct params = new RecordStruct(); params.setField("Id", id); if (StringUtil.isNotEmpty(path)) params.setField("Path", path); this.withParams(params); } }
apache-2.0
lauvetech/lauve-tv
Js/Plugins/jquery.makemecentre.js
5349
/*! @package makemecenter - jQuery Position Elements Centers Vertically and Horizontally Plugin @version version: 0.1.0 @url https://github.com/tenbullstech/jquery-make-me-center @documentation Examples and Documentation - https://github.com/tenbullstech/jquery-make-me-center @contributors https://github.com/tenbullstech/jquery-make-me-center/graphs/contributors @license Licensed under the MIT licenses: http://www.opensource.org/licenses/mit-license.php @date Friday, May 22, 2015 11:36 AM @author Aman Bansal ** If you found bug, please contact me via email <tenbulls007@gmail.com> */ (function($){ $.fn.makemecenter = function(options) { var settings = $.extend({ position : "absolute", horizontal : true, vertical : true, parentRelative : window, complete : null, marginLeft : null, marginRight : null, marginTop : null, paddingLeft : null, paddingRight : null, paddingTop : null, paddingBottom : null, is_onload : true, is_onresize : true, is_ondatachange : true, // center it on text data or height change is_animate : false, },options) var self = this; $.fn.makemecenter.destroy = function() { return self.each(function(){ $(window).off('resize.makemecenter'); }); } var adjustposition = function (elem) { var parent = $(settings.parentRelative); var parentHeight = $(parent).innerHeight(); var parentWidth = $(parent).innerWidth(); parent.css({ position : "relative" }); // Clear Element Margin and Padding to calculate actual dimensions elem.css({ margin : "", padding : "", // display : "block", }); elem.css({ position : settings.position, "margin-left" : settings.marginLeft, "margin-right" : settings.marginRight, "margin-top" : settings.marginTop, "padding-left" : settings.paddingLeft, "padding-right" : settings.paddingRight, "padding-top" : settings.paddingTop, "padding-bottom" : settings.paddingBottom, }); var contentWidth = elem.width(); // Getting applied element width before any margin and padding //console.log(contentWidth); // Adjust Horizonal Element Position if (settings.horizontal) { var set_left = (parentWidth - contentWidth- settings.marginLeft - settings.marginRight - settings.paddingLeft - settings.paddingRight) / 2; // if set_left is negative it means element is greater than or equal to parent width so set it from left 0 and prevent it from going -ve if (set_left <= 0) { set_left = 0; } elem.css({ left : set_left, }); } // Adjust Vertical Element Position var contentHeight = elem.height(); // Getting element Height after Width , margin and padding becasuse they affect height so getting height only after applying these prop if (settings.vertical) { // Padding does count on height for eg. if we have height = 200 and padding 10px top and bottom but height will count 200 always not 220 var set_top = (parentHeight - contentHeight - settings.marginTop - settings.paddingTop - settings.paddingBottom) / 2; // if set_top is negative it means element is greater than or equal to parent width so set it from top 0 and prevent it from going -ve if (set_top <= 0) { set_top = 0; } var vertical_options = { top : set_top, "margin-bottom" : 0, } // if is_animate is true then position element using animation effect if (settings.is_animate) { elem.animate(vertical_options); } else { elem.css(vertical_options); } } if ($.isFunction(settings.complete)) { return settings.complete.call(elem); } } function makeitcenter(self){ // console.log(self); // if (undefined==self) { // return false; // } return self.each(function(){ var $this = $(this); // store the object adjustposition($this); }); } function detect_datachange(self){ return self.each(function(){ var $this = $(this); // store the object // create an observer instance var observer = new MutationObserver(function(mutations) { //adjustposition($this); mutations.forEach(function(mutation) { console.log(mutation); // console.log('old', mutation.oldValue); // var props = mutation.oldValue.replace(/ /g, '').split(':'); // console.log(props); // console.log('new', mutation.target.style.cssText); if (mutation.type === 'attributes' && mutation.attributeName=="style") { console.log("mutation"); } }); }); // configuration of the observer: var config = { attributes: true, attributeFilter: ["style"], attributeOldValue: true, childList: true, characterData: true , subtree : true}; // pass in the target node, as well as the observer options observer.observe(this, config); }); } // Default Execution on Initiation makeitcenter(self); // if (settings.is_onload) { // detect_datachange(self); // } if (settings.is_onload) { $(window).load(function () { makeitcenter(self); //window.dispatchEvent(evt); }); } if (settings.is_onresize) { $(window).on("resize.makemecenter",function() { makeitcenter(self); }); } } }(jQuery))
apache-2.0
teem2/dreem2
core/promisepolyfill.js
6780
/* Copyright 2015-2016 Teem2 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 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. */ /** Copyright (c) 2014 Taylor Hakes Copyright (c) 2014 Forbes Lindesay 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. */ define(function(require, exports, module) { module.exports = Promise; // Use polyfill for setImmediate for performance gains var asap = Promise.immediateFn || (typeof setImmediate === 'function' && setImmediate) || function(fn) {setTimeout(fn, 1);}; // Polyfill for Function.prototype.bind function bind(fn, thisArg) { return function() { fn.apply(thisArg, arguments); } } var isArray = Array.isArray || function(value) {return Object.prototype.toString.call(value) === "[object Array]"}; function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); if (typeof fn !== 'function') throw new TypeError('not a function'); this._state = null; this._value = null; this._deferreds = [] doResolve(fn, bind(resolve, this), bind(reject, this)); } function handle(deferred) { var me = this; if (this._state === null) { this._deferreds.push(deferred); return; } asap(function() { var cb = me._state ? deferred.onFulfilled : deferred.onRejected; if (cb === null) { (me._state ? deferred.resolve : deferred.reject)(me._value); return; } var ret; try { ret = cb(me._value); } catch (e) { deferred.reject(e); return; } deferred.resolve(ret); }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.'); if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then; if (typeof then === 'function') { doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this)); return; } } this._state = true; this._value = newValue; finale.call(this); } catch (e) { reject.call(this, e); } } function reject(newValue) { this._state = false; this._value = newValue; finale.call(this); } function finale() { for (var i = 0, len = this._deferreds.length; i < len; i++) { handle.call(this, this._deferreds[i]); } this._deferreds = null; } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.resolve = resolve; this.reject = reject; } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return; done = true; onFulfilled(value); }, function (reason) { if (done) return; done = true; onRejected(reason); }) } catch (ex) { if (done) return; done = true; onRejected(ex); } } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); }; Promise.prototype.then = function(onFulfilled, onRejected) { var me = this; return new Promise(function(resolve, reject) { handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject)); }) }; Promise.all = function () { var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments); return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]); var remaining = args.length; function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call(val, function (val) {res(i, val);}, reject); return; } } args[i] = val; if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); }; Promise.resolve = function (value) { if (value && typeof value === 'object' && value.constructor === Promise) { return value; } return new Promise(function (resolve) { resolve(value); }); }; Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); }; Promise.race = function (values) { return new Promise(function (resolve, reject) { for (var i = 0, len = values.length; i < len; i++) { values[i].then(resolve, reject); } }); }; if (typeof module !== 'undefined' && module.exports) { module.exports = Promise; } else if (!root.Promise) { root.Promise = Promise; } })
apache-2.0
openstack-atlas/atlas-lb
core-api/core-common-api/src/main/java/org/openstack/atlas/api/validation/expectation/ExpectationTarget.java
3867
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.openstack.atlas.api.validation.expectation; import org.openstack.atlas.api.validation.exception.ValidationChainExecutionException; import org.openstack.atlas.api.validation.result.ExpectationResult; import org.openstack.atlas.api.validation.result.ExpectationResultBuilder; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class ExpectationTarget<T> { private final Method targetMethod; private final List<Expectation> expectations; public ExpectationTarget(Method targetMethod) { this.targetMethod = targetMethod; this.expectations = new LinkedList<Expectation>(); } public synchronized void addExpectation(Expectation ex) { expectations.add(ex); } public synchronized SelfValidationResult isSatisfied() { final StringBuilder strBuff = new StringBuilder(); boolean valid = true; Collections.sort(expectations); for (Expectation ex : expectations) { if (!ex.hasVerifierSet()) { strBuff.append("\nIncomplete: ").append("Expectation #").append(ex.getExpectationId()).append(" - ").append(getTargetName()); valid = false; } } return new SelfValidationResult(strBuff, valid); } public String getTargetName() { return targetMethod == null ? "Root Object" : targetMethod.getName(); } public boolean targets(Method target) { return target == targetMethod; } public synchronized List<ExpectationResult> validate(T target, Object context) { //TODO: Inline? Too complex? final Object objectToValidateAgainst = targetMethod == null ? target : invokeMethod(targetMethod, target); return validateObject(expectations, objectToValidateAgainst, context); } private List<ExpectationResult> validateObject(List<Expectation> expectations, Object objectBeingValidated, Object context) throws ValidationChainExecutionException { final ExpectationResultBuilder resultBuilder = new ExpectationResultBuilder(getTargetName()); final List<ExpectationResult> gatheredResults = new LinkedList<ExpectationResult>(); for (Expectation expectation : expectations) { final List<ValidationResult> validationResults = expectation.validate(objectBeingValidated, context); for (ValidationResult validationResult : validationResults) { if (!validationResult.expectationWasMet()) { resultBuilder.setMessage(validationResult.getMessage()); resultBuilder.setPassed(false); gatheredResults.add(resultBuilder.toResult()); } } } return gatheredResults; } private Object invokeMethod(Method m, T object) throws ValidationChainExecutionException { try { return m.invoke(object); } catch (IllegalAccessException iae) { throw new ValidationChainExecutionException("Fatal exception encountered during validation. Please verify your JVM security model.", iae); } catch (IllegalArgumentException iae) { throw new ValidationChainExecutionException("This shouldn't happen but if it does, you lose. Please report this as a bug.", iae); } catch (InvocationTargetException ite) { final Throwable t = ite.getTargetException(); throw new ValidationChainExecutionException("Exception \"" + t.getMessage() + "\" encountered during validation chain execution. Pump cause for more details.", t); } } }
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/PcodeFieldLocation.java
2596
/* ### * IP: GHIDRA * * 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 ghidra.program.util; import java.util.*; import ghidra.framework.options.SaveState; import ghidra.program.model.address.Address; import ghidra.program.model.listing.Program; public class PcodeFieldLocation extends ProgramLocation { private List<String> pcodeStrings; public PcodeFieldLocation(Program program, Address addr, List<String> pcodeStrings, int row, int charOffset) { super(program, addr, row, 0, charOffset); this.pcodeStrings = pcodeStrings; } /** * Get the row within a group of pcode strings. */ public PcodeFieldLocation() { // for deserialization } public List<String> getPcodeStrings() { return Collections.unmodifiableList(pcodeStrings); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((pcodeStrings == null) ? 0 : pcodeStrings.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; PcodeFieldLocation other = (PcodeFieldLocation) obj; if (pcodeStrings == null) { if (other.pcodeStrings != null) return false; } else if (!pcodeStrings.equals(other.pcodeStrings)) return false; return true; } @Override public void saveState(SaveState obj) { super.saveState(obj); obj.putStrings("_PCODE_STRINGS", pcodeStrings.toArray(new String[pcodeStrings.size()])); } @Override public void restoreState(Program p, SaveState obj) { super.restoreState(p, obj); String[] strings = obj.getStrings("_PCODE_STRINGS", new String[0]); pcodeStrings = new ArrayList<String>(strings.length); for (String string : strings) { pcodeStrings.add(string); } } @Override public String toString() { return super.toString() + ", Pcode sample: " + getPcodeSample(); } private String getPcodeSample() { if (pcodeStrings.size() == 0) { return "<no pcode>"; } return pcodeStrings.get(0); } }
apache-2.0
yystju/tdcc_demo
routes/hello.js
5380
(function(module) { var express = require('express'); var https = require("https"); var fs = require("fs"); var router = express.Router(); var hello = hello || {}; hello.__tokenExpireDate__ = null; hello.__token__ = null; var config = JSON.parse(fs.readFileSync(__dirname + '/../config.json')); if(config) { hello.appid = config.appid; hello.secret = config.secret; } console.log('hello.appid : ' + hello.appid); console.log('hello.secret : ' + hello.secret); //'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET'; var getWeixinToken = function() { return new Promise(function(resolve, reject) { var now = new Date(); if(hello.__tokenExpireDate__ && (hello.__tokenExpireDate__ - now) > 30000 && hello.__token__) { resolve(hello.__token__, hello.__tokenExpireDate__); } else { var options = { host: 'api.weixin.qq.com', port: 443, path: '/cgi-bin/token?grant_type=client_credential&appid='+hello.appid+'&secret='+hello.secret, method: 'GET', headers: { 'Content-Type': 'application/json' } }; var req = https.request(options, function(res) { var output = ''; //console.log(options.host + ':' + res.statusCode); res.setEncoding('utf8'); res.on('data', function (chunk) { output += chunk; }); res.on('end', function() { var obj = JSON.parse(output); var token = obj['access_token']; var expireDate = new Date(new Date().getTime() + obj['expires_in']); hello.__token__ = token; hello.__tokenExpireDate__ = expireDate; if(token) { resolve(token, expireDate); } else { reject(token); } }); }); req.on('error', function(err) { reject(err); }); req.end(); } }); }; //'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=ACCESS_TOKEN' var getWeixinServerList = function(token) { return new Promise(function(resolve, reject) { var options = { host: 'api.weixin.qq.com', port: 443, path: '/cgi-bin/getcallbackip?access_token=' + token, method: 'GET', headers: { 'Content-Type': 'application/json' } }; var req = https.request(options, function(res) { var output = ''; console.log(options.host + ':' + res.statusCode); res.setEncoding('utf8'); res.on('data', function (chunk) { output += chunk; }); res.on('end', function() { var obj = JSON.parse(output); var serverList = obj['ip_list']; if(serverList) { resolve(serverList); } else { reject(serverList); } }); }); req.on('error', function(err) { reject(err); }); req.end(); }); }; //'https://api.weixin.qq.com/shakearound/account/register?access_token=ACCESS_TOKEN' var apply4ShakeAround = function(token) { var data = { "name": "石全", "phone_number": "15802243175", "email": "quan.shi@volvo.com", "industry_id": "0308", "qualification_cert_urls": [ ], "apply_reason": "测试服务号使用摇一摇功能" }; var txt = JSON.stringify(data); return new Promise(function(resolve, reject) { var options = { host: 'api.weixin.qq.com', port: 443, path: '/shakearound/account/register?access_token=' + token, method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': txt.length } }; var req = https.request(options, function(res) { var output = ''; console.log(options.host + ':' + res.statusCode); res.setEncoding('utf8'); res.on('data', function (chunk) { output += chunk; }); res.on('end', function() { resolve(output); }); }); req.on('error', function(err) { reject(err); }); req.write(txt + '\n'); req.end(); }); }; //'https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN' /* GET users listing. */ router.get('/', function(req, res, next) { var p = getWeixinToken(); var errorHandler = function(err) {console.error(err)}; p.then(function(token) { console.log('token : ' + token); // getWeixinServerList(token).catch(errorHandler).then(function(serverList) { // console.log(JSON.stringify(serverList)); // }).catch(errorHandler); apply4ShakeAround(token).then(function(out) { console.log(out); }).catch(errorHandler); }); res.send('--1--'); }); module.exports = router; })(module);
apache-2.0
timburks/gott
operations/reverse_case_character.go
1031
// // 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 operations import ( gott "github.com/timburks/gott/types" ) // ReverseCaseCharacter reverses the case of a character. type ReverseCaseCharacter struct { operation } func (op *ReverseCaseCharacter) Perform(e gott.Editor, multiplier int) gott.Operation { op.init(e, multiplier) e.ReverseCaseCharactersAtCursor(op.Multiplier) if op.Undo { e.SetCursor(op.Cursor) } inverse := &ReverseCaseCharacter{} inverse.copyForUndo(&op.operation) return inverse }
apache-2.0
sifonsecac/capitalino-errante
wp-content/themes/nanomag/inc/new_builder/home_two_columns_post_list.php
12131
<?php class home_post_two_columns_list extends AQ_Block { //set and create block function __construct() { $block_options = array( 'name' => esc_attr__('Home post two columns list', 'jelly_text_main'), 'size' => 'span12', ); //create the block parent::__construct('home_post_two_columns_list', $block_options); } //create form function form($instance) { $titles = isset($instance['titles']) ? esc_attr($instance['titles']) : 'Home columns1'; $title1 = isset($instance['title1']) ? esc_attr($instance['title1']) : 'Home columns2'; $css_class_builder = isset($instance['css_class_builder']) ? esc_attr($instance['css_class_builder']) : 'color-1'; $css_class_builder1 = isset($instance['css_class_builder1']) ? esc_attr($instance['css_class_builder1']) : 'color-12'; $number_show = isset($instance['number_show']) ? absint($instance['number_show']) : 5; $number_offset = isset($instance['number_offset']) ? absint($instance['number_offset']) : 0; $number_offset1 = isset($instance['number_offset1']) ? absint($instance['number_offset1']) : 0; ?> <p><label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_attr_e('Title:', 'jelly_text_main'); ?></label> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('titles')); ?>" name="<?php echo esc_attr($this->get_field_name('titles')); ?>" type="text" value="<?php echo esc_attr($titles); ?>" /></p> <p><label for="<?php echo esc_attr($this->get_field_id('title1')); ?>"><?php esc_attr_e('Title for right column:','jelly_text_main'); ?></label> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title1')); ?>" name="<?php echo esc_attr($this->get_field_name('title1')); ?>" type="text" value="<?php echo esc_attr($title1); ?>" /></p> <p><label for="<?php echo esc_attr($this->get_field_id('css_class_builder')); ?>"><?php esc_attr_e('CSS class columns1','jelly_text_main'); ?></label> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('css_class_builder')); ?>" name="<?php echo esc_attr($this->get_field_name('css_class_builder')); ?>" type="text" value="<?php echo esc_attr($css_class_builder); ?>" /></p> <p><label for="<?php echo esc_attr($this->get_field_id('css_class_builder1')); ?>"><?php esc_attr_e('CSS class columns2','jelly_text_main'); ?></label> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('css_class_builder1')); ?>" name="<?php echo esc_attr($this->get_field_name('css_class_builder1')); ?>" type="text" value="<?php echo esc_attr($css_class_builder1); ?>" /></p> <p><label for="<?php echo esc_attr($this->get_field_id('number_show')); ?>"><?php esc_attr_e('Number of posts to show:', 'jelly_text_main'); ?></label> <input id="<?php echo esc_attr($this->get_field_id('number_show')); ?>" name="<?php echo esc_attr($this->get_field_name('number_show')); ?>" type="text" value="<?php echo esc_attr($number_show); ?>" size="3" /></p> <p><label for="<?php echo esc_attr($this->get_field_id('number_offset')); ?>"><?php esc_attr_e('Offset col1 posts:', 'jelly_text_main'); ?></label> <input id="<?php echo esc_attr($this->get_field_id('number_offset')); ?>" name="<?php echo esc_attr($this->get_field_name('number_offset')); ?>" type="text" value="<?php echo esc_attr($number_offset); ?>" size="3" /></p> <p><label for="<?php echo esc_attr($this->get_field_id('number_offset1')); ?>"><?php esc_attr_e('Offset col2 posts:', 'jelly_text_main'); ?></label> <input id="<?php echo esc_attr($this->get_field_id('number_offset1')); ?>" name="<?php echo esc_attr($this->get_field_name('number_offset1')); ?>" type="text" value="<?php echo esc_attr($number_offset); ?>" size="3" /></p> <p> <label for="<?php echo $this->get_field_id('cats'); ?>"><?php esc_attr_e('Choose your category:', 'jelly_text_main'); ?> <?php $categories = get_categories('hide_empty=0'); echo "<br/>"; foreach ($categories as $cat) { $option = '<input type="checkbox" id="' . $this->get_field_id('cats') . '[]" name="' . $this->get_field_name('cats') . '[]"'; if (isset($instance['cats'])) { foreach ($instance['cats'] as $cats) { if ($cats == $cat->term_id) { $option = $option . ' checked="checked"'; } } } $option .= ' value="' . $cat->term_id . '" />'; $option .= '&nbsp;'; $option .= $cat->cat_name; $option .= '<br />'; echo $option; } ?> </label> </p> <p> <label for="<?php echo esc_attr($this->get_field_id('cats1')); ?>"><?php esc_attr_e('Choose your category:', 'jelly_text_main'); ?> <?php $categories = get_categories('hide_empty=0'); echo "<br/>"; foreach ($categories as $cat) { $option = '<input type="checkbox" id="' . $this->get_field_id('cats1') . '[]" name="' . $this->get_field_name('cats1') . '[]"'; if (isset($instance['cats1'])) { foreach ($instance['cats1'] as $cats) { if ($cats == $cat->term_id) { $option = $option . ' checked="checked"'; } } } $option .= ' value="' . $cat->term_id . '" />'; $option .= '&nbsp;'; $option .= $cat->cat_name; $option .= '<br />'; echo $option; } ?> </label> </p> <?php } //create block function block($instance) { extract($instance); $titles = apply_filters('widget_title', empty($instance['titles']) ? 'Recent Posts' : $instance['titles'], $instance, $this->id_base); $title1 = apply_filters('widget_title', empty($instance['title1']) ? 'Recent Posts' : $instance['title1'], $instance, $this->id_base); if (!$number_show = absint($instance['number_show'])){$number_show = 5;} if (isset($instance['number_offset'])==''){$number_offset = 0;}else{$number_offset = absint($instance['number_offset']);} if (isset($instance['number_offset1'])==''){$number_offset1 = 0;}else{$number_offset1 = absint($instance['number_offset1']);} if (!isset($instance["cats"])){$cats = '';} if (!isset($instance["cats1"])){$cats1 = '';} // array to call recent posts. $jellywp_args = array( 'showposts' => $number_show, 'category__in' => $cats, 'ignore_sticky_posts' => 1, 'offset' => $number_offset ); $jellywp_args1 = array( 'showposts' => $number_show, 'category__in' => $cats1, 'ignore_sticky_posts' => 1, 'offset' => $number_offset1 ); $jellywp_widget = null; $jellywp_widget = new WP_Query($jellywp_args); ?> <div class="widget two_columns_post builder_two_cols"> <div class="feature-two-column list-col1-home left-post-display-content margin-left-post <?php echo esc_attr($instance['css_class_builder']);?>"> <?php if (!empty($instance['titles'])) {?><div class="widget-title"><h2><?php echo esc_attr($instance["titles"]);?></h2></div><?php }?> <div class="wrap_box_style_ul"> <ul class="feature-post-list"> <?php $i = 0; while ($jellywp_widget->have_posts()) { $jellywp_widget->the_post(); $i++; $post_id = get_the_ID(); //get all post categories $categories = get_the_category(get_the_ID()); ?> <li class="<?php if(!of_get_option('disable_css_animation')==1){echo esc_attr("appear_animation");}?>"> <a href="<?php the_permalink(); ?>" class="feature-image-link image_post" title="<?php the_title_attribute(); ?>"> <?php if ( has_post_thumbnail()) {the_post_thumbnail('small-feature');} else{echo '<img class="no_feature_img" alt="" src="'.get_template_directory_uri().'/img/feature_img/small-feature.jpg'.'">';} ?> <?php echo jelly_post_type(); ?> </a> <div class="item-details"> <?php if(of_get_option('disable_post_category') !=1){ if ($categories) { echo '<span class="meta-category-small">'; foreach( $categories as $tag) { $tag_link = get_category_link($tag->term_id); $titleColor = jelly_categorys_title_color($tag->term_id, "category", false); echo '<a class="post-category-color-text" style="color:'.esc_attr($titleColor).'" href="'.esc_url($tag_link).'">'.$tag->name.'</a>'; } echo "</span>"; } }?> <?php echo jelly_total_score_post_front_small_list(get_the_ID());?> <h3 class="feature-post-title"><a href="<?php the_permalink(); ?>"><?php the_title()?></a></h3> <?php echo jelly_post_meta(get_the_ID()); ?> </div> <div class="clearfix"></div> </li> <?php } echo " </ul>";?> </div> </div> <?php wp_reset_query(); // column right $jellywp_widget1 = null; $jellywp_widget1 = new WP_Query($jellywp_args1); ?> <div class="feature-two-column right-post-display-content <?php echo esc_attr($instance['css_class_builder1']);?>"> <?php if (!empty($instance['title1'])) {?><div class="widget-title"><h2><?php echo esc_attr($instance["title1"]);?></h2></div><?php }?> <div class="wrap_box_style_ul"> <ul class="feature-post-list"> <?php $i = 0; while ($jellywp_widget1->have_posts()) { $jellywp_widget1->the_post(); $i++; $post_id = get_the_ID(); //get all post categories $categories = get_the_category(get_the_ID()); ?> <li class="<?php if(!of_get_option('disable_css_animation')==1){echo esc_attr("appear_animation");}?>"> <a href="<?php the_permalink(); ?>" class="feature-image-link image_post" title="<?php the_title_attribute(); ?>"> <?php if ( has_post_thumbnail()) {the_post_thumbnail('small-feature');} else{echo '<img class="no_feature_img" alt="" src="'.get_template_directory_uri().'/img/feature_img/small-feature.jpg'.'">';} ?> <?php echo jelly_post_type(); ?> </a> <div class="item-details"> <?php if(of_get_option('disable_post_category') !=1){ if ($categories) { echo '<span class="meta-category-small">'; foreach( $categories as $tag) { $tag_link = get_category_link($tag->term_id); $titleColor = jelly_categorys_title_color($tag->term_id, "category", false); echo '<a class="post-category-color-text" style="color:'.esc_attr($titleColor).'" href="'.esc_url($tag_link).'">'.$tag->name.'</a>'; } echo "</span>"; } }?> <?php echo jelly_total_score_post_front_small_list(get_the_ID());?> <h3 class="feature-post-title"><a href="<?php the_permalink(); ?>"><?php the_title()?></a></h3> <?php echo jelly_post_meta(get_the_ID()); ?> </div> <div class="clearfix"></div> </li> <?php } echo " </ul>";?> </div> </div> </div> <?php wp_reset_query(); } function update($new_instance, $old_instance) { return $new_instance; } }
apache-2.0
aarya123/Assassin
server/compare/opencv-cmake/modules/photo/precomp.hpp
2404
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ #include "opencv2/core/private.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/photo.hpp" #ifdef HAVE_TEGRA_OPTIMIZATION #include "opencv2/photo/photo_tegra.hpp" #endif #endif
apache-2.0
bowlofstew/kythe
kythe/cxx/indexer/cxx/testdata/template/template_class_fn_spec.cc
535
// Checks that we get edges for member function specialization and calls // thereto. //- @F defines/binding MemDecl //- @C defines/binding TmplDefn template <typename T> struct C { static void F(); }; //- @F defines/binding IntMemDefn //- @F completes/uniquely IntMemDecl template <> void C<int>::F() {} //- IntMemDecl.complete incomplete //- IntMemDefn.complete definition //- IntMemDecl childof IntTmplSpec //- IntTmpl specializes TApp //- TApp param.0 TmplDefn //- @"C<int>::F()" ref/call IntMemDefn void dummy() { C<int>::F(); }
apache-2.0
thescouser89/pnc
facade/src/main/java/org/jboss/pnc/facade/impl/BrewPusherImpl.java
14319
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.facade.impl; import lombok.extern.slf4j.Slf4j; import org.jboss.pnc.bpm.causeway.BuildPushOperation; import org.jboss.pnc.bpm.causeway.BuildResultPushManager; import org.jboss.pnc.bpm.causeway.InProgress; import org.jboss.pnc.bpm.causeway.Result; import org.jboss.pnc.common.concurrent.Sequence; import org.jboss.pnc.common.json.GlobalModuleGroup; import org.jboss.pnc.common.logging.MDCUtils; import org.jboss.pnc.common.util.StringUtils; import org.jboss.pnc.dto.BuildPushResult; import org.jboss.pnc.dto.requests.BuildPushParameters; import org.jboss.pnc.enums.ArtifactQuality; import org.jboss.pnc.enums.BuildPushStatus; import org.jboss.pnc.enums.BuildStatus; import org.jboss.pnc.facade.BrewPusher; import org.jboss.pnc.facade.util.UserService; import org.jboss.pnc.facade.validation.AlreadyRunningException; import org.jboss.pnc.facade.validation.EmptyEntityException; import org.jboss.pnc.facade.validation.InvalidEntityException; import org.jboss.pnc.facade.validation.OperationNotAllowedException; import org.jboss.pnc.mapper.api.BuildMapper; import org.jboss.pnc.mapper.api.BuildPushResultMapper; import org.jboss.pnc.model.Artifact; import org.jboss.pnc.model.Base32LongID; import org.jboss.pnc.model.BuildRecord; import org.jboss.pnc.model.BuildRecordPushResult; import org.jboss.pnc.model.IdRev; import org.jboss.pnc.spi.coordinator.ProcessException; import org.jboss.pnc.spi.datastore.InconsistentDataException; import org.jboss.pnc.spi.datastore.predicates.ArtifactPredicates; import org.jboss.pnc.spi.datastore.predicates.BuildRecordPredicates; import org.jboss.pnc.spi.datastore.repositories.ArtifactRepository; import org.jboss.pnc.spi.datastore.repositories.BuildRecordPushResultRepository; import org.jboss.pnc.spi.datastore.repositories.BuildRecordRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import java.util.Collection; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import static org.jboss.pnc.constants.MDCKeys.BUILD_ID_KEY; import static org.jboss.pnc.enums.ArtifactQuality.BLACKLISTED; import static org.jboss.pnc.enums.ArtifactQuality.DELETED; /** * * @author Honza Brázdil &lt;jbrazdil@redhat.com&gt; */ @RequestScoped @Slf4j public class BrewPusherImpl implements BrewPusher { @Inject private BuildRecordRepository buildRecordRepository; @Inject private ArtifactRepository artifactRepository; @Inject private BuildRecordPushResultRepository buildRecordPushResultRepository; @Inject private BuildResultPushManager buildResultPushManager; @Inject private GlobalModuleGroup globalModuleGroupConfiguration; @Inject private BuildPushResultMapper buildPushResultMapper; @Inject private UserService userService; private final static EnumSet<ArtifactQuality> ARTIFACT_BAD_QUALITIES = EnumSet.of(DELETED, BLACKLISTED); private static final Logger userLog = LoggerFactory.getLogger("org.jboss.pnc._userlog_.brewpush"); @Override public Set<BuildPushResult> pushGroup(int buildGroupId, String tagPrefix) { BuildPushParameters buildPushParameters = BuildPushParameters.builder() .tagPrefix(tagPrefix) .reimport(false) .build(); List<BuildRecord> buildRecords = buildRecordRepository .queryWithPredicates(BuildRecordPredicates.withBuildConfigSetRecordId(buildGroupId)); Set<BuildPushResult> results = new HashSet<>(); for (BuildRecord buildRecord : buildRecords) { Long buildPushResultId = Sequence.nextId(); MDCUtils.addProcessContext(buildPushResultId.toString()); MDCUtils.addCustomContext(BUILD_ID_KEY, buildRecord.getId().getId()); try { results.add(doPushBuild(buildRecord.getId(), buildPushParameters, buildPushResultId)); } catch (OperationNotAllowedException | AlreadyRunningException e) { results.add( BuildPushResult.builder() .status(BuildPushStatus.REJECTED) .id(buildPushResultId.toString()) .buildId(BuildMapper.idMapper.toDto(buildRecord.getId())) .message(e.getMessage()) .build()); } catch (InconsistentDataException | ProcessException e) { results.add( BuildPushResult.builder() .status(BuildPushStatus.SYSTEM_ERROR) .id(buildPushResultId.toString()) .buildId(BuildMapper.idMapper.toDto(buildRecord.getId())) .message(e.getMessage()) .build()); } finally { MDCUtils.removeProcessContext(); MDCUtils.removeCustomContext(BUILD_ID_KEY); } } return results; } @Override public BuildPushResult pushBuild(String buildId, BuildPushParameters buildPushParameters) throws ProcessException { Base32LongID id = BuildMapper.idMapper.toEntity(buildId); BuildRecord build = buildRecordRepository.queryById(BuildMapper.idMapper.toEntity(buildId)); if (build.getStatus().equals(BuildStatus.NO_REBUILD_REQUIRED)) { throw new OperationNotAllowedException( "Build has NO_REBUILD_REQUIRED status, push last successful build or use force-rebuild."); } Long buildPushResultId = Sequence.nextId(); MDCUtils.addProcessContext(buildPushResultId.toString()); MDCUtils.addCustomContext(BUILD_ID_KEY, id.getId()); try { return doPushBuild(id, buildPushParameters, buildPushResultId); } finally { MDCUtils.removeProcessContext(); MDCUtils.removeCustomContext(BUILD_ID_KEY); } } private BuildPushResult doPushBuild( Base32LongID buildId, BuildPushParameters buildPushParameters, Long buildPushResultId) throws ProcessException { userLog.info("Push started."); // TODO START timing event // collect and validate input data BuildRecord buildRecord = getLatestSuccessfullyExecutedBuildRecord(buildId); List<Artifact> artifacts = artifactRepository .queryWithPredicates(ArtifactPredicates.withBuildRecordId(buildRecord.getId())); if (hasBadArtifactQuality(artifacts)) { String message = "Build contains artifacts of insufficient quality: BLACKLISTED/DELETED."; log.debug(message); BuildPushResult pushResult = BuildPushResult.builder() .buildId(BuildMapper.idMapper.toDto(buildId)) .status(BuildPushStatus.REJECTED) .id(buildPushResultId.toString()) .logContext(buildPushResultId.toString()) .message(message) .build(); throw new OperationNotAllowedException(message, pushResult); } log.debug("Pushing Build.id {}.", buildRecord.getId()); BuildPushOperation buildPushOperation = new BuildPushOperation( buildRecord, buildPushResultId, buildPushParameters.getTagPrefix(), buildPushParameters.isReimport(), getCompleteCallbackUrlTemplate()); Result pushResult = buildResultPushManager.push(buildPushOperation, userService.currentUserToken()); log.info("Push Result {}.", pushResult); BuildPushResult result = BuildPushResult.builder() .id(pushResult.getId()) .buildId(pushResult.getBuildId()) .status(pushResult.getStatus()) .logContext(pushResult.getId()) .message(pushResult.getMessage()) .build(); // verify operation status switch (pushResult.getStatus()) { case ACCEPTED: userLog.info("Push ACCEPTED."); return result; case REJECTED: userLog.warn("Push REJECTED."); throw new AlreadyRunningException(pushResult.getMessage(), result); case SYSTEM_ERROR: userLog.error("Brew push failed: " + pushResult.getMessage()); throw new ProcessException(pushResult.getMessage()); default: userLog.error("Invalid push result status."); throw new ProcessException("Invalid push result status."); } } private boolean hasBadArtifactQuality(Collection<Artifact> builtArtifacts) { return builtArtifacts.stream().map(Artifact::getArtifactQuality).anyMatch(ARTIFACT_BAD_QUALITIES::contains); } /** * * @param buildRecordId * @return Latest build record with status success or null if the build record does not exist. * @throws InconsistentDataException when there is no SUCCESS status before NO_REBUILD_REQUIRED * @throws InvalidEntityException when the status is not SUCCESS or NO_REBUILD_REQUIRED */ private BuildRecord getLatestSuccessfullyExecutedBuildRecord(Base32LongID buildRecordId) { BuildRecord buildRecord = buildRecordRepository.findByIdFetchProperties(buildRecordId); if (buildRecord == null) { throw new EmptyEntityException("Build record not found."); } if (BuildStatus.SUCCESS.equals(buildRecord.getStatus())) { return buildRecord; } else if (BuildStatus.NO_REBUILD_REQUIRED.equals(buildRecord.getStatus())) { // if status is NO_REBUILD_REQUIRED, find the last BuildRecord with status SUCCESS for the same idRev. IdRev idRev = buildRecord.getBuildConfigurationAuditedIdRev(); BuildRecord latestSuccessfulBuildRecord = buildRecordRepository .getLatestSuccessfulBuildRecord(idRev, buildRecord.isTemporaryBuild()); if (latestSuccessfulBuildRecord != null) { return latestSuccessfulBuildRecord; } else { String message = "There is no SUCCESS build before NO_REBUILD_REQUIRED."; log.error(message); // In case of temporary builds it can happen. The SUCCESS build might be already garbage-collected. throw new InconsistentDataException(message); } } else { // Build status is not SUCCESS or NO_REBUILD_REQUIRED. throw new OperationNotAllowedException("Not allowed to push failed build."); } } @Override public boolean brewPushCancel(String buildId) { Base32LongID id = BuildMapper.idMapper.toEntity(buildId); Optional<InProgress.Context> pushContext = buildResultPushManager.getContext(id); if (pushContext.isPresent()) { MDCUtils.addProcessContext(pushContext.get().getPushResultId()); MDCUtils.addCustomContext(BUILD_ID_KEY, id.getId()); userLog.info("Build push cancel requested."); try { return buildResultPushManager.cancelInProgressPush(id); } finally { MDCUtils.removeProcessContext(); MDCUtils.removeCustomContext(BUILD_ID_KEY); } } else { throw new EmptyEntityException("There is no running push operation for build id: " + buildId); } } @Override public BuildPushResult brewPushComplete(String buildId, BuildPushResult buildPushResult) { Base32LongID id = BuildMapper.idMapper.toEntity(buildId); MDCUtils.addProcessContext(buildPushResult.getId()); MDCUtils.addCustomContext(BUILD_ID_KEY, id.getId()); try { log.info( "Received completion notification for BuildRecord.id: {}. Object received: {}.", buildId, buildPushResult); buildResultPushManager.complete(id, buildPushResultMapper.toEntity(buildPushResult)); userLog.info("Brew push completed."); // TODO END timing event return buildPushResult; } finally { MDCUtils.removeProcessContext(); MDCUtils.removeCustomContext(BUILD_ID_KEY); } } @Override public BuildPushResult getBrewPushResult(String buildId) { Base32LongID id = BuildMapper.idMapper.toEntity(buildId); BuildPushResult result = null; Optional<InProgress.Context> pushContext = buildResultPushManager.getContext(id); if (pushContext.isPresent()) { result = BuildPushResult.builder() .buildId(buildId) .status(BuildPushStatus.ACCEPTED) .logContext(pushContext.get().getPushResultId()) .build(); } else { BuildRecordPushResult latestForBuildRecord = buildRecordPushResultRepository.getLatestForBuildRecord(id); if (latestForBuildRecord != null) { return buildPushResultMapper.toDTO(latestForBuildRecord); } } return result; } private String getCompleteCallbackUrlTemplate() { String pncBaseUrl = StringUtils.stripEndingSlash(globalModuleGroupConfiguration.getPncUrl()); return pncBaseUrl + "/builds/%s/brew-push/complete"; } }
apache-2.0
fine1021/library
support/src/main/java/com/yxkang/android/util/HashMap.java
34584
/* * 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.yxkang.android.util; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * HashMap is an implementation of {@link Map}. All optional operations are supported. * <br> * <p>All elements are permitted as keys or values, including null. * <br> * <p>Note that the iteration order for HashMap is non-deterministic. If you want * deterministic iteration, use {@link LinkedHashMap}. * <br> * <p>Note: the implementation of {@code HashMap} is not synchronized. * If one thread of several threads accessing an instance modifies the map * structurally, access to the map needs to be synchronized. A structural * modification is an operation that adds or removes an entry. Changes in * the value of an entry are not structural changes. * <br> * <p>The {@code Iterator} created by calling the {@code iterator} method * may throw a {@code ConcurrentModificationException} if the map is structurally * changed while an iterator is used to iterate over the elements. Only the * {@code remove} method that is provided by the iterator allows for removal of * elements during iteration. It is not possible to guarantee that this * mechanism works in all cases of unsynchronized concurrent modification. It * should only be used for debugging purposes. * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values */ class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Serializable { /** * Min capacity (other than zero) for a HashMap. Must be a power of two * greater than 1 (and less than 1 << 30). */ private static final int MINIMUM_CAPACITY = 4; /** * Max capacity for a HashMap. Must be a power of two >= MINIMUM_CAPACITY. */ private static final int MAXIMUM_CAPACITY = 1 << 30; /** * An empty table shared by all zero-capacity maps (typically from default * constructor). It is never written to, and replaced on first put. Its size * is set to half the minimum, so that the first resize will create a * minimum-sized table. */ private static final Entry[] EMPTY_TABLE = new HashMapEntry[MINIMUM_CAPACITY >>> 1]; /** * The default load factor. Note that this implementation ignores the * load factor, but cannot do away with it entirely because it's * mentioned in the API. * <p> * <p>Note that this constant has no impact on the behavior of the program, * but it is emitted as part of the serialized form. The load factor of * .75 is hardwired into the program, which uses cheap shifts in place of * expensive division. */ static final float DEFAULT_LOAD_FACTOR = .75F; /** * The hash table. If this hash map contains a mapping for null, it is * not represented this hash table. */ transient HashMapEntry<K, V>[] table; /** * The entry representing the null key, or null if there's no such mapping. */ transient HashMapEntry<K, V> entryForNullKey; /** * The number of mappings in this hash map. */ transient int size; /** * Incremented by "structural modifications" to allow (best effort) * detection of concurrent modification. */ transient int modCount; /** * The table is rehashed when its size exceeds this threshold. * The value of this field is generally .75 * capacity, except when * the capacity is zero, as described in the EMPTY_TABLE declaration * above. */ private transient int threshold; // Views - lazily initialized private transient Set<K> keySet; private transient Set<Entry<K, V>> entrySet; private transient Collection<V> values; /** * Constructs a new empty {@code HashMap} instance. */ @SuppressWarnings("unchecked") public HashMap() { table = (HashMapEntry<K, V>[]) EMPTY_TABLE; threshold = -1; // Forces first put invocation to replace EMPTY_TABLE } /** * Constructs a new {@code HashMap} instance with the specified capacity. * * @param capacity the initial capacity of this hash map. * @throws IllegalArgumentException when the capacity is less than zero. */ public HashMap(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity: " + capacity); } if (capacity == 0) { @SuppressWarnings("unchecked") HashMapEntry<K, V>[] tab = (HashMapEntry<K, V>[]) EMPTY_TABLE; table = tab; threshold = -1; // Forces first put() to replace EMPTY_TABLE return; } if (capacity < MINIMUM_CAPACITY) { capacity = MINIMUM_CAPACITY; } else if (capacity > MAXIMUM_CAPACITY) { capacity = MAXIMUM_CAPACITY; } else { capacity = Collections.roundUpToPowerOfTwo(capacity); } makeTable(capacity); } /** * Constructs a new {@code HashMap} instance with the specified capacity and * load factor. * * @param capacity the initial capacity of this hash map. * @param loadFactor the initial load factor. * @throws IllegalArgumentException when the capacity is less than zero or the load factor is * less or equal to zero or NaN. */ public HashMap(int capacity, float loadFactor) { this(capacity); if (loadFactor <= 0 || Float.isNaN(loadFactor)) { throw new IllegalArgumentException("Load factor: " + loadFactor); } /* * Note that this implementation ignores loadFactor; it always uses * a load factor of 3/4. This simplifies the code and generally * improves performance. */ } /** * Constructs a new {@code HashMap} instance containing the mappings from * the specified map. * * @param map the mappings to add. */ public HashMap(Map<? extends K, ? extends V> map) { this(capacityForInitSize(map.size())); constructorPutAll(map); } /** * Inserts all of the elements of map into this HashMap in a manner * suitable for use by constructors and pseudo-constructors (i.e., clone, * readObject). Also used by LinkedHashMap. */ final void constructorPutAll(Map<? extends K, ? extends V> map) { if (table == EMPTY_TABLE) { doubleCapacity(); // Don't do unchecked puts to a shared table. } for (Entry<? extends K, ? extends V> e : map.entrySet()) { constructorPut(e.getKey(), e.getValue()); } } /** * Returns an appropriate capacity for the specified initial size. Does * not round the result up to a power of two; the caller must do this! * The returned value will be between 0 and MAXIMUM_CAPACITY (inclusive). */ static int capacityForInitSize(int size) { int result = (size >> 1) + size; // Multiply by 3/2 to allow for growth // boolean expr is equivalent to result >= 0 && result<MAXIMUM_CAPACITY return (result & ~(MAXIMUM_CAPACITY - 1)) == 0 ? result : MAXIMUM_CAPACITY; } /** * Returns a shallow copy of this map. * * @return a shallow copy of this map. */ @SuppressWarnings("unchecked") @Override public Object clone() { /* * This could be made more efficient. It unnecessarily hashes all of * the elements in the map. */ HashMap<K, V> result; try { result = (HashMap<K, V>) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } // Restore clone to empty state, retaining our capacity and threshold result.makeTable(table.length); result.entryForNullKey = null; result.size = 0; result.keySet = null; result.entrySet = null; result.values = null; result.init(); // Give subclass a chance to initialize itself result.constructorPutAll(this); // Calls method overridden in subclass!! return result; } /** * This method is called from the pseudo-constructors (clone and readObject) * prior to invoking constructorPut/constructorPutAll, which invoke the * overridden constructorNewEntry method. Normally it is a VERY bad idea to * invoke an overridden method from a pseudo-constructor (Effective Java * Item 17). In this case it is unavoidable, and the init method provides a * workaround. */ void init() { } /** * Returns whether this map is empty. * * @return {@code true} if this map has no elements, {@code false} * otherwise. * @see #size() */ @Override public boolean isEmpty() { return size == 0; } /** * Returns the number of elements in this map. * * @return the number of elements in this map. */ @Override public int size() { return size; } /** * Returns the value of the mapping with the specified key. * * @param key the key. * @return the value of the mapping with the specified key, or {@code null} * if no mapping for the specified key is found. */ public V get(Object key) { if (key == null) { HashMapEntry<K, V> e = entryForNullKey; return e == null ? null : e.value; } int hash = Collections.secondaryHash(key); HashMapEntry<K, V>[] tab = table; for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { K eKey = e.key; if (eKey == key || (e.hash == hash && key.equals(eKey))) { return e.value; } } return null; } /** * Returns whether this map contains the specified key. * * @param key the key to search for. * @return {@code true} if this map contains the specified key, * {@code false} otherwise. */ @Override public boolean containsKey(Object key) { if (key == null) { return entryForNullKey != null; } int hash = Collections.secondaryHash(key); HashMapEntry<K, V>[] tab = table; for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { K eKey = e.key; if (eKey == key || (e.hash == hash && key.equals(eKey))) { return true; } } return false; } /** * Returns whether this map contains the specified value. * * @param value the value to search for. * @return {@code true} if this map contains the specified value, * {@code false} otherwise. */ @Override public boolean containsValue(Object value) { HashMapEntry[] tab = table; int len = tab.length; if (value == null) { for (int i = 0; i < len; i++) { for (HashMapEntry e = tab[i]; e != null; e = e.next) { if (e.value == null) { return true; } } } return entryForNullKey != null && entryForNullKey.value == null; } // value is non-null for (int i = 0; i < len; i++) { for (HashMapEntry e = tab[i]; e != null; e = e.next) { if (value.equals(e.value)) { return true; } } } return entryForNullKey != null && value.equals(entryForNullKey.value); } /** * Maps the specified key to the specified value. * * @param key the key. * @param value the value. * @return the value of any previous mapping with the specified key or * {@code null} if there was no such mapping. */ @Override public V put(K key, V value) { if (key == null) { return putValueForNullKey(value); } int hash = Collections.secondaryHash(key); HashMapEntry<K, V>[] tab = table; int index = hash & (tab.length - 1); for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) { if (e.hash == hash && key.equals(e.key)) { preModify(e); V oldValue = e.value; e.value = value; return oldValue; } } // No entry for (non-null) key is present; create one modCount++; if (size++ > threshold) { tab = doubleCapacity(); index = hash & (tab.length - 1); } addNewEntry(key, value, hash, index); return null; } private V putValueForNullKey(V value) { HashMapEntry<K, V> entry = entryForNullKey; if (entry == null) { addNewEntryForNullKey(value); size++; modCount++; return null; } else { preModify(entry); V oldValue = entry.value; entry.value = value; return oldValue; } } /** * Give LinkedHashMap a chance to take action when we modify an existing * entry. * * @param e the entry we're about to modify. */ void preModify(HashMapEntry<K, V> e) { } /** * This method is just like put, except that it doesn't do things that * are inappropriate or unnecessary for constructors and pseudo-constructors * (i.e., clone, readObject). In particular, this method does not check to * ensure that capacity is sufficient, and does not increment modCount. */ private void constructorPut(K key, V value) { if (key == null) { HashMapEntry<K, V> entry = entryForNullKey; if (entry == null) { entryForNullKey = constructorNewEntry(null, value, 0, null); size++; } else { entry.value = value; } return; } int hash = Collections.secondaryHash(key); HashMapEntry<K, V>[] tab = table; int index = hash & (tab.length - 1); HashMapEntry<K, V> first = tab[index]; for (HashMapEntry<K, V> e = first; e != null; e = e.next) { if (e.hash == hash && key.equals(e.key)) { e.value = value; return; } } // No entry for (non-null) key is present; create one tab[index] = constructorNewEntry(key, value, hash, first); size++; } /** * Creates a new entry for the given key, value, hash, and index and * inserts it into the hash table. This method is called by put * (and indirectly, putAll), and overridden by LinkedHashMap. The hash * must incorporate the secondary hash function. */ void addNewEntry(K key, V value, int hash, int index) { table[index] = new HashMapEntry<K, V>(key, value, hash, table[index]); } /** * Creates a new entry for the null key, and the given value and * inserts it into the hash table. This method is called by put * (and indirectly, putAll), and overridden by LinkedHashMap. */ void addNewEntryForNullKey(V value) { entryForNullKey = new HashMapEntry<K, V>(null, value, 0, null); } /** * Like newEntry, but does not perform any activity that would be * unnecessary or inappropriate for constructors. In this class, the * two methods behave identically; in LinkedHashMap, they differ. */ HashMapEntry<K, V> constructorNewEntry( K key, V value, int hash, HashMapEntry<K, V> first) { return new HashMapEntry<K, V>(key, value, hash, first); } /** * Copies all the mappings in the specified map to this map. These mappings * will replace all mappings that this map had for any of the keys currently * in the given map. * * @param map the map to copy mappings from. */ @Override public void putAll(Map<? extends K, ? extends V> map) { ensureCapacity(map.size()); super.putAll(map); } /** * Ensures that the hash table has sufficient capacity to store the * specified number of mappings, with room to grow. If not, it increases the * capacity as appropriate. Like doubleCapacity, this method moves existing * entries to new buckets as appropriate. Unlike doubleCapacity, this method * can grow the table by factors of 2^n for n > 1. Hopefully, a single call * to this method will be faster than multiple calls to doubleCapacity. * <p> * <p>This method is called only by putAll. */ private void ensureCapacity(int numMappings) { int newCapacity = Collections.roundUpToPowerOfTwo(capacityForInitSize(numMappings)); HashMapEntry<K, V>[] oldTable = table; int oldCapacity = oldTable.length; if (newCapacity <= oldCapacity) { return; } if (newCapacity == oldCapacity * 2) { doubleCapacity(); return; } // We're growing by at least 4x, rehash in the obvious way HashMapEntry<K, V>[] newTable = makeTable(newCapacity); if (size != 0) { int newMask = newCapacity - 1; for (int i = 0; i < oldCapacity; i++) { for (HashMapEntry<K, V> e = oldTable[i]; e != null; ) { HashMapEntry<K, V> oldNext = e.next; int newIndex = e.hash & newMask; HashMapEntry<K, V> newNext = newTable[newIndex]; newTable[newIndex] = e; e.next = newNext; e = oldNext; } } } } /** * Allocate a table of the given capacity and set the threshold accordingly. * * @param newCapacity must be a power of two */ private HashMapEntry<K, V>[] makeTable(int newCapacity) { @SuppressWarnings("unchecked") HashMapEntry<K, V>[] newTable = (HashMapEntry<K, V>[]) new HashMapEntry[newCapacity]; table = newTable; threshold = (newCapacity >> 1) + (newCapacity >> 2); // 3/4 capacity return newTable; } /** * Doubles the capacity of the hash table. Existing entries are placed in * the correct bucket on the enlarged table. If the current capacity is, * MAXIMUM_CAPACITY, this method is a no-op. Returns the table, which * will be new unless we were already at MAXIMUM_CAPACITY. */ private HashMapEntry<K, V>[] doubleCapacity() { HashMapEntry<K, V>[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { return oldTable; } int newCapacity = oldCapacity * 2; HashMapEntry<K, V>[] newTable = makeTable(newCapacity); if (size == 0) { return newTable; } for (int j = 0; j < oldCapacity; j++) { /* * Rehash the bucket using the minimum number of field writes. * This is the most subtle and delicate code in the class. */ HashMapEntry<K, V> e = oldTable[j]; if (e == null) { continue; } int highBit = e.hash & oldCapacity; HashMapEntry<K, V> broken = null; newTable[j | highBit] = e; for (HashMapEntry<K, V> n = e.next; n != null; e = n, n = n.next) { int nextHighBit = n.hash & oldCapacity; if (nextHighBit != highBit) { if (broken == null) newTable[j | nextHighBit] = n; else broken.next = n; broken = e; highBit = nextHighBit; } } if (broken != null) broken.next = null; } return newTable; } /** * Removes the mapping with the specified key from this map. * * @param key the key of the mapping to remove. * @return the value of the removed mapping or {@code null} if no mapping * for the specified key was found. */ @Override public V remove(Object key) { if (key == null) { return removeNullKey(); } int hash = Collections.secondaryHash(key); HashMapEntry<K, V>[] tab = table; int index = hash & (tab.length - 1); for (HashMapEntry<K, V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e.hash == hash && key.equals(e.key)) { if (prev == null) { tab[index] = e.next; } else { prev.next = e.next; } modCount++; size--; postRemove(e); return e.value; } } return null; } private V removeNullKey() { HashMapEntry<K, V> e = entryForNullKey; if (e == null) { return null; } entryForNullKey = null; modCount++; size--; postRemove(e); return e.value; } /** * Subclass overrides this method to unlink entry. */ void postRemove(HashMapEntry<K, V> e) { } /** * Removes all mappings from this hash map, leaving it empty. * * @see #isEmpty * @see #size */ @Override public void clear() { if (size != 0) { Arrays.fill(table, null); entryForNullKey = null; modCount++; size = 0; } } /** * Returns a set of the keys contained in this map. The set is backed by * this map so changes to one are reflected by the other. The set does not * support adding. * * @return a set of the keys. */ @Override public Set<K> keySet() { Set<K> ks = keySet; return (ks != null) ? ks : (keySet = new KeySet()); } /** * Returns a collection of the values contained in this map. The collection * is backed by this map so changes to one are reflected by the other. The * collection supports remove, removeAll, retainAll and clear operations, * and it does not support add or addAll operations. * <p> * This method returns a collection which is the subclass of * AbstractCollection. The iterator method of this subclass returns a * "wrapper object" over the iterator of map's entrySet(). The {@code size} * method wraps the map's size method and the {@code contains} method wraps * the map's containsValue method. * </p> * <p> * The collection is created when this method is called for the first time * and returned in response to all subsequent calls. This method may return * different collections when multiple concurrent calls occur, since no * synchronization is performed. * </p> * * @return a collection of the values contained in this map. */ @Override public Collection<V> values() { Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); } /** * Returns a set containing all of the mappings in this map. Each mapping is * an instance of {@link Entry}. As the set is backed by this map, * changes in one will be reflected in the other. * * @return a set of the mappings. */ public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } static class HashMapEntry<K, V> implements Entry<K, V> { final K key; V value; final int hash; HashMapEntry<K, V> next; HashMapEntry(K key, V value, int hash, HashMapEntry<K, V> next) { this.key = key; this.value = value; this.hash = hash; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @Override public final boolean equals(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> e = (Entry<?, ?>) o; return Objects.equals(e.getKey(), key) && Objects.equals(e.getValue(), value); } @Override public final int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } @Override public final String toString() { return key + "=" + value; } } private abstract class HashIterator { int nextIndex; HashMapEntry<K, V> nextEntry = entryForNullKey; HashMapEntry<K, V> lastEntryReturned; int expectedModCount = modCount; HashIterator() { if (nextEntry == null) { HashMapEntry<K, V>[] tab = table; HashMapEntry<K, V> next = null; while (next == null && nextIndex < tab.length) { next = tab[nextIndex++]; } nextEntry = next; } } public boolean hasNext() { return nextEntry != null; } HashMapEntry<K, V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (nextEntry == null) throw new NoSuchElementException(); HashMapEntry<K, V> entryToReturn = nextEntry; HashMapEntry<K, V>[] tab = table; HashMapEntry<K, V> next = entryToReturn.next; while (next == null && nextIndex < tab.length) { next = tab[nextIndex++]; } nextEntry = next; return lastEntryReturned = entryToReturn; } public void remove() { if (lastEntryReturned == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); HashMap.this.remove(lastEntryReturned.key); lastEntryReturned = null; expectedModCount = modCount; } } private final class KeyIterator extends HashIterator implements Iterator<K> { public K next() { return nextEntry().key; } } private final class ValueIterator extends HashIterator implements Iterator<V> { public V next() { return nextEntry().value; } } private final class EntryIterator extends HashIterator implements Iterator<Entry<K, V>> { public Entry<K, V> next() { return nextEntry(); } } /** * Returns true if this map contains the specified mapping. */ private boolean containsMapping(Object key, Object value) { if (key == null) { HashMapEntry<K, V> e = entryForNullKey; return e != null && Objects.equals(value, e.value); } int hash = Collections.secondaryHash(key); HashMapEntry<K, V>[] tab = table; int index = hash & (tab.length - 1); for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) { if (e.hash == hash && key.equals(e.key)) { return Objects.equals(value, e.value); } } return false; // No entry for key } /** * Removes the mapping from key to value and returns true if this mapping * exists; otherwise, returns does nothing and returns false. */ private boolean removeMapping(Object key, Object value) { if (key == null) { HashMapEntry<K, V> e = entryForNullKey; if (e == null || !Objects.equals(value, e.value)) { return false; } entryForNullKey = null; modCount++; size--; postRemove(e); return true; } int hash = Collections.secondaryHash(key); HashMapEntry<K, V>[] tab = table; int index = hash & (tab.length - 1); for (HashMapEntry<K, V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e.hash == hash && key.equals(e.key)) { if (!Objects.equals(value, e.value)) { return false; // Map has wrong value for key } if (prev == null) { tab[index] = e.next; } else { prev.next = e.next; } modCount++; size--; postRemove(e); return true; } } return false; // No entry for key } // Subclass (LinkedHashMap) overrides these for correct iteration order Iterator<K> newKeyIterator() { return new KeyIterator(); } Iterator<V> newValueIterator() { return new ValueIterator(); } Iterator<Entry<K, V>> newEntryIterator() { return new EntryIterator(); } private final class KeySet extends AbstractSet<K> { public Iterator<K> iterator() { return newKeyIterator(); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { int oldSize = size; HashMap.this.remove(o); return size != oldSize; } public void clear() { HashMap.this.clear(); } } private final class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return newValueIterator(); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public boolean contains(Object o) { return containsValue(o); } public void clear() { HashMap.this.clear(); } } private final class EntrySet extends AbstractSet<Entry<K, V>> { public Iterator<Entry<K, V>> iterator() { return newEntryIterator(); } public boolean contains(Object o) { if (!(o instanceof Entry)) return false; Entry<?, ?> e = (Entry<?, ?>) o; return containsMapping(e.getKey(), e.getValue()); } public boolean remove(Object o) { if (!(o instanceof Entry)) return false; Entry<?, ?> e = (Entry<?, ?>) o; return removeMapping(e.getKey(), e.getValue()); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void clear() { HashMap.this.clear(); } } private static final long serialVersionUID = 362498820763181265L; private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("loadFactor", float.class) }; private void writeObject(ObjectOutputStream stream) throws IOException { // Emulate loadFactor field for other implementations to read ObjectOutputStream.PutField fields = stream.putFields(); fields.put("loadFactor", DEFAULT_LOAD_FACTOR); stream.writeFields(); stream.writeInt(table.length); // Capacity stream.writeInt(size); for (Entry<K, V> e : entrySet()) { stream.writeObject(e.getKey()); stream.writeObject(e.getValue()); } } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int capacity = stream.readInt(); if (capacity < 0) { throw new InvalidObjectException("Capacity: " + capacity); } if (capacity < MINIMUM_CAPACITY) { capacity = MINIMUM_CAPACITY; } else if (capacity > MAXIMUM_CAPACITY) { capacity = MAXIMUM_CAPACITY; } else { capacity = Collections.roundUpToPowerOfTwo(capacity); } makeTable(capacity); int size = stream.readInt(); if (size < 0) { throw new InvalidObjectException("Size: " + size); } init(); // Give subclass (LinkedHashMap) a chance to initialize itself for (int i = 0; i < size; i++) { @SuppressWarnings("unchecked") K key = (K) stream.readObject(); @SuppressWarnings("unchecked") V val = (V) stream.readObject(); constructorPut(key, val); } } }
apache-2.0
testobject/visual-scripting
org.testobject.kernel/imgproc/src/main/java/org/testobject/kernel/imgproc/classifier/Context.java
291
package org.testobject.kernel.imgproc.classifier; import org.testobject.commons.util.image.Image; public class Context { public final Image.Int before; public final Image.Int after; public Context(Image.Int before, Image.Int after) { this.before = before; this.after = after; } }
apache-2.0
hivemq/hivemq-spi
src/main/java/com/hivemq/spi/security/QueuedMessageStrategy.java
799
/* * Copyright 2017 dc-square GmbH * * 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.hivemq.spi.security; /** * @author Lukas Brandl */ public class QueuedMessageStrategy { public static final long DISCARD = 0; public static final long DISCARD_OLDEST = 1; }
apache-2.0
beysims/reef
lang/cs/Tests/ReefTests/Evaluator.Tests/EvaluatorTests.cs
4261
/** * 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 Org.Apache.Reef.Common.Avro; using Org.Apache.Reef.Common.Evaluator; using Org.Apache.Reef.Tasks; using Org.Apache.Reef.Tang.Formats; using Org.Apache.Reef.Tang.Implementations; using Org.Apache.Reef.Tang.Interface; using Org.Apache.Reef.Tang.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; namespace Org.Apache.Reef.Test { [TestClass] public class EvaluatorTests { [TestMethod, Priority(0), TestCategory("Functional")] [Description("Parse Evaluator configuration from Java, inject and execute Shell task with DIR command based on the configuration")] [DeploymentItem(@"ConfigFiles")] public void CanInjectAndExecuteTask() { //To enforce that shell task dll be copied to output directory. ShellTask tmpTask = new ShellTask("invalid"); Assert.IsNotNull(tmpTask); string tmp = Directory.GetCurrentDirectory(); Assert.IsNotNull(tmp); AvroConfigurationSerializer serializer = new AvroConfigurationSerializer(); AvroConfiguration avroConfiguration = serializer.AvroDeseriaizeFromFile("evaluator.conf"); Assert.IsNotNull(avroConfiguration); ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder(); cb.AddConfiguration(TaskConfiguration.ConfigurationModule .Set(TaskConfiguration.Identifier, "Test_CLRContext_task") .Set(TaskConfiguration.Task, GenericType<ShellTask>.Class) .Build()); cb.BindNamedParameter<ShellTask.Command, string>(GenericType<ShellTask.Command>.Class, "dir"); IConfiguration taskConfiguration = cb.Build(); string taskConfig = serializer.ToString(taskConfiguration); ITask task = null; TaskConfiguration config = new TaskConfiguration(taskConfig); Assert.IsNotNull(config); try { IInjector injector = TangFactory.GetTang().NewInjector(config.TangConfig); task = (ITask)injector.GetInstance(typeof(ITask)); } catch (Exception e) { throw new InvalidOperationException("unable to inject task with configuration: " + taskConfig, e); } byte[] bytes = task.Call(null); string result = System.Text.Encoding.Default.GetString(bytes); //a dir command is executed in the container directory, which includes the file "evaluator.conf" Assert.IsTrue(result.Contains("evaluator.conf")); } [TestMethod, Priority(0), TestCategory("Unit")] [Description("Test driver information extacted from Http server")] public void CanExtractDriverInformaiton() { const string InfoString = "{\"remoteId\":\"socket://10.121.136.231:14272\",\"startTime\":\"2014 08 28 10:50:32\",\"services\":[{\"serviceName\":\"NameServer\",\"serviceInfo\":\"10.121.136.231:16663\"}]}"; AvroDriverInfo info = AvroJsonSerializer<AvroDriverInfo>.FromString(InfoString); Assert.IsTrue(info.remoteId.Equals("socket://10.121.136.231:14272")); Assert.IsTrue(info.startTime.Equals("2014 08 28 10:50:32")); Assert.IsTrue(new DriverInformation(info.remoteId, info.startTime, info.services).NameServerId.Equals("10.121.136.231:16663")); } } }
apache-2.0
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isis_neighbor_attribute/neighbors/neighbor/subTLVs/subTLVs_/max_reservable_link_bandwidth/__init__.py
12596
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListType from pyangbind.lib.yangtypes import YANGDynClass from pyangbind.lib.yangtypes import ReferenceType from pyangbind.lib.base import PybindBase from collections import OrderedDict from decimal import Decimal from bitarray import bitarray import six # PY3 support of some PY2 keywords (needs improved) if six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ from . import state class max_reservable_link_bandwidth(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/isis/levels/level/link-state-database/lsp/tlvs/tlv/mt-isis-neighbor-attribute/neighbors/neighbor/subTLVs/subTLVs/max-reservable-link-bandwidth. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: This container defines sub-TLV 10. """ __slots__ = ("_path_helper", "_extmethods", "__state") _yang_name = "max-reservable-link-bandwidth" _pybind_generated_by = "container" def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__state = YANGDynClass( base=state.state, is_container="container", yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="container", is_config=False, ) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path() + [self._yang_name] else: return [ "network-instances", "network-instance", "protocols", "protocol", "isis", "levels", "level", "link-state-database", "lsp", "tlvs", "tlv", "mt-isis-neighbor-attribute", "neighbors", "neighbor", "subTLVs", "subTLVs", "max-reservable-link-bandwidth", ] def _get_state(self): """ Getter method for state, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isis_neighbor_attribute/neighbors/neighbor/subTLVs/subTLVs/max_reservable_link_bandwidth/state (container) YANG Description: State parameters of sub-TLV 10. """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isis_neighbor_attribute/neighbors/neighbor/subTLVs/subTLVs/max_reservable_link_bandwidth/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: State parameters of sub-TLV 10. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=state.state, is_container="container", yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="container", is_config=False, ) except (TypeError, ValueError): raise ValueError( { "error-string": """state must be of a type compatible with container""", "defined-type": "container", "generated-type": """YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)""", } ) self.__state = t if hasattr(self, "_set"): self._set() def _unset_state(self): self.__state = YANGDynClass( base=state.state, is_container="container", yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="container", is_config=False, ) state = __builtin__.property(_get_state) _pyangbind_elements = OrderedDict([("state", state)]) from . import state class max_reservable_link_bandwidth(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/isis/levels/level/link-state-database/lsp/tlvs/tlv/mt-isis-neighbor-attribute/neighbors/neighbor/subTLVs/subTLVs/max-reservable-link-bandwidth. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: This container defines sub-TLV 10. """ __slots__ = ("_path_helper", "_extmethods", "__state") _yang_name = "max-reservable-link-bandwidth" _pybind_generated_by = "container" def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__state = YANGDynClass( base=state.state, is_container="container", yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="container", is_config=False, ) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path() + [self._yang_name] else: return [ "network-instances", "network-instance", "protocols", "protocol", "isis", "levels", "level", "link-state-database", "lsp", "tlvs", "tlv", "mt-isis-neighbor-attribute", "neighbors", "neighbor", "subTLVs", "subTLVs", "max-reservable-link-bandwidth", ] def _get_state(self): """ Getter method for state, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isis_neighbor_attribute/neighbors/neighbor/subTLVs/subTLVs/max_reservable_link_bandwidth/state (container) YANG Description: State parameters of sub-TLV 10. """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isis_neighbor_attribute/neighbors/neighbor/subTLVs/subTLVs/max_reservable_link_bandwidth/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: State parameters of sub-TLV 10. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=state.state, is_container="container", yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="container", is_config=False, ) except (TypeError, ValueError): raise ValueError( { "error-string": """state must be of a type compatible with container""", "defined-type": "container", "generated-type": """YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)""", } ) self.__state = t if hasattr(self, "_set"): self._set() def _unset_state(self): self.__state = YANGDynClass( base=state.state, is_container="container", yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="container", is_config=False, ) state = __builtin__.property(_get_state) _pyangbind_elements = OrderedDict([("state", state)])
apache-2.0
funasoul/celldesigner-parser
src/org/sbml/_2001/ns/celldesigner/StartingPointInBlockDiagram.java
5766
/******************************************************************************* * Copyright 2016 Kaito Ii, Akira Funahashi * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) // Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source // schema. // Generated on: 2016.05.30 at 07:47:34 PM JST // package org.sbml._2001.ns.celldesigner; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; // TODO: Auto-generated Javadoc /** * Starting point (residue, binding site, operator) of the link. * <p> * Java class for startingPointInBlockDiagram complex type. * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType name="startingPointInBlockDiagram"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="offsetX" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="offsetY" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="residue"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}short"> * &lt;minInclusive value="0"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="bindingSite"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}short"> * &lt;minInclusive value="0"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="operator"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}short"> * &lt;minInclusive value="0"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "startingPointInBlockDiagram") public class StartingPointInBlockDiagram { /** The offset X. */ @XmlAttribute(name = "offsetX", required = true) protected BigDecimal offsetX; /** The offset Y. */ @XmlAttribute(name = "offsetY", required = true) protected BigDecimal offsetY; /** The residue. */ @XmlAttribute(name = "residue") protected Short residue; /** The binding site. */ @XmlAttribute(name = "bindingSite") protected Short bindingSite; /** The operator. */ @XmlAttribute(name = "operator") protected Short operator; /** * Gets the value of the offsetX property. * * @return * possible object is {@link BigDecimal } */ public BigDecimal getOffsetX() { return offsetX; } /** * Sets the value of the offsetX property. * * @param value * allowed object is {@link BigDecimal } */ public void setOffsetX(BigDecimal value) { this.offsetX = value; } /** * Gets the value of the offsetY property. * * @return * possible object is {@link BigDecimal } */ public BigDecimal getOffsetY() { return offsetY; } /** * Sets the value of the offsetY property. * * @param value * allowed object is {@link BigDecimal } */ public void setOffsetY(BigDecimal value) { this.offsetY = value; } /** * Gets the value of the residue property. * * @return * possible object is {@link Short } */ public Short getResidue() { return residue; } /** * Sets the value of the residue property. * * @param value * allowed object is {@link Short } */ public void setResidue(Short value) { this.residue = value; } /** * Gets the value of the bindingSite property. * * @return * possible object is {@link Short } */ public Short getBindingSite() { return bindingSite; } /** * Sets the value of the bindingSite property. * * @param value * allowed object is {@link Short } */ public void setBindingSite(Short value) { this.bindingSite = value; } /** * Gets the value of the operator property. * * @return * possible object is {@link Short } */ public Short getOperator() { return operator; } /** * Sets the value of the operator property. * * @param value * allowed object is {@link Short } */ public void setOperator(Short value) { this.operator = value; } }
apache-2.0
tensorflow/federated
tensorflow_federated/python/simulation/datasets/emnist_test.py
2396
# Copyright 2019, The TensorFlow Federated Authors. # # 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 collections from absl import flags from absl.testing import absltest import tensorflow as tf from tensorflow_federated.python.simulation.datasets import emnist FLAGS = flags.FLAGS EXPECTED_ELEMENT_TYPE = collections.OrderedDict( label=tf.TensorSpec(shape=(), dtype=tf.int32), pixels=tf.TensorSpec(shape=(28, 28), dtype=tf.float32)) class EMNISTTest(tf.test.TestCase, absltest.TestCase): def test_get_synthetic(self): client_data = emnist.get_synthetic() self.assertLen(client_data.client_ids, 1) self.assertEqual(client_data.element_type_structure, EXPECTED_ELEMENT_TYPE) for client_id in client_data.client_ids: data = self.evaluate( list(client_data.create_tf_dataset_for_client(client_id))) images = [x['pixels'] for x in data] labels = [x['label'] for x in data] self.assertLen(labels, 10) self.assertCountEqual(labels, list(range(10))) self.assertLen(images, 10) self.assertEqual(images[0].shape, (28, 28)) self.assertEqual(images[-1].shape, (28, 28)) def test_load_from_gcs(self): self.skipTest( "CI infrastructure doesn't support downloading from GCS. Remove " 'skipTest to run test locally.') def run_test(only_digits: bool, expect_num_clients): train, test = emnist.load_data(only_digits, cache_dir=FLAGS.test_tmpdir) self.assertLen(train.client_ids, expect_num_clients) self.assertLen(test.client_ids, expect_num_clients) self.assertEqual(train.element_type_structure, EXPECTED_ELEMENT_TYPE) self.assertEqual(test.element_type_structure, EXPECTED_ELEMENT_TYPE) with self.subTest('only_digits'): run_test(True, 3383) with self.subTest('all'): run_test(False, 3400) if __name__ == '__main__': tf.test.main()
apache-2.0
mwasiluk/angular-surveys
src/builder/focus-me.directive.js
988
angular.module('mwFormBuilder') .directive('wdFocusMe', function($timeout, $parse) { return { link: function(scope, element, attrs) { var model = $parse(attrs.wdFocusMe); scope.$watch(model, function(value) { if(value === true) { $timeout(function() { element[0].focus(); }); } }); element.bind('blur', function() { $timeout(function() { scope.$apply(model.assign(scope, false)); }); }); } }; }) .factory('focus', function($timeout, $window) { return function(id) { $timeout(function() { var element = $window.document.getElementById(id); if(element) element.focus(); }); }; });
apache-2.0
blackberry/hadoop-logdriver
src/main/java/com/rim/logdriver/util/CatByTime.java
3264
/** Copyright 2013 BlackBerry, 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. */ /** * Search Logs in a given time range, based on the logdriver file structure. * <p> * Usage: [genericOptions] searchString baseDir filePrefix startTime endTime output * <p> * For example: -Djob.wait=true 'ERR=12345678' /service/web/logs app 1332939045000 1332942648000 /user/me/grep * */ package com.rim.logdriver.util; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rim.logdriver.fs.FileManager; import com.rim.logdriver.fs.PathInfo; public class CatByTime extends Configured implements Tool { private static final Logger LOG = LoggerFactory.getLogger(CatByTime.class); @Override public int run(String[] args) throws Exception { Configuration conf = getConf(); // Configuration processed by ToolRunner List<String> searchArgs = new ArrayList<String>(); if (args.length < 6) { System.out.println("Usage: " + this.getClass().getSimpleName() + " DC SVC COMP START END OUT"); } String dcNumber = args[0]; String service = args[1]; String component = args[2]; long startTime = Long.parseLong(args[3]); long endTime = Long.parseLong(args[4]); String output = args[5]; // Add the start and end time to the configuration conf.setLong("logdriver.search.start.time", startTime); conf.setLong("logdriver.search.end.time", endTime); // Get paths FileManager fm = new FileManager(conf); List<PathInfo> paths = fm.getPathInfo(dcNumber, service, component, startTime, endTime); if (paths.isEmpty()) { System.err .println("No logs found for the given component(s) and time range."); return 1; } int retval = 99; try { // Lock, then get the real paths fm.acquireReadLocks(paths); for (PathInfo pi : paths) { LOG.info("Adding path: {}", pi.getFullPath()); searchArgs.addAll(fm.getInputPaths(pi)); } // The last arg is output directory searchArgs.add(output); // Now run Cat LOG.info("Sending args to Cat: {}", searchArgs); retval = ToolRunner.run(conf, new Cat(), searchArgs.toArray(new String[0])); } finally { fm.releaseReadLocks(paths); } return retval; } public static void main(String[] args) throws Exception { // Let ToolRunner handle generic command-line options int res = ToolRunner.run(new Configuration(), new CatByTime(), args); System.exit(res); } }
apache-2.0
kidaa/any23
core/src/main/java/org/apache/any23/writer/RDFXMLWriterFactory.java
1631
/* * 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.any23.writer; import java.io.OutputStream; import org.openrdf.rio.RDFFormat; /** * @author Peter Ansell p_ansell@yahoo.com * */ public class RDFXMLWriterFactory implements WriterFactory { public static final String MIME_TYPE = RDFFormat.RDFXML.getDefaultMIMEType(); public static final String IDENTIFIER = "rdfxml"; /** * */ public RDFXMLWriterFactory() { } @Override public RDFFormat getRdfFormat() { return RDFFormat.RDFXML; } @Override public String getIdentifier() { return RDFXMLWriterFactory.IDENTIFIER; } @Override public String getMimeType() { return RDFXMLWriterFactory.MIME_TYPE; } @Override public FormatWriter getRdfWriter(OutputStream os) { return new RDFXMLWriter(os); } }
apache-2.0
arjuna-technologies/FileSystem_DataBroker_PlugIn
filesystem-file/src/main/java/com/arjuna/dbplugins/filesystem/file/FileChangeDataSource.java
5312
/* * Copyright (c) 2014-2015, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved. */ package com.arjuna.dbplugins.filesystem.file; import java.io.File; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.WatchEvent.Kind; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.arjuna.databroker.data.DataFlow; import com.arjuna.databroker.data.DataProvider; import com.arjuna.databroker.data.DataSource; import com.arjuna.databroker.data.jee.annotation.DataProviderInjection; import com.arjuna.databroker.data.jee.annotation.PreActivated; import com.arjuna.databroker.data.jee.annotation.PreDeactivated; public class FileChangeDataSource implements DataSource { private static final Logger logger = Logger.getLogger(FileChangeDataSource.class.getName()); public static final String FILENAME_PROPERYNAME = "File Name"; public FileChangeDataSource() { logger.log(Level.FINE, "FileChangeDataSource"); } public FileChangeDataSource(String name, Map<String, String> properties) { logger.log(Level.FINE, "FileChangeDataSource: " + name + ", " + properties); _name = name; _properties = properties; } @Override public DataFlow getDataFlow() { return _dataFlow; } @Override public void setDataFlow(DataFlow dataFlow) { _dataFlow = dataFlow; } @Override public String getName() { return _name; } @Override public void setName(String name) { _name = name; } @Override public Map<String, String> getProperties() { return Collections.unmodifiableMap(_properties); } @Override public void setProperties(Map<String, String> properties) { _properties = properties; } @Override public Collection<Class<?>> getDataProviderDataClasses() { Set<Class<?>> dataProviderDataClasses = new HashSet<Class<?>>(); dataProviderDataClasses.add(File.class); return dataProviderDataClasses; } @Override @SuppressWarnings("unchecked") public <T> DataProvider<T> getDataProvider(Class<T> dataClass) { if (dataClass == File.class) return (DataProvider<T>) _dataProvider; else return null; } @PreActivated public void start() { _watcher = new Watcher(new File(_properties.get(FILENAME_PROPERYNAME))); _watcher.start(); } @PreDeactivated public void finish() { _watcher.finish(); } private class Watcher extends Thread { public Watcher(File file) { _finish = false; _filePath = file.toPath().toAbsolutePath(); _directoryPath = file.getParentFile().toPath().toAbsolutePath(); } @Override public void run() { try { WatchService watchService = FileSystems.getDefault().newWatchService(); _directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY); while (! _finish) { WatchKey watchKey = watchService.take(); if (watchKey != null) { for (WatchEvent<?> watchEvent : watchKey.pollEvents()) { Kind<?> kind = watchEvent.kind(); Path context = _directoryPath.resolve((Path) watchEvent.context()); if (context.equals(_filePath) && ((kind == StandardWatchEventKinds.ENTRY_CREATE) || (kind == StandardWatchEventKinds.ENTRY_MODIFY))) _dataProvider.produce(context.toFile()); } if (! watchKey.reset()) _finish = true; } } watchService.close(); } catch (InterruptedException interruptedException) { } catch (Throwable throwable) { logger.log(Level.WARNING, "Problem while watching file", throwable); } } public void finish() { try { _finish = true; this.interrupt(); this.join(); } catch (Throwable throwable) { logger.log(Level.WARNING, "Problem during file watcher shutdown", throwable); } } private Path _filePath; private Path _directoryPath; private boolean _finish; } private DataFlow _dataFlow; private String _name; private Map<String, String> _properties; @DataProviderInjection private DataProvider<File> _dataProvider; private Watcher _watcher; }
apache-2.0
interhui/logmesh
logmesh-starter/src/main/java/org/pinae/logmesh/server/builder/MessageServerBuilder.java
11153
package org.pinae.logmesh.server.builder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.pinae.ndb.Ndb; /** * 消息服务配置信息构建器 * * @author Huiyugeng * */ public class MessageServerBuilder { private Map<String, Object> serverConfig = new HashMap<String, Object>(); public static final String RECEIVER_UDP = "udp"; public static final String RECEIVER_TCP = "tcp"; public static final String RECEIVER_JMS = "jms"; public static final String RECEIVER_KAFKA = "kafka"; /** * 获得消息服务配置信息 * * @return 消息服务配置信息 */ @SuppressWarnings("unchecked") public Map<String, Object> build() { if (serverConfig.containsKey("server")) { return (Map<String, Object>) serverConfig.get("server"); } return serverConfig; } /** * 设置消息服务所有者 * * @param owner 服务所有者 */ public void setOwner(String owner) { Object result = Ndb.execute(serverConfig, "select:server->owner"); if (result instanceof List && ((List<?>) result).size() > 0) { Ndb.execute(serverConfig, String.format("update:server->owner:%s !! owner=%s", owner, owner)); } else { Ndb.execute(serverConfig, String.format("insert:server !! owner=%s", owner)); } } /** * 增加消息队列,当消息队列存在时更新消息队列的长度 * * @param name 消息队列名称 * @param size 消息队列长度 */ public void addQueue(String name, long size) { Object result = Ndb.execute(serverConfig, String.format("select:server->queue->name:%s", name)); if (result instanceof List && ((List<?>) result).size() > 0) { Ndb.execute(serverConfig, String.format("update:server->queue->name:%s !! size=%s", name, Long.toString(size))); } else { Ndb.execute(serverConfig, String.format("insert:server->queue !! name=%s, size=%s", name, Long.toString(size))); } } /** * 设置线程管理 * * @param type 线程管理类型:filter 过滤器,router 路由, processor 自定义处理器 * @param count 线程数量 * @param delay 线程延迟时间(ms),通常为100 */ public void setThread(String type, int count, long delay) { Object result = Ndb.execute(serverConfig, String.format("select:server->thread->%s", type)); if (result instanceof List && ((List<?>) result).size() > 0) { Ndb.execute(serverConfig, String.format("update:server->thread->%s !! count=%s, delay=%s", type, Integer.toString(count), Long.toString(delay))); } else { Ndb.execute(serverConfig, String.format("insert:server->thread->%s !! count=%s, delay=%s", type, Integer.toString(count), Long.toString(delay))); } } /** * 是否启用消息归并 * * @param active 启动标记 true 启用 false 禁用 * @param cycle 消息归并周期(ms) */ public void activeMerger(boolean active, long cycle) { Object result = Ndb.execute(serverConfig, "select:server->merger"); if (result instanceof List && ((List<?>) result).size() > 0) { Ndb.execute(serverConfig, String.format("update:server->merger !! enable=%s, cycle=%s", Boolean.toString(active), Long.toString(cycle))); } else { Ndb.execute(serverConfig, String.format("insert:server->merger !! enable=%s, cycle=%s", Boolean.toString(active), Long.toString(cycle))); } } /** * 增加消息接收器 * * @param type 接收器类型 * @param active 是否激活接收器 * @param original 是否采集原始消息 * @param codec 编码模式 * @param parameters 接收器参数 */ public void addReceiver(String type, boolean active, boolean original, String codec, Map<String, Object> parameters) { Object result = Ndb.execute(serverConfig, String.format("select:server->receiver->type:%s", type)); if (result instanceof List && ((List<?>) result).size() > 0) { Ndb.execute(serverConfig, String.format("update:server->receiver->type:%s !! enable=%s, original=%s, codec=%s", type, Boolean.toString(active), Boolean.toString(original), codec)); } else { Ndb.execute(serverConfig, String.format("insert:server->receiver !! type=%s, enable=%s, original=%s, codec=%s", type, Boolean.toString(active), Boolean.toString(original), codec)); } Object receiver = Ndb.execute(serverConfig, String.format("one:server->receiver->type:%s", type)); if (receiver instanceof Map) { Map<?, ?> receiverMap = (Map<?, ?>) receiver; setParameter(receiverMap, parameters); } } /** * 设置消息计数器 * * @param parameters 消息计数器参数 */ public void setCounter(Map<String, Object> parameters) { Object result = Ndb.execute(serverConfig, "select:server->counter"); if (result instanceof List && ((List<?>) result).size() == 0) { Ndb.execute(serverConfig, String.format("insert:server->counter")); } Object counter = Ndb.execute(serverConfig, "one:server->counter"); if (counter instanceof Map) { Map<?, ?> counterMap = (Map<?, ?>) counter; setParameter(counterMap, parameters); } } /** * 设置原始消息参数 * * @param parameters 原始消息参数 */ public void setOriginal(Map<String, Object> parameters) { Object result = Ndb.execute(serverConfig, "select:server->original"); if (result instanceof List && ((List<?>) result).size() == 0) { Ndb.execute(serverConfig, String.format("insert:server->original")); } Object original = Ndb.execute(serverConfig, "one:server->original"); if (original instanceof Map) { Map<?, ?> originalMap = (Map<?, ?>) original; setParameter(originalMap, parameters); } } /** * 增加消息过滤器 * * @param startup 启动顺序 * @param name 过滤器名称 * @param active 是否启用过滤器 * @param filterClass 过滤器执行类 * @param parameters 过滤器参数 */ public void addFilter(int startup, String name, boolean active, String filterClass, Map<String, Object> parameters) { Object result = Ndb.execute(serverConfig, String.format("select:server->filter->name:%s", name)); if (result instanceof List && ((List<?>) result).size() > 0) { Ndb.execute(serverConfig, String.format("update:server->filter->name:%s !! startup=%s, enable=%s, kwClass=%s", name, Integer.toString(startup), Boolean.toString(active), filterClass)); } else { Ndb.execute(serverConfig, String.format("insert:server->filter !! name=%s, startup=%s, enable=%s, kwClass=%s", name, Integer.toString(startup), Boolean.toString(active), filterClass)); } Object filter = Ndb.execute(serverConfig, String.format("one:server->filter->name:%s", name)); if (filter instanceof Map) { setParameter((Map<?, ?>) filter, parameters); } } public void addFilter(int startup, String name, boolean active, Class<?> filterClass, Map<String, Object> parameters) { addFilter(startup, name, active, filterClass.getName(), parameters); } /** * 增加消息处理器 * * @param name 处理器名称 * @param active 是否启用处理器 * @param processorClass 处理器执行类 * @param parameters 处理器参数 */ public void addProcessor(String name, boolean active, String processorClass, Map<String, Object> parameters) { Object result = Ndb.execute(serverConfig, String.format("select:server->processor->name:%s", name)); if (result instanceof List && ((List<?>) result).size() > 0) { Ndb.execute(serverConfig, String.format("update:server->processor->name:%s !! enable=%s, kwClass=%s", name, Boolean.toString(active), processorClass)); } else { Ndb.execute(serverConfig, String.format("insert:server->processor !! name=%s, enable=%s, kwClass=%s", name, Boolean.toString(active), processorClass)); } Object processor = Ndb.execute(serverConfig, String.format("one:server->processor->name:%s", name)); if (processor instanceof Map) { setParameter((Map<?, ?>) processor, parameters); } } public void addProcessor(String name, boolean active, Class<?> processorClass, Map<String, Object> parameters) { addProcessor(name, active, processorClass.getName(), parameters); } /** * 增加消息路由器 * * @param name 路由器名称 * @param active 是否启用路由器 * @param routerClass 路由器执行类 * @param parameters 路由器参数 */ public void addRouter(String name, boolean active, String routerClass, Map<String, Object> parameters) { Object result = Ndb.execute(serverConfig, String.format("select:server->router->name:%s", name)); if (result instanceof List && ((List<?>) result).size() > 0) { Ndb.execute(serverConfig, String.format("update:server->router->name:%s !! enable=%s, kwClass=%s", name, Boolean.toString(active), routerClass)); } else { Ndb.execute(serverConfig, String.format("insert:server->router !! name=%s, enable=%s, kwClass=%s", name, Boolean.toString(active), routerClass)); } Object router = Ndb.execute(serverConfig, String.format("one:server->router->name:%s", name)); if (router instanceof Map) { setParameter((Map<?, ?>) router, parameters); } } public void addRouter(String name, boolean active, Class<?> routerClass, Map<String, Object> parameters) { addRouter(name, active, routerClass.getName(), parameters); } /** * 增加消息输出器 * * @param name 消息输出器名称 * @param active 是否启用该消息输出器 * @param outputClass 消息输出器执行类 * @param parameters 消息输出器参数 */ public void addOutputor(String name, boolean active, String outputClass, Map<String, Object> parameters) { Object result = Ndb.execute(serverConfig, String.format("select:server->outputor->name:%s", name)); if (result instanceof List && ((List<?>) result).size() > 0) { Ndb.execute(serverConfig, String.format("update:server->outputor->name:%s !! enable=%s, kwClass=%s", name, Boolean.toString(active), outputClass)); } else { Ndb.execute(serverConfig, String.format("insert:server->outputor !! name=%s, enable=%s, kwClass=%s", name, Boolean.toString(active), outputClass)); } Object output = Ndb.execute(serverConfig, String.format("one:server->outputor->name:%s", name)); if (output instanceof Map) { setParameter((Map<?, ?>) output, parameters); } } public void addOutputor(String name, boolean active, Class<?> outputClass, Map<String, Object> parameters) { addOutputor(name, active, outputClass.getName(), parameters); } /* * 参数转换 * 将K-V格式的参数列表转换为参数列表 */ @SuppressWarnings({ "rawtypes", "unchecked" }) private Map<?, ?> setParameter(Map target, Map<String, Object> parameters) { if (parameters != null) { List<Map<?, ?>> paramList = new ArrayList<Map<?, ?>>(); Set<String> keySet = parameters.keySet(); for (String key : keySet) { Object value = parameters.get(key); Map<String, Object> param = new HashMap<String, Object>(); param.put("key", key); param.put("value", value); paramList.add(param); } Map params = new HashMap(); params.put("parameter", paramList); target.put("parameters", params); } return target; } }
apache-2.0
mobilecashout/osprey
src/main/java/com/mobilecashout/osprey/project/config/BuildCommand.java
1294
/* * Copyright 2016 Innovative Mobile Solutions Limited and contributors * * 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.mobilecashout.osprey.project.config; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class BuildCommand { @SerializedName("prepare") private ArrayList<String> prepareCommands; @SerializedName("success") private ArrayList<String> successCommands; @SerializedName("failure") private ArrayList<String> failureCommands; public ArrayList<String> prepareCommands() { return prepareCommands; } public ArrayList<String> successCommands() { return successCommands; } public ArrayList<String> failureCommands() { return failureCommands; } }
apache-2.0
innowatio/iwwa-write-api
src/api/meter-reports/index.js
280
import collection from "lk-collection-convexpress"; import dispatchEvent from "services/dispatcher"; import * as authorize from "./authorize"; import schema from "./schema"; export default collection({ name: "meter-reports", dispatchEvent, authorize, schema });
apache-2.0
nuest/iceland
statistics/core/src/main/java/org/n52/iceland/statistics/api/parameters/ElasticsearchTypeRegistry.java
3472
/* * Copyright 2015 52°North Initiative for Geospatial Open Source * Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.iceland.statistics.api.parameters; import java.util.Map; import com.google.common.collect.ImmutableMap; public class ElasticsearchTypeRegistry { public final static ElasticsearchType stringField = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "string", "index", "not_analyzed")); public final static ElasticsearchType stringAnalyzedField = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "string", "index", "analyzed")); public final static ElasticsearchType dateField = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "date")); public final static ElasticsearchType integerField = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "integer")); public final static ElasticsearchType longField = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "long")); public final static ElasticsearchType doubleField = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "double")); public final static ElasticsearchType booleanField = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "boolean")); public final static ElasticsearchType ipv4Field = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "ip")); public final static ElasticsearchType geoPointField = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "geo_point")); public final static ElasticsearchType geoShapeField = new ElasticsearchType(ImmutableMap.<String, Object> of("type", "geo_shape", "precision", "1km")); public static class ElasticsearchType { private final Map<String, Object> type; public ElasticsearchType(Map<String, Object> type) { this.type = type; } public Map<String, Object> getType() { return type; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ElasticsearchType other = (ElasticsearchType) obj; if (type == null) { if (other.type != null) { return false; } } else if (!type.equals(other.type)) { return false; } return true; } public String humanReadableType() { return type.get("type").toString(); } } }
apache-2.0
csosa2/my-pwp
public_html/documentation/milestone-2.php
2278
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>Milestone 2</title> </head> <body> <header> <h1>Milestone 2</h1> <h2>Personal Web site: Christina Sosa</h2> </header> <main> <h2>Sitemap</h2> <p>This personal web site will contain 4 page-level pages total using a scroll down method instead of individual pages. No sub-pages or sub-navigation will be used. This will be the Minimum Viable Product. The web site will contain the following pages: </p> <ul> <li>Home</li> <li>About Me</li> <li>Portfolio</li> <li>Contact</li> </ul> <h2>Content Strategy</h2> <p><strong>Home: </strong> This page will include a large background image with my name and role as a Web Developer within the image area. It will feature three calls to action that will direct the user to the About me, Portfolio or Contact.</p> <p><strong>About Me: </strong>The page will describe some personal facts, professional history, core skill set and professional highlights. It will show a clear reflection of my professional strengths and personality. This page might contain a link to a PDF version of my resume.</p> <p><strong>Portfolio: </strong>This section will showcase 2-5 examples of my past projects procurred in the Deep Dive Coding Bootcamp and any future work. This will be a responsive image gallery linking to all my projects.</p> <p><strong>Contact:</strong>This page will feature a simple contact form with name, email, subject and message. </p> <h3>Interaction Flow</h3> <img src="../images/pwpInteractionFlow.svg" alt="Interaction Flow" height="40%" width="40%"> <h2>Wireframes</h2> <p>The site will feature 2 layouts:</p> <ol> <li>Home Page Layout</li> <li>Content Page Layout</li> </ol> <h3>Home Page Layout: Mobile</h3> <img src="../images/pwp-home-mobile.png" alt="Mobile Home Page"> <h3>Content Page Layout: Mobile</h3> <img src="../images/pwp-content-mobile.png" alt="Mobile Content Page"> <h3>Home Page Layout: Desktop</h3> <img src="../images/pwp-home-desktop.png" alt="Desktop Home Page"> <h3>Content Page Layout: Desktop</h3> <img src="../images/pwp-content-desktop.png" alt="Desktop Content Page"> </main> </body> </html>
apache-2.0
hmtsoi/java_play_sax
src/main/java/sax/data/transform/RScriptMethods.java
2927
/* * Copyright 2015 - Hung Ming Tsoi * * 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 sax.data.transform; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class RScriptMethods { protected RScriptMethods() { // Utility class } final private static String RDirectory = "tmp"; final private static Charset CHARSET = Charset.forName("UTF-8"); final private static Logger logger = LoggerFactory .getLogger(RScriptMethods.class); static String createRScript(SaxRepresentationImpl saxRepresentation) throws IOException { if (!Files.exists(Paths.get(RDirectory))) { new File(RDirectory).mkdir(); } final String timestamp = String.valueOf(System.currentTimeMillis()); final String filepath = String.format("%s/script_%s", RDirectory, timestamp); try (BufferedWriter writer = Files.newBufferedWriter( Paths.get(filepath), CHARSET)) { saxRepresentation.writeRScript(writer); } new File(filepath).setExecutable(true); return filepath; } static void runRScriptToGetBreakpoints(final String filepath, final List<Double> breakpoints) throws IOException, InterruptedException { final String rCommand = String.format("./%s", filepath); final Process callRscript = Runtime.getRuntime().exec(rCommand); final Runnable runReadThread = new Runnable() { @Override public void run() { try (BufferedReader input = new BufferedReader( new InputStreamReader(callRscript.getInputStream()))) { getBreakpointsFromR(input, breakpoints); } catch (IOException e) { logger.error(e.getMessage(), e); } } }; final Thread readThread = new Thread(runReadThread); readThread.start(); callRscript.waitFor(); } private static void getBreakpointsFromR(final BufferedReader input, final List<Double> breakPoints) throws IOException { breakPoints.add(Double.NEGATIVE_INFINITY); String line = null; while ((line = input.readLine()) != null) { final String breakpointStr = line.split(" ")[1]; final Double breakpoint = Double.parseDouble(breakpointStr); breakPoints.add(breakpoint); } breakPoints.add(Double.POSITIVE_INFINITY); } }
apache-2.0
moparisthebest/beehive
beehive-netui-compiler/src/main/java/org/apache/beehive/netui/compiler/BaseChecker.java
2361
/* * 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. * * $Header:$ */ package org.apache.beehive.netui.compiler; import org.apache.beehive.netui.compiler.typesystem.declaration.ClassDeclaration; import org.apache.beehive.netui.compiler.typesystem.env.CoreAnnotationProcessorEnv; import java.util.Map; public abstract class BaseChecker { private CoreAnnotationProcessorEnv _env; private Diagnostics _diagnostics; private RuntimeVersionChecker _runtimeVersionChecker; private SourceFileInfo _sourceFileInfo; protected BaseChecker( CoreAnnotationProcessorEnv env, SourceFileInfo sourceFileInfo, Diagnostics diagnostics ) { _env = env; _diagnostics = diagnostics; _sourceFileInfo = sourceFileInfo; } public Map check( ClassDeclaration jclass ) throws FatalCompileTimeException { setRuntimeVersionChecker( new RuntimeVersionChecker() ); return onCheck( jclass ); } public abstract Map onCheck( ClassDeclaration jclass ) throws FatalCompileTimeException; protected CoreAnnotationProcessorEnv getEnv() { return _env; } protected Diagnostics getDiagnostics() { return _diagnostics; } protected RuntimeVersionChecker getRuntimeVersionChecker() { return _runtimeVersionChecker; } protected void setRuntimeVersionChecker( RuntimeVersionChecker runtimeVersionChecker ) { _runtimeVersionChecker = runtimeVersionChecker; } protected SourceFileInfo getSourceFileInfo() { return _sourceFileInfo; } }
apache-2.0
eemirtekin/Sakai-10.6-TR
kernel/api/src/main/java/org/sakaiproject/entity/api/Summary.java
1649
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/kernel/tags/sakai-10.6/api/src/main/java/org/sakaiproject/entity/api/Summary.java $ * $Id: Summary.java 105077 2012-02-24 22:54:29Z ottenhoff@longsight.com $ *********************************************************************************** * * Copyright (c) 2007, 2008 Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.entity.api; import java.io.Serializable; /** * <p> * Summary is a Map that represents an RSS feed item * </p> */ public interface Summary extends Serializable { /** Property for Publication date (RFC822) */ static final String PROP_PUBDATE = "RSS:pubdate"; /** Property for Title */ static final String PROP_TITLE = "RSS:title"; /** Property for Description */ static final String PROP_DESCRIPTION = "RSS:description"; /** Property for Link */ static final String PROP_LINK = "RSS:link"; }
apache-2.0
SATL/AlgorithmsJava
src/unionfind/WQuickUnionUF.java
1105
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package unionfind; /** * * @author eslem */ public class WQuickUnionUF { private int[] ids; private int[] sizes; public WQuickUnionUF(int N) { ids = new int[N]; sizes = new int[N]; for (int i = 0; i < N; i++) { ids[i] = i; sizes[i] = 1; } } private int getRoot(int i) { while (i != ids[i]) { i = ids[i]; } return i; } public boolean isConnected(int p, int q) { return getRoot(p) == getRoot(q); } public void union(int p, int q) { int i = getRoot(p); int j = getRoot(q); if (i == j) { return; } if (sizes[i] < sizes[j]) { ids[i] = j; sizes[j] += sizes[i]; } else { ids[j] = i; sizes[i] += sizes[j]; } } }
apache-2.0
ithander/frame
src/main/java/org/ithang/tools/model/auth/AuthRealm.java
3706
package org.ithang.tools.model.auth; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.shiro.authc.AccountException; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.ithang.system.role.bean.Role; import org.ithang.system.user.bean.User; import org.ithang.system.user.service.UserService; import org.ithang.system.userResource.bean.UserResource; import org.ithang.system.userResource.service.UserResourceService; import org.ithang.system.userRole.bean.UserRole; import org.ithang.system.userRole.service.UserRoleService; import org.springframework.beans.factory.annotation.Autowired; public class AuthRealm extends AuthorizingRealm{ @Autowired private UserService userService; @Autowired private UserRoleService userRoleService; @Autowired private UserResourceService userResourceService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //通过用户名从数据库获取角色权限集 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); User user = (User) getAvailablePrincipal(principalCollection); if(null!=user){ List<UserRole> userRoles=userRoleService.listByUser(user.getId()); if(null!=userRoles&&!userRoles.isEmpty()){ Set<String> roles = new HashSet<>(); for(UserRole uRole:userRoles){ roles.add(uRole.getRole_id()); } info.setRoles(roles);; } List<UserResource> userResources=userResourceService.listByUser(user.getId()); if(null!=userResources&&!userResources.isEmpty()){ Set<String> resources = new HashSet<>(); for(UserResource uResource:userResources){ resources.add(uResource.getResource_id()); } info.setStringPermissions(resources); } } return info; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { //加这一步的目的是在Post请求的时候会先进认证,然后在到请求 if (null==authenticationToken.getPrincipal()) { return null; } UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; //获取用户信息 String mobile = token.getUsername(); User user = userService.getByMobile(mobile); if(null==user){ user=userService.getByName(mobile); } if(null==user){ throw new AccountException("用户名不正确"); } String password = user.getUpass(); if (null == password) { throw new AccountException("用户名不正确"); } else if (!password.equals(new String((char[]) token.getCredentials()))) { throw new AccountException("密码不正确"); } //这里验证authenticationToken和simpleAuthenticationInfo的信息 SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getUpass(), user.getUname()); return simpleAuthenticationInfo; } }
apache-2.0
chacaa/DoApp
app/src/main/java/com/xmartlabs/scasas/doapp/controller/AuthController.java
858
package com.xmartlabs.scasas.doapp.controller; import android.support.annotation.NonNull; import com.xmartlabs.scasas.doapp.model.AuthResponse; import com.xmartlabs.scasas.doapp.model.LoginRequest; import com.xmartlabs.scasas.doapp.model.Session; import com.xmartlabs.scasas.doapp.service.AuthService; import javax.inject.Inject; import rx.Single; /** * Created by santiago on 01/03/16. */ public class AuthController extends ServiceController { @Inject AuthService authService; @Inject SessionController sessionController; public Single<Session> login(LoginRequest loginRequest) { // TODO //authService.login(); return Single.just(new AuthResponse()) .flatMap(sessionController::setSession) .doOnSuccess(this::setLoginInfo); } public void setLoginInfo(@NonNull Session session) { // TODO } }
apache-2.0
udotdevelopment/ATSPM
MOE.Common/Business/ApproachSpeed/SpeedExportApproachDirection.cs
2726
using System; using System.Collections.Generic; using System.Linq; using MOE.Common.Models; namespace MOE.Common.Business { public class SpeedExportApproachDirection { //private Data.MOE.SpeedDataTable speedTable; public SpeedExportAvgSpeedCollection AvgSpeeds; public List<RedToRedCycle> Cycles = new List<RedToRedCycle>(); private readonly SPM db = new SPM(); private List<Speed_Events> speedTable = new List<Speed_Events>(); /// <summary> /// Constructor for Signal phase /// </summary> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="signalId"></param> /// <param name="eventData1"></param> /// <param name="region"></param> /// <param name="detChannel"></param> public SpeedExportApproachDirection(DateTime startDate, DateTime endDate, string signalId, int eventData1, string detID, string dir, int pMph, int movementdelay, int decisionpoint, int binSize, int minspeedfilter, int distancefromstopbar) { Direction = dir; Phase = eventData1; MovementDelay = movementdelay; MinSpeedFilter = minspeedfilter; DistanceFromStopBar = distancefromstopbar; DistanceFromStopBar = distancefromstopbar; GetSpeedTable(detID, startDate, endDate); GetAverageSpeeds(startDate, endDate, binSize, minspeedfilter, MovementDelay, decisionpoint, signalId, eventData1); } public string Direction { get; } public int Phase { get; } public int MovementDelay { get; } public int DistanceFromStopBar { get; } public int MinSpeedFilter { get; } private void GetSpeedTable(string detID, DateTime startDate, DateTime endDate) { //Data.MOETableAdapters.SpeedTableAdapter adapter = new Data.MOETableAdapters.SpeedTableAdapter(); speedTable = (from r in db.Speed_Events where r.DetectorID == detID && r.timestamp > startDate && r.timestamp < endDate select r).ToList(); } private void GetAverageSpeeds(DateTime startDate, DateTime endDate, int binSize, int minSpeedFilter, int movementDelay, int decisionPoint, string signalId, int phaseNumber) { var signaltable = new ControllerEventLogs(signalId, startDate, endDate, phaseNumber, new List<int> {1, 8, 10}); AvgSpeeds = new SpeedExportAvgSpeedCollection(startDate, endDate, binSize, minSpeedFilter, Cycles); } } }
apache-2.0
abates/AdventOfCode
2017/graph/graph.go
1180
package graph type Edge struct { ID string Vertex1 *Vertex Vertex2 *Vertex } type Vertex struct { ID string Edges []*Edge } func NewVertex(id string) *Vertex { return &Vertex{ID: id} } func (v *Vertex) Connect(other *Vertex) *Edge { edge := &Edge{Vertex1: v, Vertex2: other} v.Edges = append(v.Edges, edge) other.Edges = append(other.Edges, edge) return edge } func (v *Vertex) Connected() map[string]*Vertex { visited := make(map[string]*Vertex) visited[v.ID] = v queue := []*Vertex{v} for len(queue) > 0 { current := queue[0] queue = queue[1:] for _, edge := range current.Edges { for _, vertex := range []*Vertex{edge.Vertex1, edge.Vertex2} { if vertex != current { if _, found := visited[vertex.ID]; !found { queue = append(queue, vertex) visited[vertex.ID] = vertex } } } } } return visited } type Graph struct { Vertices map[string]*Vertex } func New() *Graph { return &Graph{ Vertices: make(map[string]*Vertex), } } func (g *Graph) FindOrCreateVertex(id string) *Vertex { vertex, found := g.Vertices[id] if !found { vertex = &Vertex{ID: id} g.Vertices[id] = vertex } return vertex }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-simpleworkflow/src/main/java/com/amazonaws/services/simpleworkflow/model/transform/WorkflowExecutionCompletedEventAttributesJsonUnmarshaller.java
3368
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simpleworkflow.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.simpleworkflow.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * WorkflowExecutionCompletedEventAttributes JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class WorkflowExecutionCompletedEventAttributesJsonUnmarshaller implements Unmarshaller<WorkflowExecutionCompletedEventAttributes, JsonUnmarshallerContext> { public WorkflowExecutionCompletedEventAttributes unmarshall(JsonUnmarshallerContext context) throws Exception { WorkflowExecutionCompletedEventAttributes workflowExecutionCompletedEventAttributes = new WorkflowExecutionCompletedEventAttributes(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("result", targetDepth)) { context.nextToken(); workflowExecutionCompletedEventAttributes.setResult(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("decisionTaskCompletedEventId", targetDepth)) { context.nextToken(); workflowExecutionCompletedEventAttributes.setDecisionTaskCompletedEventId(context.getUnmarshaller(Long.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return workflowExecutionCompletedEventAttributes; } private static WorkflowExecutionCompletedEventAttributesJsonUnmarshaller instance; public static WorkflowExecutionCompletedEventAttributesJsonUnmarshaller getInstance() { if (instance == null) instance = new WorkflowExecutionCompletedEventAttributesJsonUnmarshaller(); return instance; } }
apache-2.0
waans11/incubator-asterixdb
hyracks-fullstack/hyracks/hyracks-tests/hyracks-storage-am-lsm-btree-test/src/test/java/org/apache/hyracks/storage/am/lsm/btree/perf/InMemorySortRunner.java
6722
/* * 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.hyracks.storage.am.lsm.btree.perf; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.concurrent.ConcurrentSkipListSet; import org.apache.hyracks.api.dataflow.value.ITypeTraits; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference; import org.apache.hyracks.storage.am.common.datagen.DataGenThread; import org.apache.hyracks.storage.am.common.datagen.TupleBatch; import org.apache.hyracks.storage.am.common.ophelpers.MultiComparator; import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleReference; import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleWriter; import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleWriterFactory; public class InMemorySortRunner implements IExperimentRunner { public class TupleComparator implements Comparator<ITupleReference> { private final MultiComparator cmp; public TupleComparator(MultiComparator cmp) { this.cmp = cmp; } @Override public int compare(ITupleReference o1, ITupleReference o2) { try { return cmp.compare(o1, o2); } catch (HyracksDataException e) { throw new IllegalArgumentException(e); } } } private final TupleComparator tupleCmp; private final int numBatches; private final int batchSize; private final int tupleSize; private final ITypeTraits[] typeTraits; private final TypeAwareTupleWriterFactory tupleWriterFactory; private final TypeAwareTupleWriter tupleWriter; private final ArrayList<TypeAwareTupleReference> tuples; private final ByteBuffer tupleBuf; public InMemorySortRunner(int numBatches, int batchSize, int tupleSize, ITypeTraits[] typeTraits, MultiComparator cmp) { this.numBatches = numBatches; this.tupleSize = tupleSize; this.batchSize = batchSize; this.typeTraits = typeTraits; tupleCmp = new TupleComparator(cmp); tupleWriterFactory = new TypeAwareTupleWriterFactory(typeTraits); tupleWriter = (TypeAwareTupleWriter) tupleWriterFactory.createTupleWriter(); int numTuples = numBatches * batchSize; tuples = new ArrayList<TypeAwareTupleReference>(); tupleBuf = ByteBuffer.allocate(numTuples * tupleSize); for (int i = 0; i < numTuples; i++) { tuples.add((TypeAwareTupleReference) tupleWriter.createTupleReference()); } } @Override public long runExperiment(DataGenThread dataGen, int numThreads) throws InterruptedException { // Wait until the tupleBatchQueue is completely full. while (dataGen.tupleBatchQueue.remainingCapacity() != 0) { Thread.sleep(10); } long start = System.currentTimeMillis(); int tupleIndex = 0; for (int i = 0; i < numBatches; i++) { TupleBatch batch = dataGen.tupleBatchQueue.take(); for (int j = 0; j < batch.size(); j++) { // Copy the tuple to the buffer and set the pre-created tuple ref. tupleWriter.writeTuple(batch.get(j), tupleBuf.array(), tupleIndex * tupleSize); tuples.get(tupleIndex).resetByTupleOffset(tupleBuf.array(), tupleIndex * tupleSize); tupleIndex++; } } // Perform the sort. Collections.sort(tuples, tupleCmp); long end = System.currentTimeMillis(); long time = end - start; return time; } @Override public void init() throws Exception { } @Override public void deinit() throws Exception { } public void reset() throws Exception { } public class SkipListThread extends Thread { private final DataGenThread dataGen; private final ConcurrentSkipListSet<ITupleReference> skipList; private final int numBatches; public final TypeAwareTupleWriterFactory tupleWriterFactory; public final TypeAwareTupleWriter tupleWriter; public final TypeAwareTupleReference[] tuples; public final ByteBuffer tupleBuf; public SkipListThread(DataGenThread dataGen, ConcurrentSkipListSet<ITupleReference> skipList, int numBatches, int batchSize) { this.dataGen = dataGen; this.numBatches = numBatches; this.skipList = skipList; tupleWriterFactory = new TypeAwareTupleWriterFactory(typeTraits); tupleWriter = (TypeAwareTupleWriter) tupleWriterFactory.createTupleWriter(); int numTuples = numBatches * batchSize; tuples = new TypeAwareTupleReference[numTuples]; tupleBuf = ByteBuffer.allocate(numTuples * tupleSize); for (int i = 0; i < numTuples; i++) { tuples[i] = (TypeAwareTupleReference) tupleWriter.createTupleReference(); } } @Override public void run() { int tupleIndex = 0; try { for (int i = 0; i < numBatches; i++) { TupleBatch batch = dataGen.tupleBatchQueue.take(); for (int j = 0; j < batch.size(); j++) { // Copy the tuple to the buffer and set the pre-created tuple ref. tupleWriter.writeTuple(batch.get(j), tupleBuf.array(), tupleIndex * tupleSize); tuples[tupleIndex].resetByTupleOffset(tupleBuf.array(), tupleIndex * tupleSize); skipList.add(tuples[tupleIndex]); tupleIndex++; } } } catch (Exception e) { System.out.println(tupleIndex); e.printStackTrace(); } } } }
apache-2.0
celigo/netsuite-service-manager-dotnet
ServiceManager/Utility/CustomFieldDictionary.cs
9279
using System.Collections.Generic; using com.celigo.net.ServiceManager.SuiteTalk; #if CLR_2_0 using Celigo.Linq; #else using System.Linq; #endif namespace com.celigo.net.ServiceManager.Utility { /// <summary> /// A dictionary of Custom Fields indexed by the Internal IDs of the fields. /// </summary> public partial class CustomFieldDictionary : IDictionary<string, CustomFieldRef> { private readonly CustomFieldRef[] _customFields; private readonly Dictionary<string, CustomFieldRef> _dictionary; private bool _requiresInit; /// <summary> /// Initializes a new instance of the <see cref="CustomFieldDictionary"/> class. /// </summary> public CustomFieldDictionary() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="CustomFieldDictionary"/> class. /// </summary> /// <param name="customFields">The custom fields.</param> public CustomFieldDictionary(CustomFieldRef[] customFields) { _customFields = customFields; if (null != customFields) { _dictionary = new Dictionary<string, CustomFieldRef>(customFields.Length); _requiresInit = true; } else { _dictionary = new Dictionary<string, CustomFieldRef>(); _requiresInit = false; } } private void Initialize() { if (_requiresInit) lock (_dictionary) if (_requiresInit) { for (int i = _customFields.Length - 1; i >= 0; i--) if (_customFields[i] != null) { _dictionary[_customFields[i].GetInternalId()] = _customFields[i]; } _requiresInit = false; } } /// <summary> /// Returns an array of Custom Fields contained in the dictionary. /// </summary> /// <returns>An array of Custom Fields</returns> public CustomFieldRef[] ToArray() { if (_requiresInit) return _customFields; else { #if CLR_2_0 return Extensions.ToArray(_dictionary); #else return _dictionary.Values.ToArray(); #endif } } /// <summary> /// Gets the field with the given Id. /// </summary> /// <typeparam name="T">The Type of the custom field.</typeparam> /// <param name="fieldId">The field id.</param> /// <returns></returns> public T GetCustomField<T>(string fieldId) where T: CustomFieldRef { return this[fieldId] as T; } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public void Add(string key, CustomFieldRef value) { _dictionary[key] = value; } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(string key) { if (_requiresInit) Initialize(); return _dictionary.ContainsKey(key); } /// <summary> /// Gets the keys. /// </summary> /// <value>The keys.</value> public ICollection<string> Keys { get { if (_requiresInit) Initialize(); return _dictionary.Keys; } } /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public bool Remove(string key) { if (_requiresInit) Initialize(); return _dictionary.Remove(key); } /// <summary> /// Tries the get value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns></returns> public bool TryGetValue(string key, out CustomFieldRef value) { if (_requiresInit) Initialize(); return _dictionary.TryGetValue(key, out value); } /// <summary> /// Gets the values. /// </summary> /// <value>The values.</value> public ICollection<CustomFieldRef> Values { get { if (_requiresInit) Initialize(); return _dictionary.Values; } } /// <summary> /// Gets or sets the <see cref="com.celigo.net.ServiceManager.SuiteTalk.CustomFieldRef"/> with the specified key. /// </summary> /// <value></value> public CustomFieldRef this[string key] { get { if (_requiresInit) Initialize(); return _dictionary[key]; } set { if (_requiresInit) Initialize(); _dictionary[key] = value; } } /// <summary> /// Adds the specified item. /// </summary> /// <param name="item">The item.</param> public void Add(KeyValuePair<string, CustomFieldRef> item) { if (_requiresInit) Initialize(); _dictionary.Add(item.Key, item.Value); } /// <summary> /// Clears this instance. /// </summary> public void Clear() { _dictionary.Clear(); } /// <summary> /// Determines whether [contains] [the specified item]. /// </summary> /// <param name="item">The item.</param> /// <returns> /// <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>. /// </returns> public bool Contains(KeyValuePair<string, CustomFieldRef> item) { if (_requiresInit) Initialize(); return _dictionary.ContainsKey(item.Key); } /// <summary> /// Copies to. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">Index of the array.</param> public void CopyTo(KeyValuePair<string, CustomFieldRef>[] array, int arrayIndex) { if (_requiresInit) Initialize(); var itr = _dictionary.GetEnumerator(); for (int i = arrayIndex; i < array.Length; i++) { itr.MoveNext(); array[i] = itr.Current; } } /// <summary> /// Gets the count. /// </summary> /// <value>The count.</value> public int Count { get { if (_requiresInit) return _customFields.Length; else return _dictionary.Count; } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value> /// <c>true</c> if this instance is read only; otherwise, <c>false</c>. /// </value> public bool IsReadOnly { get { return false; } } /// <summary> /// Removes the specified item. /// </summary> /// <param name="item">The item.</param> /// <returns></returns> public bool Remove(KeyValuePair<string, CustomFieldRef> item) { if (_requiresInit) Initialize(); return _dictionary.Remove(item.Key); } /// <summary> /// Gets the enumerator. /// </summary> /// <returns></returns> public IEnumerator<KeyValuePair<string, CustomFieldRef>> GetEnumerator() { if (_requiresInit) Initialize(); return _dictionary.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
apache-2.0
dvreeze/yaidom
js/src/main/scala/eu/cdevreeze/yaidom/convert/JsDomToYaidomConversions.scala
10386
/* * Copyright 2011-2017 Chris de Vreeze * * 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 eu.cdevreeze.yaidom.convert import java.net.URI import scala.collection.immutable import org.scalajs.dom.raw.Attr import org.scalajs.dom.raw.Element import org.scalajs.dom.raw.NamedNodeMap import org.scalajs.dom.raw.NodeList import eu.cdevreeze.yaidom.core.Declarations import eu.cdevreeze.yaidom.core.EName import eu.cdevreeze.yaidom.core.ENameProvider import eu.cdevreeze.yaidom.core.QName import eu.cdevreeze.yaidom.core.QNameProvider import eu.cdevreeze.yaidom.core.Scope import eu.cdevreeze.yaidom.simple.Comment import eu.cdevreeze.yaidom.simple.ConverterToDocument import eu.cdevreeze.yaidom.simple.Document import eu.cdevreeze.yaidom.simple.Elem import eu.cdevreeze.yaidom.simple.Node import eu.cdevreeze.yaidom.simple.ProcessingInstruction import eu.cdevreeze.yaidom.simple.Text /** * Converter from JS DOM nodes to yaidom nodes, in particular from `org.scalajs.dom.raw.Element` to `eu.cdevreeze.yaidom.simple.Elem` and * from `org.scalajs.dom.raw.Document` to `eu.cdevreeze.yaidom.simple.Document`. * * This converter regards the input more like an "ElemBuilder" than an "Elem", in that namespace declarations instead of * scopes are extracted from input "elements", and in that conversions to yaidom Elems take an additional parent scope * parameter (against which namespace declarations are resolved to get the scope of the yaidom element). * * @author Chris de Vreeze */ trait JsDomToYaidomConversions extends ConverterToDocument[org.scalajs.dom.raw.Document] { /** * Converts an `org.scalajs.dom.raw.Document` to a `eu.cdevreeze.yaidom.simple.Document`. */ final def convertToDocument(v: org.scalajs.dom.raw.Document): Document = { // Is the document URI retained after parsing? val uriOption: Option[URI] = Option(v.documentURI) map { uriString => new URI(uriString) } Document( uriOption = uriOption, xmlDeclarationOption = None, children = nodeListToIndexedSeq(v.childNodes) flatMap { case e: org.scalajs.dom.raw.Element => Some(convertToElem(v.documentElement, Scope.Empty)) case pi: org.scalajs.dom.raw.ProcessingInstruction => Some(convertToProcessingInstruction(pi)) case c: org.scalajs.dom.raw.Comment => Some(convertToComment(c)) case _ => None }) } /** * Given a parent scope, converts an `org.scalajs.dom.raw.Element` to a `eu.cdevreeze.yaidom.simple.Elem`. * * The result `Elem` gets Scope `parentScope.resolve(extractNamespaceDeclarations(v.getAttributes))`. * * Be careful: the namespaces inherited by the passed DOM element, if any, are ignored! In other words, the ancestry of * the passed DOM element is entirely ignored. This may cause an exception to be thrown, if there are indeed such namespaces, * unless they are a subset of the passed parent scope. */ final def convertToElem(v: Element, parentScope: Scope): Elem = { val qname: QName = toQName(v) val attributes: immutable.IndexedSeq[(QName, String)] = extractAttributes(v.attributes) val namespaceDeclarations: Declarations = extractNamespaceDeclarations(v.attributes) val newScope: Scope = parentScope.resolve(namespaceDeclarations) // Recursive (not tail-recursive) val childSeq = nodeListToIndexedSeq(v.childNodes) flatMap { n => convertToNodeOption(n, newScope) } new Elem( qname = qname, attributes = attributes, scope = newScope, children = childSeq) } /** * Given a parent scope, converts an `org.scalajs.dom.raw.Node` to an optional `eu.cdevreeze.yaidom.simple.Node`. * * In case of an element, the result `Elem` (wrapped in an Option) gets Scope * `parentScope.resolve(extractNamespaceDeclarations(v.getAttributes))`. * * Be careful: the namespaces inherited by the passed DOM node, if any, are ignored! In other words, the ancestry of * the passed DOM node is entirely ignored. This may cause an exception to be thrown, if there are indeed such namespaces, * unless they are a subset of the passed parent scope. */ final def convertToNodeOption(v: org.scalajs.dom.raw.Node, parentScope: Scope): Option[Node] = { v match { case e: Element => Some(convertToElem(e, parentScope)) case t: org.scalajs.dom.raw.CDATASection => Some(convertToText(t)) case t: org.scalajs.dom.raw.Text => Some(convertToText(t)) case pi: org.scalajs.dom.raw.ProcessingInstruction => Some(convertToProcessingInstruction(pi)) case c: org.scalajs.dom.raw.Comment => Some(convertToComment(c)) case _ => None } } /** Converts an `org.scalajs.dom.raw.Text` to a `eu.cdevreeze.yaidom.simple.Text` */ final def convertToText(v: org.scalajs.dom.raw.Text): Text = v match { case cdata: org.scalajs.dom.raw.CDATASection if v.nodeType == org.scalajs.dom.raw.Node.CDATA_SECTION_NODE => Text(text = v.data, isCData = true) case _ => Text(text = v.data, isCData = false) } /** Converts an `org.scalajs.dom.raw.ProcessingInstruction` to a `eu.cdevreeze.yaidom.simple.ProcessingInstruction` */ final def convertToProcessingInstruction(v: org.scalajs.dom.raw.ProcessingInstruction): ProcessingInstruction = ProcessingInstruction(v.target, v.data) /** Converts an `org.scalajs.dom.raw.Comment` to a `eu.cdevreeze.yaidom.simple.Comment` */ final def convertToComment(v: org.scalajs.dom.raw.Comment): Comment = Comment(v.data) /** Converts a `NamedNodeMap` to an `immutable.IndexedSeq[(QName, String)]`. Namespace declarations are skipped. */ final def extractAttributes(domAttributes: NamedNodeMap): immutable.IndexedSeq[(QName, String)] = { (0 until domAttributes.length).flatMap(i => { val attr = domAttributes.item(i).asInstanceOf[Attr] if (isNamespaceDeclaration(attr)) { None } else { val qname: QName = toQName(attr) Some(qname -> attr.value) } }).toIndexedSeq } /** Converts the namespace declarations in a `NamedNodeMap` to a `Declarations` */ final def extractNamespaceDeclarations(domAttributes: NamedNodeMap): Declarations = { val nsMap = { val result = (0 until domAttributes.length) flatMap { i => val attr = domAttributes.item(i).asInstanceOf[Attr] if (isNamespaceDeclaration(attr)) { val result = extractNamespaceDeclaration(attr) Some(result) map { pair => (pair._1.getOrElse(""), pair._2) } } else { None } } result.toMap } Declarations.from(nsMap) } /** Helper method that converts a `NodeList` to an `IndexedSeq[org.scalajs.dom.raw.Node]` */ final def nodeListToIndexedSeq(nodeList: NodeList): immutable.IndexedSeq[org.scalajs.dom.raw.Node] = { val result = (0 until nodeList.length) map { i => nodeList.item(i) } result.toIndexedSeq } /** Extracts the `QName` of an `org.scalajs.dom.raw.Element` */ final def toQName(v: org.scalajs.dom.raw.Element)(implicit qnameProvider: QNameProvider): QName = { val name: String = v.tagName val arr = name.split(':') assert(arr.length >= 1 && arr.length <= 2) if (arr.length == 1) qnameProvider.getUnprefixedQName(arr(0)) else qnameProvider.getQName(arr(0), arr(1)) } /** Extracts the `QName` of an `org.scalajs.dom.raw.Attr`. If the `Attr` is a namespace declaration, an exception is thrown. */ final def toQName(v: org.scalajs.dom.raw.Attr)(implicit qnameProvider: QNameProvider): QName = { require(!isNamespaceDeclaration(v), "Namespace declaration not allowed") val name: String = v.name val arr = name.split(':') assert(arr.length >= 1 && arr.length <= 2) if (arr.length == 1) qnameProvider.getUnprefixedQName(arr(0)) else qnameProvider.getQName(arr(0), arr(1)) } /** Returns true if the `org.scalajs.dom.raw.Attr` is a namespace declaration */ final def isNamespaceDeclaration(v: org.scalajs.dom.raw.Attr): Boolean = { val name: String = v.name val arr = name.split(':') assert(arr.length >= 1 && arr.length <= 2) val result = arr(0) == "xmlns" result } /** Extracts (optional) prefix and namespace. Call only if `isNamespaceDeclaration(v)`, since otherwise an exception is thrown. */ final def extractNamespaceDeclaration(v: org.scalajs.dom.raw.Attr): (Option[String], String) = { val name: String = v.name val arr = name.split(':') assert(arr.length >= 1 && arr.length <= 2) require(arr(0) == "xmlns") val prefixOption: Option[String] = if (arr.length == 1) None else Some(arr(1)) val attrValue: String = v.value (prefixOption, attrValue) } /** Extracts the `EName` of an `org.scalajs.dom.raw.Element` */ final def toEName(v: org.scalajs.dom.raw.Element)(implicit enameProvider: ENameProvider): EName = { val nsOption = Option(v.namespaceURI) enameProvider.getEName(nsOption, v.localName) } /** Extracts the `EName` of an `org.scalajs.dom.raw.Attr`. If the `Attr` is a namespace declaration, an exception is thrown. */ final def toEName(v: org.scalajs.dom.raw.Attr)(implicit enameProvider: ENameProvider): EName = { require(!isNamespaceDeclaration(v), "Namespace declaration not allowed") val nsOption = Option(v.namespaceURI) enameProvider.getEName(nsOption, v.localName) } /** Converts a `NamedNodeMap` to an `immutable.IndexedSeq[(EName, String)]`. Namespace declarations are skipped. */ final def extractResolvedAttributes(domAttributes: NamedNodeMap): immutable.IndexedSeq[(EName, String)] = { (0 until domAttributes.length).flatMap(i => { val attr = domAttributes.item(i).asInstanceOf[Attr] if (isNamespaceDeclaration(attr)) { None } else { val ename: EName = toEName(attr) Some(ename -> attr.value) } }).toIndexedSeq } }
apache-2.0
pelamfi/pelam-scala-csv
src/test/scala/fi/pelam/csv/stream/CsvWriterTest.scala
3591
/* * This file is part of pelam-scala-csv * * Copyright © Peter Lamberg 2015 (pelam-scala-csv@pelam.fi) * * 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 fi.pelam.csv.stream import java.nio.charset.StandardCharsets import com.google.common.io.{CharStreams, Resources} import fi.pelam.csv.cell.{CellKey, StringCell} import org.junit.Assert._ import org.junit.Test class CsvWriterTest { val stringBuilder = new java.lang.StringBuilder() val charWriter = CharStreams.asWriter(stringBuilder) val csvWriter = new CsvWriter(charWriter) @Test(expected = classOf[RuntimeException]) def testWriteSameKeyError: Unit = { csvWriter.write(List(StringCell(CellKey(0, 0), "foo"), StringCell(CellKey(0, 0), "bar"))) } @Test(expected = classOf[RuntimeException]) def testWriteOldKeyError: Unit = { csvWriter.write(List(StringCell(CellKey(0, 0), "foo"), StringCell(CellKey(0, 1), "bar"), StringCell(CellKey(0, 0), "bar"))) } @Test def testSingleRow: Unit = { csvWriter.write(List(StringCell(CellKey(0, 0), "foo"), StringCell(CellKey(0, 1), "bar"))) assertEquals("foo,bar", stringBuilder.toString()) } @Test def testFinalNewLine: Unit = { csvWriter.write(List(StringCell(CellKey(0, 0), "foo"), StringCell(CellKey(0, 1), "bar"))) csvWriter.goToNextRow() assertEquals("foo,bar\n", stringBuilder.toString()) } @Test def testTwoLines: Unit = { csvWriter.write(List(StringCell(CellKey(0, 0), "foo"), StringCell(CellKey(0, 1), "bar"))) csvWriter.write(List(StringCell(CellKey(1, 0), "x"), StringCell(CellKey(1, 1), "y"))) assertEquals("foo,bar\nx,y", stringBuilder.toString()) } @Test def testTwoLinesWithGoToNextLine: Unit = { csvWriter.write(List(StringCell(CellKey(0, 0), "foo"), StringCell(CellKey(0, 1), "bar"))) csvWriter.goToNextRow() csvWriter.write(List(StringCell(CellKey(1, 0), "x"), StringCell(CellKey(1, 1), "y"))) csvWriter.goToNextRow() assertEquals("foo,bar\nx,y\n", stringBuilder.toString()) } @Test def testSkips: Unit = { csvWriter.write(StringCell(CellKey(0, 0), "foo")) csvWriter.write(StringCell(CellKey(1, 1), "bar")) assertEquals("foo\n,bar", stringBuilder.toString()) } @Test def testQuotes: Unit = { assertEquals("foo", CsvWriter.serialize(StringCell(CellKey(0, 0), "foo"), ',')) assertEquals("\"f,oo\"", CsvWriter.serialize(StringCell(CellKey(0, 0), "f,oo"), ',')) assertEquals("\"f,,oo\"", CsvWriter.serialize(StringCell(CellKey(0, 0), "f,,oo"), ',')) assertEquals("\"f\"\"oo\"", CsvWriter.serialize(StringCell(CellKey(0, 0), "f\"oo"), ',')) } @Test def loopbackTest: Unit = { val file = Resources.asByteSource(Resources.getResource("csv–file-for-loading")) val csvStringOrig = file.asCharSource(StandardCharsets.UTF_8).read() val readOrigCells = new CsvReader(csvStringOrig).throwOnError.toIndexedSeq assertEquals("Initial data cell count sanity check", 180, readOrigCells.size) csvWriter.write(readOrigCells) assertEquals(csvStringOrig, stringBuilder.toString()) } }
apache-2.0
paidgeek/opkp
src/main/resources/static/js/explore.js
2019
app.controller("graphs", function($scope, opkpService, dataGraph) { $scope.dataGraph = dataGraph; $scope.path = []; $scope.pathLength = 1; $scope.selectedColumns = []; $scope.getColumns = function(index) { return $scope.dataGraph.fields[$scope.path[index]].map(function(field) { return field.name; }); } $scope.selectNode = function(index, node) { $scope.path[index] = node; $scope.selectedColumns[index] = []; } $scope.addNode = function() { $scope.pathLength++; } $scope.getSteps = function(start) { if (start < 0) { return Object.keys($scope.dataGraph.fields).sort(); } var nodes = Object.keys($scope.dataGraph.fields).sort(); if ($scope.pathLength > start && nodes) { var steps = []; var startNode = $scope.path[start]; for (var i = 0; i < nodes.length; i++) { if ($scope.dataGraph.pathExists(startNode, nodes[i])) { steps.push(nodes[i]); } } for (var i = 0; i <= start; i++) { var idx = steps.indexOf($scope.path[i]); if (idx != -1) { steps.splice(idx, 1); } } return steps; } return []; } $scope.removeNode = function(i) { $scope.path.splice(i, $scope.pathLength); $scope.pathLength = $scope.path.length; $scope.selectedColumns.splice(i); } $scope.update = function() { if ($scope.path.length == 0 || !$scope.selectedColumns) { return; } for (var i = 0; i < $scope.selectedColumns.length; i++) { for (var j = 0; j < $scope.selectedColumns[i].length; j++) { $scope.selectedColumns[i][j] = $scope.path[i] + "." + $scope.selectedColumns[i][j]; } } var columns = [].concat.apply([], $scope.selectedColumns); opkpService.path($scope.path, columns).then(function(data) { $scope.responseData = data; }); } });
apache-2.0
jaredpar/random
WorkItemFixer/WorkItemFixer/Program.cs
9558
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.WorkItemTracking.Client; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace WorkItemFixer { internal static class Program { internal static void Main(string[] args) { var teamFoundationServer = new TfsTeamProjectCollection(new Uri("http://vstfdevdiv:8080/DevDiv2")); var tfsWorkItemStore = new WorkItemStore(new TfsTeamProjectCollection(new Uri("http://vstfdevdiv:8080/DevDiv2"))); var roslynWorkItemStore = new WorkItemStore(new TfsTeamProjectCollection(new Uri("http://vstfdevdiv:8080/DevDiv_Projects"))); var workItemData = new WorkItemData(tfsWorkItemStore, roslynWorkItemStore); var unknownList = new List<string>(); var workItemUtil = new WorkItemUtil(workItemData, unknownList); var dataFile = @"c:\users\jaredpar\data.txt"; var root = @"e:\dd\roslyn\src"; var files = Directory.EnumerateFiles(root, "*.vb", SearchOption.AllDirectories) .Concat(Directory.EnumerateFiles(root, "*.cs", SearchOption.AllDirectories)); foreach (var filePath in files) { Console.WriteLine($"{filePath}"); SourceText text; using (var stream = File.OpenRead(filePath)) { text = SourceText.From(stream); } var rewriter = Path.GetExtension(filePath) == ".cs" ? (IRewriter)new CSharpWorkItemRewriter(workItemUtil, filePath) : (IRewriter)new BasicWorkItemRewriter(workItemUtil, filePath); var newText = rewriter.TryUpdate(text); if (newText != null) { using (var writer = new StreamWriter(filePath, append: false, encoding: text.Encoding)) { newText.Write(writer); } } if (unknownList.Count > 20) { File.AppendAllLines(dataFile, unknownList); unknownList.Clear(); } } File.AppendAllLines(dataFile, unknownList.ToArray()); } } interface IRewriter { SourceText TryUpdate(SourceText text); } internal struct WorkItemInfo { internal readonly int Id; internal readonly int OldId; internal readonly string Description; internal WorkItemInfo(int id, string description, int? oldId = null) { Id = id; Description = description; OldId = oldId ?? id; } } internal sealed class WorkItemData { private readonly WorkItemStore _tfsWorkItemStore; private readonly WorkItemStore _roslynWorkItemStore; private readonly Dictionary<int, int?> _idMap = new Dictionary<int, int?>(); private readonly Dictionary<int, bool> _githubMap = new Dictionary<int, bool>(); internal WorkItemData(WorkItemStore tfsWorkItemStore, WorkItemStore roslynWorkItemStore) { _tfsWorkItemStore = tfsWorkItemStore; _roslynWorkItemStore = roslynWorkItemStore; } internal bool TryGetMigratedInfo(int id, out int newId) { int? value; if (!_idMap.TryGetValue(id, out value)) { value = GetMigratedInfoCore(id); _idMap[id] = value; } newId = value ?? 0; return value.HasValue; } /// <summary> /// Is this a bug from the old Roslyn database? /// </summary> internal bool IsRoslynBug(int id) { try { var workItem = _roslynWorkItemStore.GetWorkItem(id); return workItem.AreaPath.Contains("Roslyn"); } catch { return false; } } internal bool IsGithubBug(int id) { if (id > 9000) { return false; } bool value; if (!_githubMap.TryGetValue(id, out value)) { value = IsGithubBugCore(id); _githubMap[id] = value; } return value; } private bool IsGithubBugCore(int id) { int count = 5; while (count > 0) { try { var url = $"https://github.com/dotnet/roslyn/issues/{id}"; var request = WebRequest.CreateHttp(url); var response = (HttpWebResponse)request.GetResponse(); return response.StatusCode == HttpStatusCode.OK; } catch { } count--; } return false; } internal bool IsDevDivTfsBug(int id, bool checkAreaPath = true) { try { var workItem = _tfsWorkItemStore.GetWorkItem(id); var areaPath = workItem.AreaPath; if (checkAreaPath) { return areaPath.StartsWith(@"DevDiv\Cloud Platform\Managed Languages"); } return true; } catch (Exception) { return false; } } private int? GetMigratedInfoCore(int id) { try { var workItem = _tfsWorkItemStore.GetWorkItem(id); var resolutionField = workItem.Fields["Resolution"]; if (resolutionField?.Value?.ToString() == "Migrated to VSO") { var mirrorField = workItem.Fields["Mirrored TFS ID"]; if (mirrorField?.Value != null) { return int.Parse(mirrorField.Value.ToString()); } } } catch (Exception) { } return null; } } internal sealed class WorkItemUtil { private const string UrlVso = "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems/edit/{0}"; private const string UrlRoslyn = "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/{0}"; private const string UrlDevDiv = "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/{0}"; private const string UrlGithub = "https://github.com/dotnet/roslyn/issues/{0}"; private readonly WorkItemData _workItemData; private readonly List<string> _unknownList; internal WorkItemUtil(WorkItemData workItemData, List<string> unknownList) { _workItemData = workItemData; _unknownList = unknownList; } internal WorkItemInfo? GetUpdatedWorkItemInfo(string filePath, FileLinePositionSpan loc, int id, string description) { if (StringComparer.OrdinalIgnoreCase.Equals("devdiv", description)) { if (_workItemData.IsDevDivTfsBug(id)) { return new WorkItemInfo(id, string.Format(UrlDevDiv, id)); } } if (string.IsNullOrEmpty(description)) { if (_workItemData.IsDevDivTfsBug(id)) { return new WorkItemInfo(id, string.Format(UrlDevDiv, id)); } if (_workItemData.IsGithubBug(id) && !_workItemData.IsRoslynBug(id)) { return new WorkItemInfo(id, string.Format(UrlGithub, id)); } if (!_workItemData.IsGithubBug(id) && _workItemData.IsRoslynBug(id)) { return new WorkItemInfo(id, string.Format(UrlRoslyn, id)); } if (id > 100000 && _workItemData.IsDevDivTfsBug(id, checkAreaPath: false)) { return new WorkItemInfo(id, string.Format(UrlDevDiv, id)); } _unknownList.Add($"{filePath} line {loc.StartLinePosition.Line} id {id}"); } if (RewriteUrl(id, ref description)) { return new WorkItemInfo(id, description); } Uri uri; if (!Uri.TryCreate(description, UriKind.Absolute, out uri)) { _unknownList.Add($"Bad Url {filePath} {loc.StartLinePosition.Line}"); } return null; } internal static bool RewriteUrl(int id, ref string description) { Uri uri; if (!Uri.TryCreate(description, UriKind.Absolute, out uri) || string.IsNullOrEmpty(uri.Fragment)) { return false; } var builder = new UriBuilder(uri); builder.Fragment = null; builder.Path = $"{uri.PathAndQuery}/edit/{id}"; description = builder.ToString(); return true; } } }
apache-2.0
ynhng/Indigo.NET
Indigo.WebMatrix/static/base/base.js
19596
/*! * Author: Yin Hang * Date: 26 Jul 2014 * Description: * This file should be included in all pages !**/ (function ($) { $(function () { /* 为所有复选框、单选框配置样式 */ $("input[type='checkbox'], input[type='radio']").iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional }); /* 为链接使用不同的HTTP-METHOD发送 */ $('a[data-method]').click(function () { var $this = $(this); $('<form>', { action: this.href, method: $this.data('method') }).appendTo('body').submit(); return false; }); /* 为搜索表单提供分页功能 */ $('.pagination[data-target] li[class!="disabled"] a').click(function () { var form = $($('.pagination').attr('data-target')); var pageNumber = $('#PageNumber').val($(this).data('number')); form.append(pageNumber); form.append($('#PageLength')); form.submit(); return false; }); $('.modal-dialog').center(); }); })(jQuery); /* CENTER ELEMENTS */ (function ($) { "use strict"; jQuery.fn.center = function (parent) { if (parent) { parent = this.parent(); } else { parent = window; } this.css({ "position": "absolute", "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"), "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px") }); return this; } }(jQuery)); /*! ** Unobtrusive validation support library for jQuery and jQuery Validate ** Copyright (C) Microsoft Corporation. All rights reserved. */ /*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */ /*global document: false, jQuery: false */ (function ($) { var $jQval = $.validator, adapters, data_validation = "unobtrusiveValidation"; function setValidationValues(options, ruleName, value) { options.rules[ruleName] = value; if (options.message) { options.messages[ruleName] = options.message; } } function splitAndTrim(value) { return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g); } function escapeAttributeValue(value) { // As mentioned on http://api.jquery.com/category/selectors/ return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1"); } function getModelPrefix(fieldName) { return fieldName.substr(0, fieldName.lastIndexOf(".") + 1); } function appendModelPrefix(value, prefix) { if (value.indexOf("*.") === 0) { value = value.replace("*.", prefix); } return value; } function onError(error, inputElement) { // 'this' is the form element var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"), replaceAttrValue = container.attr("data-valmsg-replace"), replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null; container.removeClass("field-validation-valid").addClass("field-validation-error"); error.data("unobtrusiveContainer", container); if (container.length > 0) { var inputContainer = $(inputElement).parents(".form-group"); if (inputContainer) { inputContainer.removeClass("has-success").addClass("has-error"); if (inputContainer.hasClass("has-feedback")) { inputContainer.find(".form-control-feedback").remove(); inputContainer.append('<i class="fa fa-times-circle fa-lg form-control-feedback"></i>'); } } } if (replace) { container.empty(); error.removeClass("input-validation-error").appendTo(container); } else { error.hide(); } } function onErrors(event, validator) { // 'this' is the form element var container = $(this).find("[data-valmsg-summary=true]"), list = container.find("ul"); if (list && list.length && validator.errorList.length) { list.empty(); container.addClass("validation-summary-errors alert alert-error").removeClass("validation-summary-valid"); $.each(validator.errorList, function () { $("<li />").html(this.message).appendTo(list); }); } } function onSuccess(error) { // 'this' is the form element var container = error.data("unobtrusiveContainer"), replaceAttrValue = container.attr("data-valmsg-replace"), replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null; if (container) { container.addClass("field-validation-valid").removeClass("field-validation-error"); error.removeData("unobtrusiveContainer"); var inputContainer = $("#" + container.data("valmsg-for")).parents(".form-group"); if (inputContainer) { inputContainer.removeClass("has-error").addClass("has-success"); if (inputContainer.hasClass("has-feedback")) { inputContainer.find(".form-control-feedback").remove(); inputContainer.append('<i class="fa fa-check-circle fa-lg form-control-feedback"></i>'); } } if (replace) { container.empty(); } } } function onReset(event) { // 'this' is the form element var $form = $(this); $form.data("validator").resetForm(); $form.find(".validation-summary-errors") .addClass("validation-summary-valid") .removeClass("validation-summary-errors"); $form.find(".field-validation-error") .addClass("field-validation-valid") .removeClass("field-validation-error") .removeData("unobtrusiveContainer") .find(">*") // If we were using valmsg-replace, get the underlying error .removeData("unobtrusiveContainer"); } function validationInfo(form) { var $form = $(form), result = $form.data(data_validation), onResetProxy = $.proxy(onReset, form); if (!result) { result = { options: { // options structure passed to jQuery Validate's validate() method errorClass: "text-danger", errorElement: "span", errorPlacement: $.proxy(onError, form), invalidHandler: $.proxy(onErrors, form), messages: {}, rules: {}, success: $.proxy(onSuccess, form) }, attachValidation: function () { $form .unbind("reset." + data_validation, onResetProxy) .bind("reset." + data_validation, onResetProxy) .validate(this.options); }, validate: function () { // a validation function that is called by unobtrusive Ajax $form.validate(); return $form.valid(); } }; $form.data(data_validation, result); } return result; } $jQval.unobtrusive = { adapters: [], parseElement: function (element, skipAttach) { /// <summary> /// Parses a single HTML element for unobtrusive validation attributes. /// </summary> /// <param name="element" domElement="true">The HTML element to be parsed.</param> /// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the /// validation to the form. If parsing just this single element, you should specify true. /// If parsing several elements, you should specify false, and manually attach the validation /// to the form when you are finished. The default is false.</param> var $element = $(element), form = $element.parents("form")[0], valInfo, rules, messages; if (!form) { // Cannot do client-side validation without a form return; } valInfo = validationInfo(form); valInfo.options.rules[element.name] = rules = {}; valInfo.options.messages[element.name] = messages = {}; $.each(this.adapters, function () { var prefix = "data-val-" + this.name, message = $element.attr(prefix), paramValues = {}; if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy) prefix += "-"; $.each(this.params, function () { paramValues[this] = $element.attr(prefix + this); }); this.adapt({ element: element, form: form, message: message, params: paramValues, rules: rules, messages: messages }); } }); $.extend(rules, { "__dummy__": true }); if (!skipAttach) { valInfo.attachValidation(); } }, parse: function (selector) { /// <summary> /// Parses all the HTML elements in the specified selector. It looks for input elements decorated /// with the [data-val=true] attribute value and enables validation according to the data-val-* /// attribute values. /// </summary> /// <param name="selector" type="String">Any valid jQuery selector.</param> var $forms = $(selector) .parents("form") .andSelf() .add($(selector).find("form")) .filter("form"); $(selector).find(":input[data-val=true]").each(function () { $jQval.unobtrusive.parseElement(this, true); }); $forms.each(function () { var info = validationInfo(this); if (info) { info.attachValidation(); } }); } }; adapters = $jQval.unobtrusive.adapters; adapters.add = function (adapterName, params, fn) { /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary> /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param> /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and /// mmmm is the parameter name).</param> /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML /// attributes into jQuery Validate rules and/or messages.</param> /// <returns type="jQuery.validator.unobtrusive.adapters" /> if (!fn) { // Called with no params, just a function fn = params; params = []; } this.push({ name: adapterName, params: params, adapt: fn }); return this; }; adapters.addBool = function (adapterName, ruleName) { /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where /// the jQuery Validate validation rule has no parameter values.</summary> /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param> /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value /// of adapterName will be used instead.</param> /// <returns type="jQuery.validator.unobtrusive.adapters" /> return this.add(adapterName, function (options) { setValidationValues(options, ruleName || adapterName, true); }); }; adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) { /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary> /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param> /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only /// have a minimum value.</param> /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only /// have a maximum value.</param> /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you /// have both a minimum and maximum value.</param> /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that /// contains the minimum value. The default is "min".</param> /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that /// contains the maximum value. The default is "max".</param> /// <returns type="jQuery.validator.unobtrusive.adapters" /> return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) { var min = options.params.min, max = options.params.max; if (min && max) { setValidationValues(options, minMaxRuleName, [min, max]); } else if (min) { setValidationValues(options, minRuleName, min); } else if (max) { setValidationValues(options, maxRuleName, max); } }); }; adapters.addSingleVal = function (adapterName, attribute, ruleName) { /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where /// the jQuery Validate validation rule has a single value.</summary> /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param> /// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value. /// The default is "val".</param> /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value /// of adapterName will be used instead.</param> /// <returns type="jQuery.validator.unobtrusive.adapters" /> return this.add(adapterName, [attribute || "val"], function (options) { setValidationValues(options, ruleName || adapterName, options.params[attribute]); }); }; $jQval.addMethod("__dummy__", function (value, element, params) { return true; }); $jQval.addMethod("regex", function (value, element, params) { var match; if (this.optional(element)) { return true; } match = new RegExp(params).exec(value); return (match && (match.index === 0) && (match[0].length === value.length)); }); $jQval.addMethod("nonalphamin", function (value, element, nonalphamin) { var match; if (nonalphamin) { match = value.match(/\W/g); match = match && match.length >= nonalphamin; } return match; }); adapters.addSingleVal("accept", "exts").addSingleVal("regex", "pattern"); adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url"); adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range"); adapters.add("equalto", ["other"], function (options) { var prefix = getModelPrefix(options.element.name), other = options.params.other, fullOtherName = appendModelPrefix(other, prefix), element = $(options.form).find(":input[name='" + escapeAttributeValue(fullOtherName) + "']")[0]; setValidationValues(options, "equalTo", element); }); adapters.add("required", function (options) { // jQuery Validate equates "required" with "mandatory" for checkbox elements if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") { setValidationValues(options, "required", true); } }); adapters.add("remote", ["url", "type", "additionalfields"], function (options) { var value = { url: options.params.url, type: options.params.type || "GET", data: {} }, prefix = getModelPrefix(options.element.name); $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) { var paramName = appendModelPrefix(fieldName, prefix); value.data[paramName] = function () { return $(options.form).find(":input[name='" + escapeAttributeValue(paramName) + "']").val(); }; }); setValidationValues(options, "remote", value); }); adapters.add("password", ["min", "nonalphamin", "regex"], function (options) { if (options.params.min) { setValidationValues(options, "minlength", options.params.min); } if (options.params.nonalphamin) { setValidationValues(options, "nonalphamin", options.params.nonalphamin); } if (options.params.regex) { setValidationValues(options, "regex", options.params.regex); } }); $(function () { $jQval.unobtrusive.parse(document); /* 设置全局错误信息样式 */ $('.validation-summary-errors').addClass('alert alert-danger').children('ul').addClass('list-unstyled'); }); }(jQuery));
apache-2.0
tlorentzen/laravel-followable
src/Like.php
334
<?php namespace Tlorentzen\Likeable; use Illuminate\Database\Eloquent\Model as Eloquent; class Like extends Eloquent { protected $table = 'likes'; public $timestamps = false; protected $fillable = ['likeable_id', 'likeable_type', 'user_id']; public function likeable() { return $this->morphTo(); } }
apache-2.0
shigeyf/AzureMediaVideoPortalSample
VideoPortalDemo/App_Start/Startup.Auth.cs
6105
//---------------------------------------------------------------------------------------------- // Copyright 2014 Microsoft Corporation // // 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. //---------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IdentityModel.Claims; using System.Linq; //using System.Security.Claims; using System.Threading.Tasks; using System.Web; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.WindowsAzure.MediaServices.Client; using Owin; using VideoPortalDemo.Models; namespace VideoPortalDemo { public partial class Startup { private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"]; private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"]; private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"]; public static readonly string Authority = aadInstance + tenantId; // This is the resource ID of the AAD Graph API. We'll need this to request a token to call the Graph API. //string graphResourceId = "https://graph.windows.net"; // added by shigeyf@microsoft.com to the original template private string graphResourceId = ConfigurationManager.AppSettings["ida:GraphResourceId"]; private string kdResourceId = ConfigurationManager.AppSettings["ida:KeyDeliveryResourceId"]; private string mediaServicesAccount = ConfigurationManager.AppSettings["ams:MediaServicesAccount"]; private string mediaServicesKey = ConfigurationManager.AppSettings["ams:MediaServicesKey"]; // added by shigeyf@microsoft.com to the original template public void ConfigureAuth(IAppBuilder app) { ApplicationDbContext db = new ApplicationDbContext(); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = Authority, PostLogoutRedirectUri = postLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications() { // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. AuthorizationCodeReceived = (context) => { var code = context.Code; ClientCredential credential = new ClientCredential(clientId, appKey); string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID)); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); // added by shigeyf@microsoft.com to the original template // Getting KeyDelivery Access Token AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, kdResourceId); string kdAccessToken = kdAPiresult.AccessToken; System.IdentityModel.Tokens.JwtSecurityToken kdAccessJwtToken = new System.IdentityModel.Tokens.JwtSecurityToken(kdAccessToken); try { // Initializing MediaServicesCredentials in order to obtain access token to be used to connect var amsCredentials = new MediaServicesCredentials(mediaServicesAccount, mediaServicesKey); // Forces to get access token amsCredentials.RefreshToken(); //Adding media services access token as claim so it can be accessible within controller context.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(VideoPortalDemo.Configurations.ClaimsAmsAcessToken, amsCredentials.AccessToken)); } catch { } //context.AuthenticationTicket.Identity.AddClaim( // new System.Security.Claims.Claim("KdAccessJwtSecurityTokenClaim", kdAccessJwtToken.RawData)); // added by shigeyf@microsoft.com to the original template return Task.FromResult(0); } } }); } } }
apache-2.0
networksoft/erp.wellnet
application/views/website/ov/compra_reporte/datos_envio.php
5841
<link href="/cart/HTML/assets/css/style.css" rel="stylesheet"> <link href="/cart/HTML/assets/css/skin-3.css" rel="stylesheet"> <!-- css3 animation effect for this template --> <link href="/cart/HTML/assets/css/animate.min.css" rel="stylesheet"> <!-- styles needed by carousel slider --> <link href="/cart/HTML/assets/css/owl.carousel.css" rel="stylesheet"> <link href="/cart/HTML/assets/css/owl.theme.css" rel="stylesheet"> <!-- styles needed by checkRadio --> <link href="/cart/HTML/assets/css/ion.checkRadio.css" rel="stylesheet"> <link href="/cart/HTML/assets/css/ion.checkRadio.cloudy.css" rel="stylesheet"> <!-- styles needed by mCustomScrollbar --> <link href="/cart/HTML/assets/css/jquery.mCustomScrollbar.css" rel="stylesheet"> <!-- Just for debugging purposes. --> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> <!-- include pace script for automatic web page progress bar --> <script> paceOptions = { elements: true }; </script> <script src="/cart/HTML/assets/js/pace.min.js"></script> <div class="row"> <div class="col-md-3"></div> <div class="well col-md-8" style="background-color: #fff;"> <h1>Datos de envío</h1> <form class="smart-form" method="POST" action="guardarEnvio"> <fieldset> <div class="col col-xs-12 col-md-6 col-lg-6"> <label class="select">Pais <select id="pais" required name="pais" onChange="Departamentos()"> <option value="-" selected>-- Seleciona un pais --</option> <?foreach ($paises as $key){ ?> <option <?=($key->Code==$datos['pais']) ? "selected" : ""?> value="<?=$key->Code?>"><?=$key->Name?></option> <? }?> </select> </label> </div> <div class="col col-xs-12 col-md-6 col-lg-6"> <label for="" class="select">Estado/Departamento <select id="departamento" name="estado" onChange="CiudadesDepartamento()" required><option value="<?=$datos['estado']?>" selected><?=$datos['estado']?></option> </select> </label> </div> <div class="col col-xs-12 col-md-6 col-lg-6"> <label for="" class="select">Municipio/Ciudad <select id="municipio" required name="municipio" onChange="BuscarProveedores()"> <option value="<?=$datos['municipio']?>" selected><?=$datos['municipio']?></option> </select> </label> </div> <div class="col col-xs-12 col-md-6 col-lg-6"> <label class="input">Colonia / Barrio <input required type="text" id="colonia" name="colonia" value="<?php echo $datos['colonia']; ?>"> </label> </div> <div class="col col-xs-12 col-md-6 col-lg-6"> <label class="input">Dirección <input required type="text" id="direccion" name="direccion" value="<?php echo $datos['calle']; ?>"> </label> </div> <div class="col col-xs-12 col-md-6 col-lg-6"> <label class="input">Codigo Postal <input type="text" id="codigo" name="codigo" value="<?php echo $datos['cp']; ?>"> </label> </div> </fieldset> <footer class="col col-12 pull-right" > <button type="submit" class="btn btn-success" onclick="CrearComprador()">3. Ver Pedido</button> <a class="btn btn-danger" href="/ov/compras/carrito?tipo=1">Atras</a> </footer> </form> </div> </div> <div class="row"> <!-- a blank row to get started --> <div class="col-sm-12"> <br /> <br /> </div> </div> <script type="text/javascript" src="/cart/HTML/assets/js/smoothproducts.min.js"></script> <script src="js/plugin/bootstrap-wizard/jquery.bootstrap.wizard.min.js"></script> <script src="/template/js/plugin/fuelux/wizard/wizard.min.js"></script> <script src="/template/js/plugin/jquery-form/jquery-form.min.js"></script> <script src="/template/js/validacion.js"></script> <script src="/template/js/plugin/fuelux/wizard/wizard.min.js"></script> <script type="text/javascript" charset="charset"> function Departamentos(){ var pa = $("#pais").val(); $.ajax({ type: "POST", url: "/bo/proveedor_mensajeria/DepartamentoPais", data: {pais: pa} }) .done(function( msg ) { $('#departamento option').each(function() { $(this).remove(); }); datos=$.parseJSON(msg); $('#departamento').append('<option value="0">-- Seleciona un Estado / Departamento --</option>'); for(var i in datos){ $('#departamento').append('<option value="'+datos[i]['Name']+'">'+datos[i]['Name']+'</option>'); } }); } function CiudadesDepartamento(){ var pa = $("#departamento").val(); $.ajax({ type: "POST", url: "/bo/proveedor_mensajeria/CiudadDepartamento", data: {departamento: pa} }) .done(function( msg ) { $('#municipio option').each(function() { $(this).remove(); }); datos=$.parseJSON(msg); $('#municipio').append('<option value="">-- Seleciona una ciudad / municipio </option>'); for(var i in datos){ $('#municipio').append('<option value="'+datos[i]['Name']+'">'+datos[i]['Name']+'</option>'); } }); } function BuscarProveedores(){ var pa = $("#municipio").val(); $.ajax({ type: "POST", url: "/ov/compras/buscarProveedores", data: {id_ciudad: pa} }) .done(function( msg ) { $('#tarifa option').each(function() { $(this).remove(); }); datos=$.parseJSON(msg); $('#tarifa').append('<option value="">-- Seleciona una Tarifa --</option>'); for(var i in datos){ $('#tarifa').append('<option value="'+datos[i]['id']+'">'+datos[i]['razon_social']+' - $'+datos[i]['tarifa']+'</option>'); } }); } </script>
apache-2.0
phongdly/puppetlabs-dsc
spec/unit/puppet/type/dsc_xwebconfigkeyvalue_spec.rb
11844
#!/usr/bin/env ruby require 'spec_helper' describe Puppet::Type.type(:dsc_xwebconfigkeyvalue) do let :dsc_xwebconfigkeyvalue do Puppet::Type.type(:dsc_xwebconfigkeyvalue).new( :name => 'foo', :dsc_websitepath => 'foo', :dsc_configsection => 'AppSettings', :dsc_key => 'foo', ) end it "should stringify normally" do expect(dsc_xwebconfigkeyvalue.to_s).to eq("Dsc_xwebconfigkeyvalue[foo]") end it 'should default to ensure => present' do expect(dsc_xwebconfigkeyvalue[:ensure]).to eq :present end it 'should require that dsc_websitepath is specified' do #dsc_xwebconfigkeyvalue[:dsc_websitepath] expect { Puppet::Type.type(:dsc_xwebconfigkeyvalue).new( :name => 'foo', :dsc_configsection => 'AppSettings', :dsc_ensure => 'Present', :dsc_key => 'foo', :dsc_value => 'foo', :dsc_isattribute => true, )}.to raise_error(Puppet::Error, /dsc_websitepath is a required attribute/) end it 'should not accept array for dsc_websitepath' do expect{dsc_xwebconfigkeyvalue[:dsc_websitepath] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_websitepath' do expect{dsc_xwebconfigkeyvalue[:dsc_websitepath] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_websitepath' do expect{dsc_xwebconfigkeyvalue[:dsc_websitepath] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_websitepath' do expect{dsc_xwebconfigkeyvalue[:dsc_websitepath] = 16}.to raise_error(Puppet::ResourceError) end it 'should require that dsc_configsection is specified' do #dsc_xwebconfigkeyvalue[:dsc_configsection] expect { Puppet::Type.type(:dsc_xwebconfigkeyvalue).new( :name => 'foo', :dsc_websitepath => 'foo', :dsc_ensure => 'Present', :dsc_key => 'foo', :dsc_value => 'foo', :dsc_isattribute => true, )}.to raise_error(Puppet::Error, /dsc_configsection is a required attribute/) end it 'should accept dsc_configsection predefined value AppSettings' do dsc_xwebconfigkeyvalue[:dsc_configsection] = 'AppSettings' expect(dsc_xwebconfigkeyvalue[:dsc_configsection]).to eq('AppSettings') end it 'should accept dsc_configsection predefined value appsettings' do dsc_xwebconfigkeyvalue[:dsc_configsection] = 'appsettings' expect(dsc_xwebconfigkeyvalue[:dsc_configsection]).to eq('appsettings') end it 'should not accept values not equal to predefined values' do expect{dsc_xwebconfigkeyvalue[:dsc_configsection] = 'invalid value'}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_configsection' do expect{dsc_xwebconfigkeyvalue[:dsc_configsection] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_configsection' do expect{dsc_xwebconfigkeyvalue[:dsc_configsection] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_configsection' do expect{dsc_xwebconfigkeyvalue[:dsc_configsection] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_configsection' do expect{dsc_xwebconfigkeyvalue[:dsc_configsection] = 16}.to raise_error(Puppet::ResourceError) end it 'should accept dsc_ensure predefined value Present' do dsc_xwebconfigkeyvalue[:dsc_ensure] = 'Present' expect(dsc_xwebconfigkeyvalue[:dsc_ensure]).to eq('Present') end it 'should accept dsc_ensure predefined value present' do dsc_xwebconfigkeyvalue[:dsc_ensure] = 'present' expect(dsc_xwebconfigkeyvalue[:dsc_ensure]).to eq('present') end it 'should accept dsc_ensure predefined value present and update ensure with this value (ensure end value should be a symbol)' do dsc_xwebconfigkeyvalue[:dsc_ensure] = 'present' expect(dsc_xwebconfigkeyvalue[:ensure]).to eq(dsc_xwebconfigkeyvalue[:dsc_ensure].downcase.to_sym) end it 'should accept dsc_ensure predefined value Absent' do dsc_xwebconfigkeyvalue[:dsc_ensure] = 'Absent' expect(dsc_xwebconfigkeyvalue[:dsc_ensure]).to eq('Absent') end it 'should accept dsc_ensure predefined value absent' do dsc_xwebconfigkeyvalue[:dsc_ensure] = 'absent' expect(dsc_xwebconfigkeyvalue[:dsc_ensure]).to eq('absent') end it 'should accept dsc_ensure predefined value absent and update ensure with this value (ensure end value should be a symbol)' do dsc_xwebconfigkeyvalue[:dsc_ensure] = 'absent' expect(dsc_xwebconfigkeyvalue[:ensure]).to eq(dsc_xwebconfigkeyvalue[:dsc_ensure].downcase.to_sym) end it 'should not accept values not equal to predefined values' do expect{dsc_xwebconfigkeyvalue[:dsc_ensure] = 'invalid value'}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_ensure' do expect{dsc_xwebconfigkeyvalue[:dsc_ensure] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_ensure' do expect{dsc_xwebconfigkeyvalue[:dsc_ensure] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_ensure' do expect{dsc_xwebconfigkeyvalue[:dsc_ensure] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_ensure' do expect{dsc_xwebconfigkeyvalue[:dsc_ensure] = 16}.to raise_error(Puppet::ResourceError) end it 'should require that dsc_key is specified' do #dsc_xwebconfigkeyvalue[:dsc_key] expect { Puppet::Type.type(:dsc_xwebconfigkeyvalue).new( :name => 'foo', :dsc_websitepath => 'foo', :dsc_configsection => 'AppSettings', :dsc_ensure => 'Present', :dsc_value => 'foo', :dsc_isattribute => true, )}.to raise_error(Puppet::Error, /dsc_key is a required attribute/) end it 'should not accept array for dsc_key' do expect{dsc_xwebconfigkeyvalue[:dsc_key] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_key' do expect{dsc_xwebconfigkeyvalue[:dsc_key] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_key' do expect{dsc_xwebconfigkeyvalue[:dsc_key] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_key' do expect{dsc_xwebconfigkeyvalue[:dsc_key] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_value' do expect{dsc_xwebconfigkeyvalue[:dsc_value] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_value' do expect{dsc_xwebconfigkeyvalue[:dsc_value] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_value' do expect{dsc_xwebconfigkeyvalue[:dsc_value] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_value' do expect{dsc_xwebconfigkeyvalue[:dsc_value] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_isattribute' do expect{dsc_xwebconfigkeyvalue[:dsc_isattribute] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should accept boolean for dsc_isattribute' do dsc_xwebconfigkeyvalue[:dsc_isattribute] = true expect(dsc_xwebconfigkeyvalue[:dsc_isattribute]).to eq(true) end it "should accept boolean-like value 'true' and munge this value to boolean for dsc_isattribute" do dsc_xwebconfigkeyvalue[:dsc_isattribute] = 'true' expect(dsc_xwebconfigkeyvalue[:dsc_isattribute]).to eq(true) end it "should accept boolean-like value 'false' and munge this value to boolean for dsc_isattribute" do dsc_xwebconfigkeyvalue[:dsc_isattribute] = 'false' expect(dsc_xwebconfigkeyvalue[:dsc_isattribute]).to eq(false) end it "should accept boolean-like value 'True' and munge this value to boolean for dsc_isattribute" do dsc_xwebconfigkeyvalue[:dsc_isattribute] = 'True' expect(dsc_xwebconfigkeyvalue[:dsc_isattribute]).to eq(true) end it "should accept boolean-like value 'False' and munge this value to boolean for dsc_isattribute" do dsc_xwebconfigkeyvalue[:dsc_isattribute] = 'False' expect(dsc_xwebconfigkeyvalue[:dsc_isattribute]).to eq(false) end it "should accept boolean-like value :true and munge this value to boolean for dsc_isattribute" do dsc_xwebconfigkeyvalue[:dsc_isattribute] = :true expect(dsc_xwebconfigkeyvalue[:dsc_isattribute]).to eq(true) end it "should accept boolean-like value :false and munge this value to boolean for dsc_isattribute" do dsc_xwebconfigkeyvalue[:dsc_isattribute] = :false expect(dsc_xwebconfigkeyvalue[:dsc_isattribute]).to eq(false) end it 'should not accept int for dsc_isattribute' do expect{dsc_xwebconfigkeyvalue[:dsc_isattribute] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_isattribute' do expect{dsc_xwebconfigkeyvalue[:dsc_isattribute] = 16}.to raise_error(Puppet::ResourceError) end # Configuration PROVIDER TESTS describe "powershell provider tests" do it "should successfully instanciate the provider" do described_class.provider(:powershell).new(dsc_xwebconfigkeyvalue) end before(:each) do @provider = described_class.provider(:powershell).new(dsc_xwebconfigkeyvalue) end describe "when dscmeta_import_resource is true (default) and dscmeta_module_name existing/is defined " do it "should compute powershell dsc test script with Invoke-DscResource" do expect(@provider.ps_script_content('test')).to match(/Invoke-DscResource/) end it "should compute powershell dsc test script with method Test" do expect(@provider.ps_script_content('test')).to match(/Method\s+=\s*'test'/) end it "should compute powershell dsc set script with Invoke-DscResource" do expect(@provider.ps_script_content('set')).to match(/Invoke-DscResource/) end it "should compute powershell dsc test script with method Set" do expect(@provider.ps_script_content('set')).to match(/Method\s+=\s*'set'/) end end describe "when dsc_ensure is 'present'" do before(:each) do dsc_xwebconfigkeyvalue.original_parameters[:dsc_ensure] = 'present' dsc_xwebconfigkeyvalue[:dsc_ensure] = 'present' @provider = described_class.provider(:powershell).new(dsc_xwebconfigkeyvalue) end it "should update :ensure to :present" do expect(dsc_xwebconfigkeyvalue[:ensure]).to eq(:present) end it "should compute powershell dsc test script in which ensure value is 'present'" do expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/) end it "should compute powershell dsc set script in which ensure value is 'present'" do expect(@provider.ps_script_content('set')).to match(/ensure = 'present'/) end end describe "when dsc_ensure is 'absent'" do before(:each) do dsc_xwebconfigkeyvalue.original_parameters[:dsc_ensure] = 'absent' dsc_xwebconfigkeyvalue[:dsc_ensure] = 'absent' @provider = described_class.provider(:powershell).new(dsc_xwebconfigkeyvalue) end it "should update :ensure to :absent" do expect(dsc_xwebconfigkeyvalue[:ensure]).to eq(:absent) end it "should compute powershell dsc test script in which ensure value is 'present'" do expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/) end it "should compute powershell dsc set script in which ensure value is 'absent'" do expect(@provider.ps_script_content('set')).to match(/ensure = 'absent'/) end end end end
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-guardduty/src/main/java/com/amazonaws/services/guardduty/model/transform/AccessKeyDetailsJsonUnmarshaller.java
3481
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.guardduty.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.guardduty.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * AccessKeyDetails JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AccessKeyDetailsJsonUnmarshaller implements Unmarshaller<AccessKeyDetails, JsonUnmarshallerContext> { public AccessKeyDetails unmarshall(JsonUnmarshallerContext context) throws Exception { AccessKeyDetails accessKeyDetails = new AccessKeyDetails(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("accessKeyId", targetDepth)) { context.nextToken(); accessKeyDetails.setAccessKeyId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("principalId", targetDepth)) { context.nextToken(); accessKeyDetails.setPrincipalId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("userName", targetDepth)) { context.nextToken(); accessKeyDetails.setUserName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("userType", targetDepth)) { context.nextToken(); accessKeyDetails.setUserType(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return accessKeyDetails; } private static AccessKeyDetailsJsonUnmarshaller instance; public static AccessKeyDetailsJsonUnmarshaller getInstance() { if (instance == null) instance = new AccessKeyDetailsJsonUnmarshaller(); return instance; } }
apache-2.0
flipkart-incubator/Lyrics
lyrics-core/src/main/java/com/flipkart/lyrics/annotators/AnnotatorStyle.java
1716
/* * Copyright 2016 Flipkart Internet, pvt ltd. * * 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.flipkart.lyrics.annotators; import com.flipkart.lyrics.model.FieldModel; import com.flipkart.lyrics.model.TypeModel; import com.flipkart.lyrics.specs.FieldSpec; import com.flipkart.lyrics.specs.MethodSpec; import com.flipkart.lyrics.specs.TypeSpec; import java.util.List; /** * Created by shrey.garg on 03/01/17. */ public abstract class AnnotatorStyle { public abstract void processNamedAsRule(FieldSpec.Builder fieldSpec, FieldModel fieldModel); public abstract void processInclusionRule(FieldSpec.Builder fieldSpec, FieldModel fieldModel); public abstract void processGlobalInclusionRule(TypeSpec.Builder typeSpec, TypeModel typeModel); public abstract void processSubTypeRule(TypeSpec.Builder typeSpec, TypeModel typeModel); public abstract void processIgnoreUnknownsRule(TypeSpec.Builder typeSpec, TypeModel typeModel); public abstract void processPropertyOrderRule(TypeSpec.Builder typeSpec, TypeModel typeModel); public abstract void processConstructorOrderRule(MethodSpec.Builder methodSpec, TypeModel typeModel, List<String> constructorFields); }
apache-2.0
orioncode/orionplatform
orion_math/orion_math_core/src/main/java/com/orionplatform/math/linearalgebra/matrix/generic/GenericMatrixInternalService.java
932
package com.orionplatform.math.linearalgebra.matrix.generic; import com.orionplatform.math.MathObject; import com.orionplatform.math.geometry.vector.generic.GenericVector; import com.orionplatform.math.linearalgebra.matrix.generic.tasks.GenericMatrixEqualsTask; import com.orionplatform.math.linearalgebra.matrix.generic.tasks.GenericMatrixHashCodeTask; import com.orionplatform.math.linearalgebra.matrix.generic.tasks.GenericMatrixOfDiagonalTask; class GenericMatrixInternalService implements MathObject { static synchronized boolean equals(GenericMatrix x, Object y) { return GenericMatrixEqualsTask.run(x, y); } static synchronized int hashCode(GenericMatrix x) { return GenericMatrixHashCodeTask.run(x); } static synchronized GenericMatrix ofDiagonal(GenericVector diagonalElements) { return GenericMatrixOfDiagonalTask.run(diagonalElements); } }
apache-2.0
MayankGo/ec2-api
ec2api/openstack/common/service.py
15202
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # 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. """Generic Node base class for all workers that run on hosts.""" import errno import logging import os import random import signal import sys import time try: # Importing just the symbol here because the io module does not # exist in Python 2.6. from io import UnsupportedOperation # noqa except ImportError: # Python 2.6 UnsupportedOperation = None import eventlet from eventlet import event from oslo_config import cfg from ec2api.openstack.common import eventlet_backdoor from ec2api.openstack.common._i18n import _LE, _LI, _LW from ec2api.openstack.common import systemd from ec2api.openstack.common import threadgroup CONF = cfg.CONF LOG = logging.getLogger(__name__) def _sighup_supported(): return hasattr(signal, 'SIGHUP') def _is_daemon(): # The process group for a foreground process will match the # process group of the controlling terminal. If those values do # not match, or ioctl() fails on the stdout file handle, we assume # the process is running in the background as a daemon. # http://www.gnu.org/software/bash/manual/bashref.html#Job-Control-Basics try: is_daemon = os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()) except OSError as err: if err.errno == errno.ENOTTY: # Assume we are a daemon because there is no terminal. is_daemon = True else: raise except UnsupportedOperation: # Could not get the fileno for stdout, so we must be a daemon. is_daemon = True return is_daemon def _is_sighup_and_daemon(signo): if not (_sighup_supported() and signo == signal.SIGHUP): # Avoid checking if we are a daemon, because the signal isn't # SIGHUP. return False return _is_daemon() def _signo_to_signame(signo): signals = {signal.SIGTERM: 'SIGTERM', signal.SIGINT: 'SIGINT'} if _sighup_supported(): signals[signal.SIGHUP] = 'SIGHUP' return signals[signo] def _set_signals_handler(handler): signal.signal(signal.SIGTERM, handler) signal.signal(signal.SIGINT, handler) if _sighup_supported(): signal.signal(signal.SIGHUP, handler) class Launcher(object): """Launch one or more services and wait for them to complete.""" def __init__(self): """Initialize the service launcher. :returns: None """ self.services = Services() self.backdoor_port = eventlet_backdoor.initialize_if_enabled() def launch_service(self, service): """Load and start the given service. :param service: The service you would like to start. :returns: None """ service.backdoor_port = self.backdoor_port self.services.add(service) def stop(self): """Stop all services which are currently running. :returns: None """ self.services.stop() def wait(self): """Waits until all services have been stopped, and then returns. :returns: None """ self.services.wait() def restart(self): """Reload config files and restart service. :returns: None """ cfg.CONF.reload_config_files() self.services.restart() class SignalExit(SystemExit): def __init__(self, signo, exccode=1): super(SignalExit, self).__init__(exccode) self.signo = signo class ServiceLauncher(Launcher): def _handle_signal(self, signo, frame): # Allow the process to be killed again and die from natural causes _set_signals_handler(signal.SIG_DFL) raise SignalExit(signo) def handle_signal(self): _set_signals_handler(self._handle_signal) def _wait_for_exit_or_signal(self, ready_callback=None): status = None signo = 0 LOG.debug('Full set of CONF:') CONF.log_opt_values(LOG, logging.DEBUG) try: if ready_callback: ready_callback() super(ServiceLauncher, self).wait() except SignalExit as exc: signame = _signo_to_signame(exc.signo) LOG.info(_LI('Caught %s, exiting'), signame) status = exc.code signo = exc.signo except SystemExit as exc: status = exc.code finally: self.stop() return status, signo def wait(self, ready_callback=None): systemd.notify_once() while True: self.handle_signal() status, signo = self._wait_for_exit_or_signal(ready_callback) if not _is_sighup_and_daemon(signo): return status self.restart() class ServiceWrapper(object): def __init__(self, service, workers): self.service = service self.workers = workers self.children = set() self.forktimes = [] class ProcessLauncher(object): _signal_handlers_set = set() @classmethod def _handle_class_signals(cls, *args, **kwargs): for handler in cls._signal_handlers_set: handler(*args, **kwargs) def __init__(self): """Constructor.""" self.children = {} self.sigcaught = None self.running = True rfd, self.writepipe = os.pipe() self.readpipe = eventlet.greenio.GreenPipe(rfd, 'r') self.handle_signal() def handle_signal(self): self._signal_handlers_set.add(self._handle_signal) _set_signals_handler(self._handle_class_signals) def _handle_signal(self, signo, frame): self.sigcaught = signo self.running = False # Allow the process to be killed again and die from natural causes _set_signals_handler(signal.SIG_DFL) def _pipe_watcher(self): # This will block until the write end is closed when the parent # dies unexpectedly self.readpipe.read() LOG.info(_LI('Parent process has died unexpectedly, exiting')) sys.exit(1) def _child_process_handle_signal(self): # Setup child signal handlers differently def _sigterm(*args): signal.signal(signal.SIGTERM, signal.SIG_DFL) raise SignalExit(signal.SIGTERM) def _sighup(*args): signal.signal(signal.SIGHUP, signal.SIG_DFL) raise SignalExit(signal.SIGHUP) signal.signal(signal.SIGTERM, _sigterm) if _sighup_supported(): signal.signal(signal.SIGHUP, _sighup) # Block SIGINT and let the parent send us a SIGTERM signal.signal(signal.SIGINT, signal.SIG_IGN) def _child_wait_for_exit_or_signal(self, launcher): status = 0 signo = 0 # NOTE(johannes): All exceptions are caught to ensure this # doesn't fallback into the loop spawning children. It would # be bad for a child to spawn more children. try: launcher.wait() except SignalExit as exc: signame = _signo_to_signame(exc.signo) LOG.info(_LI('Child caught %s, exiting'), signame) status = exc.code signo = exc.signo except SystemExit as exc: status = exc.code except BaseException: LOG.exception(_LE('Unhandled exception')) status = 2 finally: launcher.stop() return status, signo def _child_process(self, service): self._child_process_handle_signal() # Reopen the eventlet hub to make sure we don't share an epoll # fd with parent and/or siblings, which would be bad eventlet.hubs.use_hub() # Close write to ensure only parent has it open os.close(self.writepipe) # Create greenthread to watch for parent to close pipe eventlet.spawn_n(self._pipe_watcher) # Reseed random number generator random.seed() launcher = Launcher() launcher.launch_service(service) return launcher def _start_child(self, wrap): if len(wrap.forktimes) > wrap.workers: # Limit ourselves to one process a second (over the period of # number of workers * 1 second). This will allow workers to # start up quickly but ensure we don't fork off children that # die instantly too quickly. if time.time() - wrap.forktimes[0] < wrap.workers: LOG.info(_LI('Forking too fast, sleeping')) time.sleep(1) wrap.forktimes.pop(0) wrap.forktimes.append(time.time()) pid = os.fork() if pid == 0: launcher = self._child_process(wrap.service) while True: self._child_process_handle_signal() status, signo = self._child_wait_for_exit_or_signal(launcher) if not _is_sighup_and_daemon(signo): break launcher.restart() os._exit(status) LOG.info(_LI('Started child %d'), pid) wrap.children.add(pid) self.children[pid] = wrap return pid def launch_service(self, service, workers=1): wrap = ServiceWrapper(service, workers) LOG.info(_LI('Starting %d workers'), wrap.workers) while self.running and len(wrap.children) < wrap.workers: self._start_child(wrap) def _wait_child(self): try: # Block while any of child processes have exited pid, status = os.waitpid(0, 0) if not pid: return None except OSError as exc: if exc.errno not in (errno.EINTR, errno.ECHILD): raise return None if os.WIFSIGNALED(status): sig = os.WTERMSIG(status) LOG.info(_LI('Child %(pid)d killed by signal %(sig)d'), dict(pid=pid, sig=sig)) else: code = os.WEXITSTATUS(status) LOG.info(_LI('Child %(pid)s exited with status %(code)d'), dict(pid=pid, code=code)) if pid not in self.children: LOG.warning(_LW('pid %d not in child list'), pid) return None wrap = self.children.pop(pid) wrap.children.remove(pid) return wrap def _respawn_children(self): while self.running: wrap = self._wait_child() if not wrap: continue while self.running and len(wrap.children) < wrap.workers: self._start_child(wrap) def wait(self): """Loop waiting on children to die and respawning as necessary.""" systemd.notify_once() LOG.debug('Full set of CONF:') CONF.log_opt_values(LOG, logging.DEBUG) try: while True: self.handle_signal() self._respawn_children() # No signal means that stop was called. Don't clean up here. if not self.sigcaught: return signame = _signo_to_signame(self.sigcaught) LOG.info(_LI('Caught %s, stopping children'), signame) if not _is_sighup_and_daemon(self.sigcaught): break cfg.CONF.reload_config_files() for service in set( [wrap.service for wrap in self.children.values()]): service.reset() for pid in self.children: os.kill(pid, signal.SIGHUP) self.running = True self.sigcaught = None except eventlet.greenlet.GreenletExit: LOG.info(_LI("Wait called after thread killed. Cleaning up.")) self.stop() def stop(self): """Terminate child processes and wait on each.""" self.running = False for pid in self.children: try: os.kill(pid, signal.SIGTERM) except OSError as exc: if exc.errno != errno.ESRCH: raise # Wait for children to die if self.children: LOG.info(_LI('Waiting on %d children to exit'), len(self.children)) while self.children: self._wait_child() class Service(object): """Service object for binaries running on hosts.""" def __init__(self, threads=1000): self.tg = threadgroup.ThreadGroup(threads) # signal that the service is done shutting itself down: self._done = event.Event() def reset(self): # NOTE(Fengqian): docs for Event.reset() recommend against using it self._done = event.Event() def start(self): pass def stop(self, graceful=False): self.tg.stop(graceful) self.tg.wait() # Signal that service cleanup is done: if not self._done.ready(): self._done.send() def wait(self): self._done.wait() class Services(object): def __init__(self): self.services = [] self.tg = threadgroup.ThreadGroup() self.done = event.Event() def add(self, service): self.services.append(service) self.tg.add_thread(self.run_service, service, self.done) def stop(self): # wait for graceful shutdown of services: for service in self.services: service.stop() service.wait() # Each service has performed cleanup, now signal that the run_service # wrapper threads can now die: if not self.done.ready(): self.done.send() # reap threads: self.tg.stop() def wait(self): self.tg.wait() def restart(self): self.stop() self.done = event.Event() for restart_service in self.services: restart_service.reset() self.tg.add_thread(self.run_service, restart_service, self.done) @staticmethod def run_service(service, done): """Service start wrapper. :param service: service to run :param done: event to wait on until a shutdown is triggered :returns: None """ service.start() done.wait() def launch(service, workers=1): if workers is None or workers == 1: launcher = ServiceLauncher() launcher.launch_service(service) else: launcher = ProcessLauncher() launcher.launch_service(service, workers=workers) return launcher
apache-2.0