code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.sequenceiq.cloudbreak.validation.customimage; import com.sequenceiq.cloudbreak.api.endpoint.v4.customimage.request.CustomImageCatalogV4VmImageRequest; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class UniqueRegionValidatorTest { private UniqueRegionValidator victim; @Before public void setUp() { victim = new UniqueRegionValidator(); } @Test public void testValid() { assertTrue(victim.isValid(withRegions("region1", "region2"), null)); } @Test public void testValidEmpty() { assertTrue(victim.isValid(Collections.emptySet(), null)); } @Test public void testValidNull() { assertTrue(victim.isValid(null, null)); } @Test public void testInvalid() { assertFalse(victim.isValid(withRegions("region1", "region1"), null)); } private Set<CustomImageCatalogV4VmImageRequest> withRegions(String... regions) { return Arrays.stream(regions).map(r -> { CustomImageCatalogV4VmImageRequest item = new CustomImageCatalogV4VmImageRequest(); item.setRegion(r); return item; }).collect(Collectors.toSet()); } }
hortonworks/cloudbreak
core-api/src/test/java/com/sequenceiq/cloudbreak/validation/customimage/UniqueRegionValidatorTest.java
Java
apache-2.0
1,393
package toolbox_test import ( "github.com/stretchr/testify/assert" "github.com/viant/toolbox" "github.com/viant/toolbox/url" "testing" ) func TestExtractURIParameters(t *testing.T) { { parameters, matched := toolbox.ExtractURIParameters("/v1/path/{app}/{version}/", "/v1/path/app/1.0/?v=12") assert.True(t, matched) if !matched { t.FailNow() } assert.Equal(t, 2, len(parameters)) assert.Equal(t, "app", parameters["app"]) assert.Equal(t, "1.0", parameters["version"]) } { parameters, matched := toolbox.ExtractURIParameters("/v1/path/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abc") assert.True(t, matched) assert.Equal(t, 3, len(parameters)) assert.Equal(t, "1,2,3,4,5", parameters["ids"]) assert.Equal(t, "subpath", parameters["sub"]) assert.Equal(t, "abc", parameters["name"]) } { parameters, matched := toolbox.ExtractURIParameters("/v1/path/{ids}", "/v1/path/this-is-test") assert.True(t, matched) assert.Equal(t, 1, len(parameters)) assert.Equal(t, "this-is-test", parameters["ids"]) } { _, matched := toolbox.ExtractURIParameters("/v2/path/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abc") assert.False(t, matched) } { _, matched := toolbox.ExtractURIParameters("/v1/path1/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abc") assert.False(t, matched) } { _, matched := toolbox.ExtractURIParameters("/v1/path1/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abc") assert.False(t, matched) } { _, matched := toolbox.ExtractURIParameters("/v1/path/{ids}", "/v1/path/1") assert.True(t, matched) } { _, matched := toolbox.ExtractURIParameters("/v1/reverse/", "/v1/reverse/") assert.True(t, matched) } { parameters, matched := toolbox.ExtractURIParameters("/v1/path/{ids}/{sub}/a/{name}", "/v1/path/1,2,3,4,5/subpath/a/abcwrwr") assert.True(t, matched) assert.Equal(t, 3, len(parameters)) assert.Equal(t, "1,2,3,4,5", parameters["ids"]) assert.Equal(t, "subpath", parameters["sub"]) assert.Equal(t, "abcwrwr", parameters["name"]) } } func TestURLBase(t *testing.T) { URL := "http://github.com/abc" baseURL := toolbox.URLBase(URL) assert.Equal(t, "http://github.com", baseURL) } func TestURLSplit(t *testing.T) { { URL := "http://github.com/abc/trter/rds" parentURL, resource := toolbox.URLSplit(URL) assert.Equal(t, "http://github.com/abc/trter", parentURL) assert.Equal(t, "rds", resource) } } func TestURLStripPath(t *testing.T) { { URL := "http://github.com/abc" assert.EqualValues(t, "http://github.com", toolbox.URLStripPath(URL)) } { URL := "http://github.com" assert.EqualValues(t, "http://github.com", toolbox.URLStripPath(URL)) } } func TestURL_Rename(t *testing.T) { { URL := "http://github.com/abc/" resource := url.NewResource(URL) resource.Rename("/tmp/abc") assert.Equal(t, "http://github.com//tmp/abc", resource.URL) } } func TestURLPathJoin(t *testing.T) { { URL := "http://github.com/abc" assert.EqualValues(t, "http://github.com/abc/path/a.txt", toolbox.URLPathJoin(URL, "path/a.txt")) } { URL := "http://github.com/abc/" assert.EqualValues(t, "http://github.com/abc/path/a.txt", toolbox.URLPathJoin(URL, "path/a.txt")) } { URL := "http://github.com/abc/" assert.EqualValues(t, "http://github.com/a.txt", toolbox.URLPathJoin(URL, "/a.txt")) } }
viant/toolbox
uri_test.go
GO
apache-2.0
3,363
package gov.cdc.sdp.cbr; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.camel.CamelContext; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.DefaultExchange; import org.apache.camel.test.spring.CamelSpringJUnit4ClassRunner; import org.apache.camel.test.spring.CamelTestContextBootstrapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.BootstrapWith; import org.springframework.test.context.ContextConfiguration; import de.saly.javamail.mock2.MockMailbox; @RunWith(CamelSpringJUnit4ClassRunner.class) @BootstrapWith(CamelTestContextBootstrapper.class) @ContextConfiguration(locations = { "classpath:EmailOnException.xml" }) @PropertySource("classpath:application.properties") public class EmailOnExceptionTest extends BaseDBTest { Object lock = new Object(); String address = "cbr_errors@cdc.gov"; @Autowired protected CamelContext camelContext; @EndpointInject(uri = "mock:mock_endpoint") protected MockEndpoint mockEndpoint; @Produce(uri = "direct:start") protected ProducerTemplate template; @Before public void setup() throws SQLException, IOException { MockMailbox.resetAll(); synchronized (lock) { mockEndpoint.reset(); DataSource ds = (DataSource) camelContext.getRegistry().lookupByName("sdpqDataSource"); super.setupDb(ds); } } @Test public void noS3AtUriTest() throws Exception { assertEquals("Should be 0 messages in inbox", 0, MockMailbox.get(address).getInbox().getMessageCount()); mockEndpoint.expectedMessageCount(1); Exchange exchange = new DefaultExchange(camelContext); template.send(exchange); mockEndpoint.assertIsSatisfied(); assertEquals("Should be 1 message in inbox", 1, MockMailbox.get(address).getInbox().getMessageCount()); } }
CDCgov/SDP-CBR
phinms/src/test/java/gov/cdc/sdp/cbr/EmailOnExceptionTest.java
Java
apache-2.0
2,315
๏ปฟusing UnityEngine; using System.Collections; public class CanvasHandler : MonoBehaviour { // Use this for initialization void Awake() { LeanTween.addListener((int)Events.ENERGYPOWERIN, OnEnergyPowerIn); LeanTween.addListener((int)Events.ENERGYPOWEROUT, OnEnergyPowerOut); } public void OnDestroy() { LeanTween.removeListener((int)Events.ENERGYPOWERIN, OnEnergyPowerIn); LeanTween.removeListener((int)Events.ENERGYPOWEROUT, OnEnergyPowerOut); } void OnEnergyPowerIn(LTEvent evt) { gameObject.SetActive(false); } void OnEnergyPowerOut(LTEvent evt) { gameObject.SetActive(true); } }
yantian001/2DShooting
Assets/2DShooting/Scripts/UI/CanvasHandler.cs
C#
apache-2.0
692
public class SuperWildCardDemo { public static void main(String[] args) { GenericStack<String> stack1 = new GenericStack<String>(); GenericStack<Object> stack2 = new GenericStack<Object>(); stack2.push("Java"); stack2.push(2); stack1.push("Sun"); add(stack1, stack2); AnyWildCardDemo.print(stack2); } public static <T> void add(GenericStack<T> stack1, GenericStack<? super T> stack2) { while (!stack1.isEmpty()) stack2.push(stack1.pop()); } }
txs72/BUPTJava
slides/19/examples/SuperWildCardDemo.java
Java
apache-2.0
511
# -*- coding: utf-8 -*- # Copyright 2020 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. # import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.ads.googleads.v9.resources.types import bidding_strategy from google.ads.googleads.v9.services.types import bidding_strategy_service from .base import BiddingStrategyServiceTransport, DEFAULT_CLIENT_INFO class BiddingStrategyServiceGrpcTransport(BiddingStrategyServiceTransport): """gRPC backend transport for BiddingStrategyService. Service to manage bidding strategies. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ self._ssl_channel_credentials = ssl_channel_credentials if channel: # Sanity check: Ensure that channel and credentials are not both # provided. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None elif api_mtls_endpoint: warnings.warn( "api_mtls_endpoint and client_cert_source are deprecated", DeprecationWarning, ) host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) if credentials is None: credentials, _ = google.auth.default( scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id ) # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._ssl_channel_credentials = ssl_credentials else: host = host if ":" in host else host + ":443" if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, ssl_credentials=ssl_channel_credentials, scopes=self.AUTH_SCOPES, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._stubs = {} # type: Dict[str, Callable] # Run the base constructor. super().__init__( host=host, credentials=credentials, client_info=client_info, ) @classmethod def create_channel( cls, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, scopes: Optional[Sequence[str]] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: address (Optionsl[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. """ return grpc_helpers.create_channel( host, credentials=credentials, scopes=scopes or cls.AUTH_SCOPES, **kwargs, ) def close(self): self.grpc_channel.close() @property def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service. """ return self._grpc_channel @property def get_bidding_strategy( self, ) -> Callable[ [bidding_strategy_service.GetBiddingStrategyRequest], bidding_strategy.BiddingStrategy, ]: r"""Return a callable for the get bidding strategy method over gRPC. Returns the requested bidding strategy in full detail. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RequestError <>`__ Returns: Callable[[~.GetBiddingStrategyRequest], ~.BiddingStrategy]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_bidding_strategy" not in self._stubs: self._stubs["get_bidding_strategy"] = self.grpc_channel.unary_unary( "/google.ads.googleads.v9.services.BiddingStrategyService/GetBiddingStrategy", request_serializer=bidding_strategy_service.GetBiddingStrategyRequest.serialize, response_deserializer=bidding_strategy.BiddingStrategy.deserialize, ) return self._stubs["get_bidding_strategy"] @property def mutate_bidding_strategies( self, ) -> Callable[ [bidding_strategy_service.MutateBiddingStrategiesRequest], bidding_strategy_service.MutateBiddingStrategiesResponse, ]: r"""Return a callable for the mutate bidding strategies method over gRPC. Creates, updates, or removes bidding strategies. Operation statuses are returned. List of thrown errors: `AdxError <>`__ `AuthenticationError <>`__ `AuthorizationError <>`__ `BiddingError <>`__ `BiddingStrategyError <>`__ `ContextError <>`__ `DatabaseError <>`__ `DateError <>`__ `DistinctError <>`__ `FieldError <>`__ `FieldMaskError <>`__ `HeaderError <>`__ `IdError <>`__ `InternalError <>`__ `MutateError <>`__ `NewResourceCreationError <>`__ `NotEmptyError <>`__ `NullError <>`__ `OperationAccessDeniedError <>`__ `OperatorError <>`__ `QuotaError <>`__ `RangeError <>`__ `RequestError <>`__ `SizeLimitError <>`__ `StringFormatError <>`__ `StringLengthError <>`__ Returns: Callable[[~.MutateBiddingStrategiesRequest], ~.MutateBiddingStrategiesResponse]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "mutate_bidding_strategies" not in self._stubs: self._stubs[ "mutate_bidding_strategies" ] = self.grpc_channel.unary_unary( "/google.ads.googleads.v9.services.BiddingStrategyService/MutateBiddingStrategies", request_serializer=bidding_strategy_service.MutateBiddingStrategiesRequest.serialize, response_deserializer=bidding_strategy_service.MutateBiddingStrategiesResponse.deserialize, ) return self._stubs["mutate_bidding_strategies"] __all__ = ("BiddingStrategyServiceGrpcTransport",)
googleads/google-ads-python
google/ads/googleads/v9/services/services/bidding_strategy_service/transports/grpc.py
Python
apache-2.0
12,551
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; namespace iWay.RemoteControlBase.Protocol.RemoteExplorer.Requests { public class RenameContentReq : BasicReq { public string ContentPath; public string NewContentName; } }
iWay7/RemoteControl
RemoteControlBase/Protocol/RemoteExplorer/Requests/RenameContentReq.cs
C#
apache-2.0
291
/** * @license * Copyright 2016 Google Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {GL} from 'neuroglancer/webgl/context'; /** * Sets parameters to make a texture suitable for use as a raw array: NEAREST * filtering, clamping. */ export function setRawTextureParameters(gl: WebGLRenderingContext) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Prevents s-coordinate wrapping (repeating). Repeating not // permitted for non-power-of-2 textures. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); // Prevents t-coordinate wrapping (repeating). Repeating not // permitted for non-power-of-2 textures. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } export function resizeTexture( gl: GL, texture: WebGLTexture|null, width: number, height: number, format: number = gl.RGBA, dataType: number = gl.UNSIGNED_BYTE) { gl.activeTexture(gl.TEXTURE0 + gl.tempTextureUnit); gl.bindTexture(gl.TEXTURE_2D, texture); setRawTextureParameters(gl); gl.texImage2D( gl.TEXTURE_2D, 0, /*internalformat=*/format, /*width=*/width, /*height=*/height, /*border=*/0, /*format=*/format, dataType, <any>null); gl.bindTexture(gl.TEXTURE_2D, null); }
funkey/neuroglancer
src/neuroglancer/webgl/texture.ts
TypeScript
apache-2.0
1,865
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * 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.jiumao.remote.exception; /** * ๅผ‚ๆญฅ่ฐƒ็”จๆˆ–่€…Oneway่ฐƒ็”จ๏ผŒๅ †็งฏ็š„่ฏทๆฑ‚่ถ…่ฟ‡ไฟกๅท้‡ๆœ€ๅคงๅ€ผ * * @author shijia.wxr<vintage.wang@gmail.com> * @since 2013-7-13 */ public class RemotingTooMuchRequestException extends RemotingException { private static final long serialVersionUID = 4326919581254519654L; public RemotingTooMuchRequestException(String message) { super(message); } }
jiumao-org/wechat-mall
mall-remoting/src/main/java/org/jiumao/remote/exception/RemotingTooMuchRequestException.java
Java
apache-2.0
1,085
/** * Copyright (C) 2015 Zalando SE (http://tech.zalando.com) * * 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.zalando.stups.tokens; import java.io.File; import com.fasterxml.jackson.databind.ObjectMapper; public abstract class AbstractJsonFileBackedCredentialsProvider { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final FileSupplier fileSupplier; public AbstractJsonFileBackedCredentialsProvider(final String filename) { this.fileSupplier = new FileSupplier(filename); } public AbstractJsonFileBackedCredentialsProvider(final File file) { this.fileSupplier = new FileSupplier(file); } protected File getFile() { return fileSupplier.get(); } protected <T> T read(final Class<T> cls) { try { return OBJECT_MAPPER.readValue(getFile(), cls); } catch (final Throwable e) { throw new CredentialsUnavailableException(e.getMessage(), e); } } }
zalando-stups/tokens
src/main/java/org/zalando/stups/tokens/AbstractJsonFileBackedCredentialsProvider.java
Java
apache-2.0
1,522
package io.quarkus.arc.test.unused; import static org.junit.jupiter.api.Assertions.assertTrue; import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.test.ArcTestContainer; import javax.enterprise.context.Dependent; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.InterceptionType; import javax.enterprise.util.AnnotationLiteral; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class RemoveUnusedInterceptorTest extends RemoveUnusedComponentsTest { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(HasObserver.class, Alpha.class, AlphaInterceptor.class, Counter.class, Bravo.class, BravoInterceptor.class) .removeUnusedBeans(true) .build(); @SuppressWarnings("serial") @Test public void testRemoval() { ArcContainer container = Arc.container(); assertPresent(HasObserver.class); assertNotPresent(Counter.class); // Both AlphaInterceptor and BravoInterceptor were removed assertTrue(container.beanManager().resolveInterceptors(InterceptionType.AROUND_INVOKE, new AnnotationLiteral<Alpha>() { }).isEmpty()); assertTrue(container.beanManager().resolveInterceptors(InterceptionType.AROUND_INVOKE, new AnnotationLiteral<Bravo>() { }).isEmpty()); } @Dependent static class HasObserver { void observe(@Observes String event) { } } }
quarkusio/quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/unused/RemoveUnusedInterceptorTest.java
Java
apache-2.0
1,563
__author__ = 'wangxun' """def double(list): i=0 while i <len(list): print i list[i]=list[i]*2 i+=1 return(list) """ def doulbe(list): i=0 [list[i]=list[i]*2 while i<len(list)] return(list) print double([1,2,3,4])
wonstonx/wxgittest
day2 test1.py
Python
apache-2.0
266
package net.orangemile.informatica.powercenter.domain; import java.util.ArrayList; import java.util.List; import net.orangemile.informatica.powercenter.domain.constant.InstanceType; import net.orangemile.informatica.powercenter.domain.constant.PortType; public class Transformation implements Box, Cloneable { private String name; private String description; private String type; private String objectVersion; private Boolean reusable; private String isVsamNormalizer; private String refSourceName; private String refDbdName; private String templateId; private String templateName; private String parent; private ParentType parentType; private String versionNumber; private String crcValue; private List<Group> groupList; private List<SourceField> sourceFieldList; private List<TransformField> transformFieldList; private List<TableAttribute> tableAttributeList; private List<InitProp> initPropList; private List<MetaDataExtension> metaDataExtensionList; private List<TransformFieldAttrDef> transformFieldAttrDefList; private List<FieldDependency> fieldDependencyList; private FlatFile flatFileList; public Transformation() {} public Transformation( String name, String description, InstanceType type ) { this.name = name; this.description = description; this.type = type.getInstanceType(); } public List<TransformField> getInputPorts() { ArrayList<TransformField> fields = new ArrayList<TransformField>(); for ( TransformField field : transformFieldList ) { if ( PortType.isInputPort(field.getPortType()) ) { fields.add( field ); } } return fields; } public List<TransformField> getOutputPorts() { ArrayList<TransformField> fields = new ArrayList<TransformField>(); for ( TransformField field : transformFieldList ) { if ( PortType.isOutputPort(field.getPortType()) ) { fields.add( field ); } } return fields; } public String getCrcValue() { return crcValue; } public void setCrcValue(String crcValue) { this.crcValue = crcValue; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<FieldDependency> getFieldDependencyList() { return fieldDependencyList; } public void setFieldDependencyList(ArrayList<FieldDependency> fieldDependencyList) { this.fieldDependencyList = fieldDependencyList; } public FlatFile getFlatFileList() { return flatFileList; } public void setFlatFileList(FlatFile flatFileList) { this.flatFileList = flatFileList; } public List<Group> getGroupList() { return groupList; } public void setGroupList(ArrayList<Group> groupList) { this.groupList = groupList; } public List<InitProp> getInitPropList() { return initPropList; } public void setInitPropList(ArrayList<InitProp> initPropList) { this.initPropList = initPropList; } public String getIsVsamNormalizer() { return isVsamNormalizer; } public void setIsVsamNormalizer(String isVsamNormalizer) { this.isVsamNormalizer = isVsamNormalizer; } public List<MetaDataExtension> getMetaDataExtensionList() { return metaDataExtensionList; } public void setMetaDataExtensionList(ArrayList<MetaDataExtension> metaDataExtensionList) { this.metaDataExtensionList = metaDataExtensionList; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getObjectVersion() { return objectVersion; } public void setObjectVersion(String objectVersion) { this.objectVersion = objectVersion; } public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public ParentType getParentType() { return parentType; } public void setParentType(ParentType parentType) { this.parentType = parentType; } public String getRefDbdName() { return refDbdName; } public void setRefDbdName(String refDbdName) { this.refDbdName = refDbdName; } public String getRefSourceName() { return refSourceName; } public void setRefSourceName(String refSourceName) { this.refSourceName = refSourceName; } public Boolean isReusable() { return reusable; } public void setReusable(Boolean reusable) { this.reusable = reusable; } public List<SourceField> getSourceFieldList() { return sourceFieldList; } public void setSourceFieldList(List<SourceField> sourceFieldList) { this.sourceFieldList = sourceFieldList; } public List<TableAttribute> getTableAttributeList() { return tableAttributeList; } public void setTableAttributeList(List<TableAttribute> tableAttributeList) { this.tableAttributeList = tableAttributeList; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } public String getTemplateName() { return templateName; } public void setTemplateName(String templateName) { this.templateName = templateName; } public List<TransformFieldAttrDef> getTransformFieldAttrDefList() { return transformFieldAttrDefList; } public void setTransformFieldAttrDefList(ArrayList<TransformFieldAttrDef> transformFieldAttrDefList) { this.transformFieldAttrDefList = transformFieldAttrDefList; } public List<TransformField> getTransformFieldList() { return transformFieldList; } public void setTransformFieldList(List<TransformField> transformFieldList) { this.transformFieldList = transformFieldList; } public void addTransformField( TransformField transformField ) { if ( transformFieldList == null ) { transformFieldList = new ArrayList<TransformField>(); } transformFieldList.add( transformField ); } public void addTransformFields( List<TransformField> transformFields ){ if ( transformFieldList == null ) { transformFieldList = new ArrayList<TransformField>(); } for( TransformField field : transformFields ) { transformFieldList.add(field); } } /** * Adds the given transform field after the given field * @param transformField * @param afterFieldName */ public void addTransformField( TransformField transformField, String afterFieldName ) { if ( transformFieldList == null ) { throw new RuntimeException("TransformFieldList is null"); } for ( int i=0;i<transformFieldList.size();i++) { if ( transformFieldList.get(i).getName().equalsIgnoreCase(afterFieldName) ) { transformFieldList.add(i + 1, transformField); return; } } throw new RuntimeException("Field not found - " + afterFieldName ); } public TransformField getTransformField( String name ) { for ( TransformField field : transformFieldList ) { if ( field.getName().equalsIgnoreCase(name) ) { return field; } } return null; } public String getInstanceType() { return type; } public void setType(String type) { this.type = type; } public String getVersionNumber() { return versionNumber; } public void setVersionNumber(String versionNumber) { this.versionNumber = versionNumber; } public enum ParentType { MAPPING, MAPPLET } @Override public Object clone() { try { return super.clone(); } catch ( CloneNotSupportedException e ) { throw new RuntimeException(e); } } /**************************************** * Utility Methods ****************************************/ /** * Returns the associated table attribute * @param key * @return */ public TableAttribute getTableAttribute( String key ) { for ( TableAttribute ta : tableAttributeList ) { if ( ta.getName().equalsIgnoreCase(key) ) { return ta; } } return null; } }
autodidacticon/informatica-powercenter-automation
src/app/java/net/orangemile/informatica/powercenter/domain/Transformation.java
Java
apache-2.0
7,970
''' Created on 04/11/2015 @author: S41nz ''' class TBTAFMetadataType(object): ''' Simple enumeration class that describes the types of metadata that can be discovered within a source code asset ''' #Verdict enumeration types #The verdict for a passing test TEST_CODE="Test Code" #The verdict for a failed test PRODUCT_CODE="Product Code"
S41nz/TBTAF
tbtaf/common/enums/metadata_type.py
Python
apache-2.0
379
package showcaseview; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import ganggongui.dalkomsoft02.com.myapplication.R; /** * Created by ganggongui on 15. 1. 21.. */ public class Fragment_thred extends Fragment { private View view; // ์ฒซ๋ฒˆ์งธ ํ”„๋ž˜๊ทธ ๋จผํŠธ๋กœ ๋Œ์•„๊ฐ€๋Š” // ๋ฒ„ํŠผ ์ž…๋‹ˆ๋‹ค. private ImageButton backbtn; // ์—‘ํ‹ฐ๋น„์™€์˜ ํ†ต์‹ ์„ ์œ„ํ•œ // ์ธํ„ฐํŽ˜์ด์Šค ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธ ํ•ฉ๋‹ˆ๋‹ค. private onBackButtonListener backButtonListener; public interface onBackButtonListener { public void goBack(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // ํ”„๋ ˆ๊ทธ๋จผํŠธ๋Š” ์•กํ‹ฐ๋น„ํ‹ฐ๋ฅผ ์ƒ์†ํ•˜์ง€ ์•Š์•˜์œผ๋ฏ€๋กœ // ์ฝ˜ํ…์ŠคํŠธ ์ •๋ณด๋ฅผ ์–ป๊ธฐ์œ„ํ•ด ์—‘ํ‹ฐ๋น„ํ‹ฐ๋ฅผ ํ˜•๋ณ€ํ™˜ํ•˜์—ฌ // ๊ฐ’์œผ๋กœ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค. backButtonListener = (onBackButtonListener) activity; } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { this.view = inflater.inflate(R.layout.fragment_thred, container, false); return this.view; } @Override public void onStart() { super.onStart(); backbtn = (ImageButton) view.findViewById(R.id.btn1); backbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ์ธํ„ฐํŽ˜์ด์Šค์˜ ๋ฉ”์†Œ๋“œ๋ฅผ // ์ด์šฉํ•˜์—ฌ ์—‘ํ‹ฐ๋น„ํ‹ฐ์™€ ํ†ต์‹ ํ•ฉ๋‹ˆ๋‹ค. backButtonListener.goBack(); } }); } }
kiss5331/Android
FakeStudyApp/FakeStudy_s/app/src/main/java/showcaseview/Fragment_thred.java
Java
apache-2.0
1,888
package com.decker.jdclassifier; import java.util.ArrayDeque; import java.util.Queue; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringTokenizer extends AbstractTokenizer { Queue<Token> tokenQueue = new ArrayDeque<Token>(); Token buffer = null; int line = 0; public StringTokenizer(String[] strings) { Pattern pattern = Pattern.compile("\\b[A-Za-z0-9_'-]{2,32}\\b|^[A-Za-z0-9_'-]{2,32}\\b|\\b[A-Za-z0-9_'-]{2,32}$"); for(String string : strings) { Matcher matcher = pattern.matcher(string); while(matcher.find()) { String match = matcher.group(); if(!stopwords.contains(match)) this.tokenQueue.add(new Token(string.toLowerCase(), line, matcher.start())); } line++; } } @Override public boolean hasNext() { if(buffer != null) return true; buffer = this.tokenQueue.poll(); return buffer != null; } @Override public Token next() { if(buffer == null) hasNext(); Token token = this.buffer; this.buffer = null; return token; } }
zig158/jdclassifier
jdclassifier/src/com/decker/jdclassifier/StringTokenizer.java
Java
apache-2.0
1,043
package com.mnknowledge.dp.behavioral.observer.wheather; public class CurrentView implements Observer, DisplayElement { private float temperature; private float humidity; @SuppressWarnings("unused") private Subject weatherAPI; public CurrentView(Subject weatherData) { this.weatherAPI = weatherData; weatherData.registerObserver(this); } public void update(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; display(); } public void display() { System.out.println("Current conditions: " + temperature + "C degrees and " + humidity + "% humidity"); } }
stapetro/mnk_designpatterns
dpsamples/src/main/java/com/mnknowledge/dp/behavioral/observer/wheather/CurrentView.java
Java
apache-2.0
705
package net.falappa.swing.table; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.BorderFactory; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.DefaultTableCellRenderer; /* * Highlight only the area occupied by text, not the entire background */ class SelectAllRenderer extends DefaultTableCellRenderer { private Color selectionBackground; private Border editBorder = BorderFactory.createLineBorder(Color.BLACK); private boolean isPaintSelection; public SelectAllRenderer() { this(UIManager.getColor("TextField.selectionBackground")); } public SelectAllRenderer(Color selectionBackground) { this.selectionBackground = selectionBackground; } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); // This variable is used by the paintComponent() method to control when // the background painting (to mimic the text selection) is done. if (hasFocus && table.isCellEditable(row, column) && !getText().equals("")) { isPaintSelection = true; } else { isPaintSelection = false; } return this; } /* * Override to control the background painting of the renderer */ protected void paintComponent(Graphics g) { // Paint the background manually so we can simulate highlighting the text, // therefore we need to make the renderer non-opaque if (isPaintSelection) { setBorder(editBorder); g.setColor(UIManager.getColor("Table.focusCellBackground")); g.fillRect(0, 0, getSize().width, getSize().height); g.setColor(selectionBackground); g.fillRect(0, 0, getPreferredSize().width, getSize().height); setOpaque(false); } super.paintComponent(g); setOpaque(true); } }
AlexFalappa/hcc
af-toolkit/src/main/java/net/falappa/swing/table/SelectAllRenderer.java
Java
apache-2.0
2,222
input = """ f(1). :- f(X). """ output = """ f(1). :- f(X). """
veltri/DLV2
tests/parser/grounding_only.2.test.py
Python
apache-2.0
71
package don.sphere; import don.sphere.exif.IFDEntry; import okio.Buffer; import okio.ByteString; import java.io.EOFException; import java.io.IOException; import java.text.ParseException; /** * Created by Don on 30.07.2015. */ public class ExifUtil extends SectionParser<SectionExif> { public static final ByteString EXIF_HEADER = ByteString.encodeUtf8("Exif\0\0"); public static final int EXIF_HEADER_SIZE = 6; public static final ByteString ALIGN_INTEL = ByteString.decodeHex("49492A00"); public static final ByteString ALIGN_MOTOROLA = ByteString.decodeHex("4d4d002A"); @Override public String toString() { return "ExifUtil{}"; } @Override public boolean canParse(int marker, int length, Buffer data) { if (marker != JpegParser.JPG_APP1) return false; Log.d("EXIF", "MAYBE PARSE - " + data.indexOfElement(EXIF_HEADER)); return data.indexOfElement(EXIF_HEADER) == 0; } @Override public SectionExif parse(int marker, int length, Buffer data) throws ParseException, IOException { data.skip(EXIF_HEADER_SIZE); SectionExif sectionExif = new SectionExif(); final ByteString alignemnt = data.readByteString(4); if (alignemnt.rangeEquals(0, ALIGN_INTEL, 0, 4)) sectionExif.setByteOrder(SectionExif.ByteOrder.INTEL); else if (alignemnt.rangeEquals(0, ALIGN_MOTOROLA, 0, 4)) sectionExif.setByteOrder(SectionExif.ByteOrder.MOTOROLA); else throw new ParseException("Couldnt parse exif section. Unknown ALignment", 2); if (sectionExif.getByteOrder() == SectionExif.ByteOrder.INTEL) parseIntelByteOrder(sectionExif, data); else parseIntelByteOrder(sectionExif, data); return sectionExif; } private void parseMotorolaByteOrder(SectionExif exif, Buffer source) { } private void parseIntelByteOrder(SectionExif exif, Buffer source) throws EOFException { //Read first IFD OFFSET AND SKIP final int offset = source.readIntLe() - 8; source.skip(offset); while (true) { final int ifdEntries = source.readShortLe(); Log.d("IFD BLOCK", "START==== " + ifdEntries + " Entries"); int tag, dataFormat, dataComponents, dataBlock; for (int i = 0; i < ifdEntries; i++) { //PARSE IFD ENTRY tag = source.readShortLe(); dataFormat = source.readShortLe(); dataComponents = source.readIntLe(); Buffer offsetBuffer = new Buffer(); if (IFDEntry.tagBytes(dataFormat) * dataComponents > 4) { source.copyTo(offsetBuffer, (exif.getByteOrder() == SectionExif.ByteOrder.INTEL) ? source.readIntLe() : source.readInt(), dataComponents); } else { source.copyTo(offsetBuffer, 0, 4); } exif.addIFDEntry(IFDEntry.create(exif.getByteOrder(), tag, dataFormat, dataComponents, offsetBuffer)); offsetBuffer.close(); } int ifdBlockOffset = source.readIntLe(); if (ifdBlockOffset == 0) { //No further ifd block Log.d("IFD BLOCK", "LAST===="); break; } else { Log.d("IFD BLOCK", "NEXT BLOCK OFFSET: " + ifdBlockOffset); source.skip(ifdBlockOffset); } Log.d("IFD BLOCK", "END===="); } } }
donmahallem/SphereEdit
src/main/java/don/sphere/ExifUtil.java
Java
apache-2.0
3,530
/* eslint-env browser */ (function() { 'use strict'; // Check to make sure service workers are supported in the current browser, // and that the current page is accessed from a secure origin. Using a // service worker from an insecure origin will trigger JS console errors. See // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features var isLocalhost = Boolean(window.location.hostname === 'localhost' || // [::1] is the IPv6 localhost address. window.location.hostname === '[::1]' || // 127.0.0.1/8 is considered localhost for IPv4. window.location.hostname.match( /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); if ('serviceWorker' in navigator && (window.location.protocol === 'https:' || isLocalhost)) { navigator.serviceWorker.register('service-worker.js') .then(function(registration) { // Check to see if there's an updated version of service-worker.js with // new files to cache: // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-registration-update-method if (typeof registration.update === 'function') { registration.update(); } // updatefound is fired if service-worker.js changes. registration.onupdatefound = function() { // updatefound is also fired the very first time the SW is installed, // and there's no need to prompt for a reload at that point. // So check here to see if the page is already controlled, // i.e. whether there's an existing service worker. if (navigator.serviceWorker.controller) { // The updatefound event implies that registration.installing is set: // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event var installingWorker = registration.installing; installingWorker.onstatechange = function() { switch (installingWorker.state) { case 'installed': // At this point, the old content will have been purged and the // fresh content will have been added to the cache. // It's the perfect time to display a 'New content is // available; please refresh.' message in the page's interface. break; case 'redundant': throw new Error('The installing ' + 'service worker became redundant.'); default: // Ignore } }; } }; }).catch(function(e) { console.error('Error during service worker registration:', e); }); } // Your custom JavaScript goes here // var rss_tuoitre = 'http://tuoitre.vn/rss/tt-tin-moi-nhat.rss'; // var rss_vnexpress = 'http://vnexpress.net/rss/tin-moi-nhat.rss'; var rssReader = 'yql'; var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); function urlBuilder(type, url) { if (type === "rss") { if (rssReader === 'google') { return 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=20&q=' + url; } else if (rssReader === 'yql') { return 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22' + url + '%22&format=json'; } } else { return url; } } var displayDiv = document.getElementById('mainContent'); // Part 1 - Create a function that returns a promise function getJsonAsync(url) { // Promises require two functions: one for success, one for failure return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => { if (xhr.readyState == 4 && xhr.status === 200) { // We can resolve the promise resolve(xhr.response); } else { // It's a failure, so let's reject the promise reject('Unable to load RSS'); } } xhr.onerror = () => { // It's a failure, so let's reject the promise reject('Unable to load RSS'); }; xhr.send(); }); } function getNewsDetail(type, link, callback) { if (type === "json") { callback(news[link]); return; } // get news detail by using rest api which are created by import.io showLoading(); var connector = 'e920a944-d799-4ed7-a017-322eb25ace70'; if (link.indexOf('tuoitre.vn') > -1) { connector = 'bdf72c89-c94b-48f4-967b-b5bc3f8288f7'; } else if (link.indexOf('vnexpress.net') > -1 || link.indexOf('gamethu.net') > -1) { connector = 'e920a944-d799-4ed7-a017-322eb25ace70'; } $.ajax({ url: 'https://api.import.io/store/connector/' + connector + '/_query', data: { input: 'webpage/url:' + link, _apikey: '59531d5e38004cbd944872b657c479fb6eb8a951555700c13023482aad713db52a65da670cd35dbe42a8fc32301bb78f419cba619c4c1c2e66ecde01de25b90dc014dece32953d8ad7c9de7ad788a261' }, success: function(response) { callback(response.results[0]); }, error: function(error) { showDialog({ title: 'Error', text: error }) }, complete: function() { hideLoading(); } }); } var news = []; function loadNews(type, url) { showLoading(); url = urlBuilder(type, url); var promise = $.ajax({ url: url, // crossDomain: true, // dataType: "jsonp" }); promise.done(function(response) { displayDiv.innerHTML = ''; if (type === "rss") { if (rssReader === 'google') { if (response.responseData.feed) { news = response.responseData.feed.entries; } else { news = response.query.results.item; } } else if (rssReader === 'yql') { news = response.query.results.item; } } else if (type === "json") { news = response.results.results || response.results.items || response.results.collection1; } news.forEach(item => { displayDiv.innerHTML += getTemplateNews(item); }); $('button.simple-ajax-popup').on('click', function(e) { e.preventDefault(); var link = $(this).data('link'); console.log(link); if (!link) { showDialog({ title: 'no link', text: link }) return; } if (type === "json") { link = $(this).parents('.news-item').index(); }; getNewsDetail(type, link, function(detail) { var content_html = detail.content_html || detail.content; if (!isChrome) { content_html = content_html.replace(new RegExp('.webp', 'g'), ''); } var $content = $('<div>' + content_html + '</div'); $content.find('.nocontent').remove(); // var $content = $(content_html).siblings(".nocontent").remove(); showDialog({ title: detail.title, text: $content.html() }) }) }); }).complete(function() { hideLoading(); }); } function getTemplateNews(news) { if (!news.content) { news.content = news.description || ""; } news.content = news.content.replace(new RegExp('/s146/', 'g'), '/s440/'); news.summary = news.summary || news.content; if (!news.image && news.summary.indexOf('<img ') === -1 && news.content.indexOf('<img ') > -1) { news.image = $(news.content).find('img:first-child').attr('src'); } news.image = (news.image) ? `<img src="${news.image.replace(new RegExp('/s146/', 'g'), '/s440/')}" />` : ''; if (!isChrome) { news.image = news.image.replace(new RegExp('.webp', 'g'), ''); } news.time = news.time || news.publishedDate || news.pubDate || ''; news.link = news.link || news.url; news.sourceText = news.source ? ' - ' + news.source.text : ''; return `<div class='news-item mdl-color-text--grey-700 mdl-shadow--2dp'> <div class='news-item__title'> <div class='news-item__title-text mdl-typography--title'> ${news.title} </div> <div class='news-item__title-time'>${news.time} <b>${news.sourceText}</b></div> </div> <div class='news-item__content'> ${news.image} ${news.summary} </div> <div class='news-item__actions'> <button data-link='${news.link}' class='mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect simple-ajax-popup'> View more </button> <a href='${news.link}' target='_blank' class='mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect simple-ajax-popup'> Open web </a> </div> </div>` } $('.change-news').click(function(e) { loadNews($(this).data('type'), $(this).data('url')); $(".mdl-layout__obfuscator").click(); }); $('.change-news:first-child').click(); // PLUGIN mdl-jquery-modal-dialog.js function showLoading() { // remove existing loaders $('.loading-container').remove(); $('<div id="orrsLoader" class="loading-container"><div><div class="mdl-spinner mdl-js-spinner is-active"></div></div></div>').appendTo("body"); componentHandler.upgradeElements($('.mdl-spinner').get()); setTimeout(function() { $('#orrsLoader').css({ opacity: 1 }); }, 1); } function hideLoading() { $('#orrsLoader').css({ opacity: 0 }); setTimeout(function() { $('#orrsLoader').remove(); }, 400); } function showDialog(options) { options = $.extend({ id: 'orrsDiag', title: null, text: null, negative: false, positive: false, cancelable: true, contentStyle: null, onLoaded: false }, options); // remove existing dialogs $('.dialog-container').remove(); $(document).unbind("keyup.dialog"); $('<div id="' + options.id + '" class="dialog-container"><div class="mdl-card mdl-shadow--16dp"></div></div>').appendTo("body"); var dialog = $('#orrsDiag'); var content = dialog.find('.mdl-card'); if (options.contentStyle != null) content.css(options.contentStyle); if (options.title != null) { $('<h5>' + options.title + '</h5>').appendTo(content); } if (options.text != null) { $('<p>' + options.text + '</p>').appendTo(content); } if (options.negative || options.positive) { var buttonBar = $('<div class="mdl-card__actions dialog-button-bar"></div>'); if (options.negative) { options.negative = $.extend({ id: 'negative', title: 'Cancel', onClick: function() { return false; } }, options.negative); var negButton = $('<button class="mdl-button mdl-js-button mdl-js-ripple-effect" id="' + options.negative.id + '">' + options.negative.title + '</button>'); negButton.click(function(e) { e.preventDefault(); if (!options.negative.onClick(e)) hideDialog(dialog) }); negButton.appendTo(buttonBar); } if (options.positive) { options.positive = $.extend({ id: 'positive', title: 'OK', onClick: function() { return false; } }, options.positive); var posButton = $('<button class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" id="' + options.positive.id + '">' + options.positive.title + '</button>'); posButton.click(function(e) { e.preventDefault(); if (!options.positive.onClick(e)) hideDialog(dialog) }); posButton.appendTo(buttonBar); } buttonBar.appendTo(content); } componentHandler.upgradeDom(); if (options.cancelable) { dialog.click(function() { hideDialog(dialog); }); $(document).bind("keyup.dialog", function(e) { if (e.which == 27) hideDialog(dialog); }); content.click(function(e) { e.stopPropagation(); }); } setTimeout(function() { dialog.css({ opacity: 1 }); if (options.onLoaded) options.onLoaded(); }, 1); } function hideDialog(dialog) { $(document).unbind("keyup.dialog"); dialog.css({ opacity: 0 }); setTimeout(function() { dialog.remove(); }, 400); } })();
leetrunghoo/surfnews
app/scripts/main.js
JavaScript
apache-2.0
15,008
<?php defined('XAPP') || require_once(dirname(__FILE__) . '/../../../Core/core.php'); xapp_import('xapp.Log.Exception'); /** * Log writer exception class * * @package Log * @subpackage Log_Writer * @class Xapp_Log_Writer_Exception * @author Frank Mueller <support@xapp-studio.com> */ class Xapp_Log_Writer_Exception extends Xapp_Log_Exception { /** * error exception class constructor directs instance * to error xapp error handling * * @param string $message excepts error message * @param int $code expects error code * @param int $severity expects severity flag */ public function __construct($message, $code = 0, $severity = XAPP_ERROR_ERROR) { parent::__construct($message, $code, $severity); xapp_error($this); } }
back1992/ticool
components/com_xas/xapp/lib/rpc/lib/vendor/xapp/Log/Writer/Exception/Exception.php
PHP
apache-2.0
797
package com.turnos.cliente.conexion; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status.Family; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.turnos.datos.WebServUtils; import com.turnos.datos.vo.ComentarioBean; import com.turnos.datos.vo.ETLTBean; import com.turnos.datos.vo.FestivoBean; import com.turnos.datos.vo.MensajeBean; import com.turnos.datos.vo.MunicipioBean; import com.turnos.datos.vo.PaisBean; import com.turnos.datos.vo.PropuestaCambioBean; import com.turnos.datos.vo.ProvinciaBean; import com.turnos.datos.vo.ResidenciaBean; import com.turnos.datos.vo.RespuestaBean; import com.turnos.datos.vo.ServicioBean; import com.turnos.datos.vo.SesionBean; import com.turnos.datos.vo.TrabajadorBean; import com.turnos.datos.vo.TurnoBean; import com.turnos.datos.vo.TurnoTrabajadorDiaBean; import com.turnos.datos.vo.UsuarioBean; public class ClienteREST { public static enum MetodoHTTP{GET, POST, PUT, DELETE, OPTIONS, HEAD}; public static SesionBean login(String tokenLogin, Aplicacion aplicacion) { Hashtable<String, String> headerParams = new Hashtable<String, String>(1); headerParams.put("tokenLogin", tokenLogin); RespuestaBean<SesionBean> respuesta = llamada(aplicacion, new SesionBean(), WebServUtils.PREF_AUTH_PATH + WebServUtils.PREF_LOGIN_PATH, MetodoHTTP.GET, null, null, headerParams, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } /* public static ResidenciaBean residenciaGetResidencia(String codRes, boolean incGeo, Sesion sesion) { Hashtable<String, String> queryParams = new Hashtable<String, String>(1); queryParams.put(WebServUtils.Q_PARAM_INC_GEO, Boolean.toString(incGeo)); RespuestaBean<ResidenciaBean> respuesta = llamada(sesion, new ResidenciaBean(), WebServUtils.PREF_RES_PATH + '/' + codRes, MetodoHTTP.GET, queryParams, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static List<ResidenciaBean> residenciaListaResidencias(String pais, String provincia, String municipio, boolean incGeo, int limite, int offset, Sesion sesion) { Hashtable<String, String> queryParams = new Hashtable<String, String>(6); if (pais != null) { queryParams.put(WebServUtils.Q_PARAM_COD_PAIS, pais); } if (provincia != null) { queryParams.put(WebServUtils.Q_PARAM_COD_PROV, provincia); } if (municipio != null) { queryParams.put(WebServUtils.Q_PARAM_COD_MUNI, municipio); } if (limite > 0) { queryParams.put(WebServUtils.Q_PARAM_LIMITE, Integer.toString(limite)); } if (offset > 0) { queryParams.put(WebServUtils.Q_PARAM_OFFSET, Integer.toString(offset)); } queryParams.put(WebServUtils.Q_PARAM_INC_GEO, Boolean.toString(incGeo)); RespuestaBean<ResidenciaBean> respuesta = llamada(sesion, new ResidenciaBean(), WebServUtils.PREF_RES_PATH, MetodoHTTP.GET, queryParams, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getListaResultados(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static TrabajadorBean trabajadorGetTrabajador(String codRes, String codTrab, Sesion sesion) { RespuestaBean<TrabajadorBean> respuesta = llamada(sesion, new TrabajadorBean(), WebServUtils.PREF_RES_PATH + '/' + codRes + WebServUtils.PREF_TRAB_PATH + '/' + codTrab, MetodoHTTP.GET, null, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } //*/ /* ************************************ */ public static MensajeBean mensajeGetMensaje(long arg0, long arg1, int arg2, boolean arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static int mensajeGetNumMensajes(long arg0, boolean arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return -1; } public static int mensajeGetNumRespuestas(long arg0, long arg1, boolean arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return -1; } public static List<MensajeBean> mensajeListaMensajes(long arg0, String arg1, boolean arg2, boolean arg3, int arg4, int arg5, int arg6, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<MensajeBean> mensajeListaRespuestas(long arg0, long arg1, boolean arg2, boolean arg3, int arg4, int arg5, int arg6, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static MensajeBean mensajeNuevoMensaje(MensajeBean arg0, long arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean mensajeSetMensajeLeido(long arg0, long arg1, boolean arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static boolean mensajeSetMensajeNoLeido(long arg0, long arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static boolean mensajeSetMensajeSiLeido(long arg0, long arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static UsuarioBean usuarioCambiaNivelUsuario(int arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static UsuarioBean usuarioGetUsuario(int arg0, boolean arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static UsuarioBean usuarioModUsuario(UsuarioBean arg0, int arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static UsuarioBean usuarioNuevoUsuario(UsuarioBean arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean turnoBorraTurno(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static TurnoBean turnoGetTurno(String arg0, String arg1, boolean arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<TurnoBean> turnoListaTurnos(String arg0, String arg1, boolean arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TurnoBean turnoModTurno(TurnoBean arg0, String arg1, String arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TurnoBean turnoNuevoTurno(TurnoBean arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<FestivoBean> municipioGetFestivosMunicipio(String codPais, String codProvincia, String codMunicipio, Date time_ini, Date time_fin, boolean completo, boolean inc_geo, int limite, int offset, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static MunicipioBean municipioGetMunicipio(String arg0, String arg1, String arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ResidenciaBean> municipioGetResidenciasMunicipio(String arg0, String arg1, String arg2, boolean arg3, int arg4, int arg5, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<MunicipioBean> municipioListaMunicipios(String arg0, String arg1, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean residenciaBorraResidencia(String arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static List<FestivoBean> residenciaGetDiasFestivos(String arg0, Date time_ini, Date time_fin, int arg3, int arg4, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<TurnoTrabajadorDiaBean> residenciaGetHorarioCompletoDia(String arg0, Date time, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ResidenciaBean residenciaGetResidencia(String codRes, boolean incGeo, Sesion sesion) { Hashtable<String, String> queryParams = new Hashtable<String, String>(1); queryParams.put(WebServUtils.Q_PARAM_INC_GEO, Boolean.toString(incGeo)); RespuestaBean<ResidenciaBean> respuesta = llamada(sesion, new ResidenciaBean(), WebServUtils.PREF_RES_PATH + '/' + codRes, MetodoHTTP.GET, queryParams, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static List<ResidenciaBean> residenciaListaResidencias(String pais, String provincia, String municipio, boolean incGeo, int limite, int offset, Sesion sesion) { Hashtable<String, String> queryParams = new Hashtable<String, String>(6); if (pais != null) { queryParams.put(WebServUtils.Q_PARAM_COD_PAIS, pais); } if (provincia != null) { queryParams.put(WebServUtils.Q_PARAM_COD_PROV, provincia); } if (municipio != null) { queryParams.put(WebServUtils.Q_PARAM_COD_MUNI, municipio); } if (limite > 0) { queryParams.put(WebServUtils.Q_PARAM_LIMITE, Integer.toString(limite)); } if (offset > 0) { queryParams.put(WebServUtils.Q_PARAM_OFFSET, Integer.toString(offset)); } queryParams.put(WebServUtils.Q_PARAM_INC_GEO, Boolean.toString(incGeo)); RespuestaBean<ResidenciaBean> respuesta = llamada(sesion, new ResidenciaBean(), WebServUtils.PREF_RES_PATH, MetodoHTTP.GET, queryParams, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getListaResultados(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static ResidenciaBean residenciaModResidencia(ResidenciaBean arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ResidenciaBean residenciaNuevaResidencia(ResidenciaBean arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean servicioBorraServicio(String arg0, String arg1, long arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static ServicioBean servicioGetServicio(String arg0, String arg1, long arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ServicioBean> servicioListaServicios(String arg0, String arg1, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ServicioBean servicioModServicio(ServicioBean arg0, String arg1, String arg2, long arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ServicioBean servicioNuevoServicio(ServicioBean arg0, String arg1, String arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean festivoBorraDiaFestivo(long arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static FestivoBean festivoGetDiaFestivo(long arg0, boolean arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<FestivoBean> festivoListaDiasFestivos(String codPais, String codProvincia, String codMunicipio, String tipoStr, Date time_ini, Date time_fin, boolean completo, boolean incGeo, int limite, int offset, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static FestivoBean festivoModDiaFestivo(FestivoBean arg0, long arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static FestivoBean festivoNuevoDiaFestivo(FestivoBean arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean comentarioBorraComentario(long arg1, long arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static ComentarioBean comentarioNuevoComentario(ComentarioBean arg0, long arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<FestivoBean> paisGetFestivosPais(String codPais, Date time_ini, Date time_fin, boolean inc_geo, int limite, int offset, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static PaisBean paisGetPais(String arg0, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ResidenciaBean> paisGetResidenciasPais(String arg0, boolean arg1, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<PaisBean> paisListaPaises(int arg0, int arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<FestivoBean> provinciaGetFestivosProvincia(String codPais, String codProvincia, Date time_ini, Date time_fin, boolean completo, boolean inc_geo, int limite, int offset, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static ProvinciaBean provinciaGetProvincia(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ResidenciaBean> provinciaGetResidenciasProvincia(String arg0, String arg1, boolean arg2, int arg3, int arg4, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<ProvinciaBean> provinciaListaProvincias(String arg0, int arg1, int arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static boolean trabajadorBorraTrabajador(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return false; } public static TurnoTrabajadorDiaBean trabajadorGetHorarioTrabajadorDia(String arg0, String arg1, int arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static List<TurnoTrabajadorDiaBean> trabajadorGetHorarioTrabajadorRango(String arg0, String arg1, int arg2, int arg3, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static int trabajadorGetNumPropuestasCambio(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return -1; } public static List<PropuestaCambioBean> trabajadorGetPropuestasCambio(String arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TrabajadorBean trabajadorGetTrabajador(String codRes, String codTrab, Sesion sesion) { RespuestaBean<TrabajadorBean> respuesta = llamada(sesion, new TrabajadorBean(), WebServUtils.PREF_RES_PATH + '/' + codRes + WebServUtils.PREF_TRAB_PATH + '/' + codTrab, MetodoHTTP.GET, null, null, null, null); if (respuesta != null && respuesta.getResultado() != null) { return respuesta.getResultado(); } else { //TODO ( probablemente lanzar excepcion (??) ) return null; } } public static List<TrabajadorBean> trabajadorListaTrabajadores(String arg0, int arg1, int arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TrabajadorBean trabajadorModTrabajador(TrabajadorBean arg0, String arg1, String arg2, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static TrabajadorBean trabajadorNuevoTrabajador(TrabajadorBean arg0, String arg1, Sesion sesion) { //----------------- //---- TODO ------- //----------------- return null; } public static PropuestaCambioBean propuestacambioNuevoPropuestaCambio( PropuestaCambioBean rawBean, Sesion sesion) { // TODO Auto-generated method stub return null; } public static PropuestaCambioBean propuestacambioModPropuestaCambio( PropuestaCambioBean rawBean, long id_cambio, Sesion sesion) { // TODO Auto-generated method stub return null; } public static List<PropuestaCambioBean> propuestacambioListaPropuestaCambios(String estado, Sesion sesion) { // TODO Auto-generated method stub return null; } public static PropuestaCambioBean propuestacambioGetPropuestaCambio(long id_cambio, boolean b, Sesion sesion) { // TODO Auto-generated method stub return null; } public static boolean propuestacambioBorraPropuestaCambio(long id_cambio, Sesion sesion) { // TODO Auto-generated method stub return false; } /* ************************************ */ private static <T extends ETLTBean> RespuestaBean<T> llamada( Aplicacion aplicacion, T tipo, String recurso, MetodoHTTP metodo, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headerParams, String jsonBody) { System.out.println(" ***** LLAMANDO *** (" + recurso + ", " + metodo + ", " + queryParams + ", " + jsonBody + ") *****"); RespuestaBean<T> res = new RespuestaBean<T>(); Client client = null; try { client = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class); WebTarget target = client.target(aplicacion.baseURL).path(recurso); if(queryParams != null && !queryParams.isEmpty()) { for(Entry<String, String> entry: queryParams.entrySet()) { target = target.queryParam(entry.getKey(), entry.getValue()); } } Builder b = target.request(MediaType.APPLICATION_JSON_TYPE); if (headerParams == null) { headerParams = new Hashtable<String, String>(1); } headerParams.put("publicKey", aplicacion.publicKey); b = b.headers(new MultivaluedHashMap<String, Object>(headerParams)); Response rp; switch(metodo) { case GET: rp = b.get(); break; case POST: rp = b.post(Entity.entity(jsonBody, MediaType.APPLICATION_JSON_TYPE)); break; case PUT: rp = b.put(Entity.entity(jsonBody, MediaType.APPLICATION_JSON_TYPE)); break; case DELETE: rp = b.delete(); break; default: return null; } if (rp.getStatusInfo().getFamily() == Family.SUCCESSFUL) { res = rp.readEntity(RespuestaBean.class); } else { //TODO // System.out.println("****** MAL ******" + rp); } } finally { if(client != null) client.close(); } return res; } public static <T extends ETLTBean> RespuestaBean<T> llamada(Sesion sesion, T tipo, String recurso, MetodoHTTP metodo, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headerParams, String jsonBody) { if (headerParams == null) { headerParams = new Hashtable<String, String>(1); } headerParams.put("tokenSesion", sesion.getTokenSesion()); return llamada(sesion.aplicacion, tipo, recurso, metodo, queryParams, postParams, headerParams, jsonBody); } }
catoyos-turnos/ETLT-DESA
ClienteAPI/1.0/ETLTClienteAPI_1.0/src/com/turnos/cliente/conexion/ClienteREST.java
Java
apache-2.0
20,545
package de.atomfrede.jenkins.domain.coverage; import java.io.Serializable; public class ClassCoverage implements Serializable { private static final long serialVersionUID = -8132894251774828498L; private int percentage; private float percentageFloat; public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } public float getPercentageFloat() { return percentageFloat; } public void setPercentageFloat(float percentageFloat) { this.percentageFloat = percentageFloat; } }
atomfrede/animated-octo-adventure
jenkins.service/src/main/java/de/atomfrede/jenkins/domain/coverage/ClassCoverage.java
Java
apache-2.0
568
#!/usr/bin/ruby # # Author:: api.sgomes@gmail.com (Sรฉrgio Gomes) # # Copyright:: Copyright 2011, Google Inc. All Rights Reserved. # # License:: 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 example illustrates how to update an ad, setting its status to 'PAUSED'. # To create ads, run add_ads.rb. # # Tags: AdGroupAdService.mutate require 'rubygems' gem 'google-adwords-api' require 'adwords_api' API_VERSION = :v201003 def update_ad() # AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml # when called without parameters. adwords = AdwordsApi::Api.new ad_group_ad_srv = adwords.service(:AdGroupAdService, API_VERSION) ad_group_id = 'INSERT_AD_GROUP_ID_HERE'.to_i ad_id = 'INSERT_AD_ID_HERE'.to_i # Prepare for updating ad. operation = { :operator => 'SET', :operand => { :ad_group_id => ad_group_id, :status => 'PAUSED', :ad => { :id => ad_id } } } # Update ad. response = ad_group_ad_srv.mutate([operation]) if response and response[:value] ad = response[:value].first puts 'Ad id %d was successfully updated, status set to %s.' % [ad[:ad][:id], ad[:status]] else puts 'No ads were updated.' end end if __FILE__ == $0 # To enable logging of SOAP requests, set the ADWORDSAPI_DEBUG environment # variable to 'true'. This can be done either from your operating system # environment or via code, as done below. ENV['ADWORDSAPI_DEBUG'] = 'false' begin update_ad() # Connection error. Likely transitory. rescue Errno::ECONNRESET, SOAP::HTTPStreamError, SocketError => e puts 'Connection Error: %s' % e puts 'Source: %s' % e.backtrace.first # API Error. rescue AdwordsApi::Errors::ApiException => e puts 'API Exception caught.' puts 'Message: %s' % e.message puts 'Code: %d' % e.code if e.code puts 'Trigger: %s' % e.trigger if e.trigger puts 'Errors:' if e.errors e.errors.each_with_index do |error, index| puts ' %d. Error type is %s. Fields:' % [index + 1, error[:xsi_type]] error.each_pair do |field, value| if field != :xsi_type puts ' %s: %s' % [field, value] end end end end end end
sylow/google-adwords-api
examples/v201003/update_ad.rb
Ruby
apache-2.0
2,835
package com.jarvis.cache.serializer.hession; import com.caucho.hessian.io.AbstractHessianInput; import com.caucho.hessian.io.AbstractMapDeserializer; import com.caucho.hessian.io.IOExceptionWrapper; import java.io.IOException; import java.lang.ref.WeakReference; /** * */ public class WeakReferenceDeserializer extends AbstractMapDeserializer { @Override public Object readObject(AbstractHessianInput in, Object[] fields) throws IOException { try { WeakReference<Object> obj = instantiate(); in.addRef(obj); Object value = in.readObject(); obj = null; return new WeakReference<Object>(value); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(e); } } protected WeakReference<Object> instantiate() throws Exception { Object obj = new Object(); return new WeakReference<Object>(obj); } }
qiujiayu/AutoLoadCache
autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/WeakReferenceDeserializer.java
Java
apache-2.0
985
/* * ../../../..//fonts/HTML-CSS/TeX/png/AMS/Regular/BBBold.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ /************************************************************* * * MathJax/fonts/HTML-CSS/TeX/png/AMS/Regular/BBBold.js * * Defines the image size data needed for the HTML-CSS OutputJax * to display mathematics using fallback images when the fonts * are not available to the client browser. * * --------------------------------------------------------------------- * * Copyright (c) 2009-2013 The MathJax Consortium * * 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 * * 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. * */ MathJax.OutputJax["HTML-CSS"].defineImageData({ MathJax_AMS: { 0x20: [ // SPACE [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0] ], 0x41: [ // LATIN CAPITAL LETTER A [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 10, 0], [12, 12, 0], [14, 14, 0], [17, 16, 0], [20, 19, 0], [23, 23, 0], [28, 27, 0], [33, 33, 0], [39, 39, 0], [46, 46, 0] ], 0x42: [ // LATIN CAPITAL LETTER B [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [21, 22, 0], [25, 27, 0], [29, 32, 0], [35, 38, 0], [41, 45, 0] ], 0x43: [ // LATIN CAPITAL LETTER C [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 10, 0], [12, 12, 0], [14, 14, 0], [16, 16, 0], [19, 21, 2], [23, 24, 1], [27, 28, 1], [32, 34, 1], [38, 40, 1], [45, 48, 2] ], 0x44: [ // LATIN CAPITAL LETTER D [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [16, 16, 0], [20, 19, 0], [23, 22, 0], [27, 27, 0], [32, 32, 0], [39, 38, 0], [46, 45, 0] ], 0x45: [ // LATIN CAPITAL LETTER E [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [22, 22, 0], [26, 27, 0], [30, 32, 0], [36, 38, 0], [43, 45, 0] ], 0x46: [ // LATIN CAPITAL LETTER F [5, 5, 0], [5, 6, 0], [6, 7, 0], [7, 8, 0], [9, 9, 0], [10, 11, 0], [12, 13, 0], [14, 16, 0], [17, 19, 0], [20, 22, 0], [23, 27, 0], [27, 32, 0], [33, 38, 0], [39, 45, 0] ], 0x47: [ // LATIN CAPITAL LETTER G [6, 5, 0], [7, 6, 0], [8, 7, 0], [9, 8, 0], [11, 10, 0], [13, 12, 0], [15, 14, 0], [18, 16, 0], [21, 19, 0], [25, 24, 1], [30, 29, 2], [35, 33, 0], [42, 40, 1], [50, 47, 1] ], 0x48: [ // LATIN CAPITAL LETTER H [6, 5, 0], [7, 6, 0], [8, 7, 0], [9, 8, 0], [11, 9, 0], [13, 11, 0], [15, 13, 0], [18, 16, 0], [22, 19, 0], [26, 22, 0], [30, 27, 0], [36, 32, 0], [43, 38, 0], [51, 45, 0] ], 0x49: [ // LATIN CAPITAL LETTER I [3, 5, 0], [4, 6, 0], [4, 7, 0], [5, 8, 0], [6, 9, 0], [7, 11, 0], [8, 13, 0], [9, 16, 0], [11, 19, 0], [13, 22, 0], [15, 27, 0], [18, 32, 0], [21, 38, 0], [25, 45, 0] ], 0x4a: [ // LATIN CAPITAL LETTER J [4, 6, 1], [4, 7, 1], [5, 8, 1], [6, 9, 1], [7, 11, 2], [8, 13, 2], [10, 15, 2], [12, 18, 2], [14, 21, 2], [16, 26, 4], [19, 30, 3], [23, 35, 3], [27, 42, 4], [32, 50, 5] ], 0x4b: [ // LATIN CAPITAL LETTER K [6, 5, 0], [7, 6, 0], [8, 7, 0], [10, 8, 0], [11, 9, 0], [13, 11, 0], [15, 13, 0], [18, 16, 0], [22, 19, 0], [26, 22, 0], [31, 27, 0], [36, 32, 0], [43, 38, 0], [51, 45, 0] ], 0x4c: [ // LATIN CAPITAL LETTER L [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [22, 22, 0], [26, 27, 0], [30, 32, 0], [36, 38, 0], [43, 45, 0] ], 0x4d: [ // LATIN CAPITAL LETTER M [7, 5, 0], [8, 6, 0], [10, 7, 0], [11, 8, 0], [13, 9, 0], [16, 11, 0], [19, 13, 0], [22, 16, 0], [26, 19, 0], [31, 22, 0], [37, 27, 0], [44, 32, 0], [52, 38, 0], [61, 45, 0] ], 0x4e: [ // LATIN CAPITAL LETTER N [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 9, 0], [10, 10, 0], [12, 12, 0], [14, 14, 0], [17, 17, 0], [20, 21, 1], [24, 24, 1], [28, 29, 1], [33, 34, 1], [39, 40, 1], [47, 48, 2] ], 0x4f: [ // LATIN CAPITAL LETTER O [6, 5, 0], [7, 6, 0], [8, 7, 0], [9, 8, 0], [11, 10, 0], [13, 12, 0], [15, 14, 0], [18, 16, 0], [21, 21, 2], [25, 24, 1], [30, 28, 1], [35, 34, 1], [42, 40, 1], [49, 48, 2] ], 0x50: [ // LATIN CAPITAL LETTER P [5, 5, 0], [5, 6, 0], [6, 7, 0], [8, 8, 0], [9, 9, 0], [10, 11, 0], [12, 13, 0], [14, 16, 0], [17, 19, 0], [20, 22, 0], [24, 27, 0], [28, 32, 0], [34, 38, 0], [40, 45, 0] ], 0x51: [ // LATIN CAPITAL LETTER Q [6, 6, 1], [7, 8, 2], [8, 9, 2], [9, 10, 2], [11, 12, 2], [13, 15, 3], [15, 17, 3], [18, 20, 4], [21, 24, 5], [25, 30, 7], [30, 35, 8], [35, 41, 8], [42, 49, 10], [49, 58, 12] ], 0x52: [ // LATIN CAPITAL LETTER R [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 27, 0], [33, 32, 0], [39, 38, 0], [47, 45, 0] ], 0x53: [ // LATIN CAPITAL LETTER S [4, 5, 0], [5, 6, 0], [6, 7, 0], [7, 8, 0], [8, 10, 0], [9, 12, 0], [11, 14, 0], [13, 16, 0], [15, 19, 0], [18, 23, 0], [21, 27, 0], [25, 33, 0], [30, 40, 1], [35, 47, 1] ], 0x54: [ // LATIN CAPITAL LETTER T [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [21, 22, 0], [25, 27, 0], [30, 32, 0], [36, 38, 0], [42, 45, 0] ], 0x55: [ // LATIN CAPITAL LETTER U [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 28, 1], [33, 33, 1], [40, 39, 1], [47, 46, 1] ], 0x56: [ // LATIN CAPITAL LETTER V [5, 5, 0], [6, 6, 0], [8, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [15, 13, 0], [17, 16, 0], [20, 20, 1], [24, 24, 2], [29, 28, 1], [34, 33, 1], [40, 39, 1], [48, 46, 1] ], 0x57: [ // LATIN CAPITAL LETTER W [7, 5, 0], [9, 6, 0], [10, 7, 0], [12, 8, 0], [14, 9, 0], [17, 11, 0], [20, 13, 0], [24, 16, 0], [28, 20, 1], [33, 24, 2], [39, 28, 1], [47, 33, 1], [55, 39, 1], [66, 47, 2] ], 0x58: [ // LATIN CAPITAL LETTER X [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 27, 0], [33, 32, 0], [39, 38, 0], [47, 45, 0] ], 0x59: [ // LATIN CAPITAL LETTER Y [5, 5, 0], [6, 6, 0], [7, 7, 0], [9, 8, 0], [10, 9, 0], [12, 11, 0], [14, 13, 0], [17, 16, 0], [20, 19, 0], [24, 22, 0], [28, 27, 0], [33, 32, 0], [39, 38, 0], [47, 45, 0] ], 0x5a: [ // LATIN CAPITAL LETTER Z [5, 5, 0], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0], [11, 11, 0], [13, 13, 0], [15, 16, 0], [18, 19, 0], [21, 22, 0], [25, 27, 0], [30, 32, 0], [36, 38, 0], [42, 45, 0] ], 0x6b: [ // LATIN SMALL LETTER K [4, 5, 0], [5, 6, 0], [6, 7, 0], [7, 8, 0], [8, 10, 0], [9, 12, 0], [11, 14, 0], [13, 16, 0], [15, 19, 0], [18, 23, 0], [21, 27, 0], [25, 32, 0], [30, 38, 0], [36, 45, 0] ] } }); MathJax.Ajax.loadComplete( MathJax.OutputJax["HTML-CSS"].imgDir + "/AMS/Regular" + MathJax.OutputJax["HTML-CSS"].imgPacked + "/BBBold.js" );
GerHobbelt/MathJax
fonts/HTML-CSS/TeX/png/AMS/Regular/BBBold.js
JavaScript
apache-2.0
10,460
package com.ourcode.models.input; import com.google.gson.annotations.SerializedName; import com.graphhopper.jsprit.core.problem.job.Break; import java.util.ArrayList; /** * Created by LEOLEOl on 5/19/2017. */ public class OCBreak { @SerializedName("breakCode") private String breakCode; @SerializedName("serviceTime") private double serviceTime; // (in hours) @SerializedName("timeWindows") public ArrayList<OCTimeWindow> timeWindows; // (in hours) private Break j_break; public Break _getJ_break() { return j_break; } public double getServiceTime() {return serviceTime;} public void setServiceTime(double serviceTime) {this.serviceTime = serviceTime;} public OCBreak(OCBreak ocBreak) { this.breakCode = ocBreak.breakCode; this.serviceTime = ocBreak.serviceTime; this.timeWindows = new ArrayList<>(); for (OCTimeWindow timeWindow: ocBreak.timeWindows) this.timeWindows.add(new OCTimeWindow(timeWindow)); } public OCBreak build() { Break.Builder builder = Break.Builder.newInstance(breakCode); builder.setServiceTime(serviceTime); for (OCTimeWindow timeWindow: timeWindows) builder.addTimeWindow(timeWindow.build()._getJ_timeWindow()); j_break = builder.build(); return this; } }
LEOLEOl/jsprit-me
viet-jsprit/src/main/java/com/ourcode/models/input/OCBreak.java
Java
apache-2.0
1,371
/* * 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.google.cloud.dataflow.examples.complete.game; import com.google.cloud.dataflow.examples.complete.game.UserScore.GameActionInfo; import com.google.cloud.dataflow.examples.complete.game.UserScore.ParseEventFn; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.testing.PAssert; import com.google.cloud.dataflow.sdk.testing.RunnableOnService; import com.google.cloud.dataflow.sdk.testing.TestPipeline; import com.google.cloud.dataflow.sdk.transforms.Create; import com.google.cloud.dataflow.sdk.transforms.Filter; import com.google.cloud.dataflow.sdk.transforms.MapElements; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.TypeDescriptor; import org.joda.time.Instant; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.Serializable; import java.util.Arrays; import java.util.List; /** * Tests of HourlyTeamScore. * Because the pipeline was designed for easy readability and explanations, it lacks good * modularity for testing. See our testing documentation for better ideas: * https://cloud.google.com/dataflow/pipelines/testing-your-pipeline. */ @RunWith(JUnit4.class) public class HourlyTeamScoreTest implements Serializable { static final String[] GAME_EVENTS_ARRAY = new String[] { "user0_MagentaKangaroo,MagentaKangaroo,3,1447955630000,2015-11-19 09:53:53.444", "user13_ApricotQuokka,ApricotQuokka,15,1447955630000,2015-11-19 09:53:53.444", "user6_AmberNumbat,AmberNumbat,11,1447955630000,2015-11-19 09:53:53.444", "user7_AlmondWallaby,AlmondWallaby,15,1447955630000,2015-11-19 09:53:53.444", "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,12,1447955630000,2015-11-19 09:53:53.444", "user7_AndroidGreenKookaburra,AndroidGreenKookaburra,11,1447955630000,2015-11-19 09:53:53.444", "user19_BisqueBilby,BisqueBilby,6,1447955630000,2015-11-19 09:53:53.444", "user19_BisqueBilby,BisqueBilby,8,1447955630000,2015-11-19 09:53:53.444", // time gap... "user0_AndroidGreenEchidna,AndroidGreenEchidna,0,1447965690000,2015-11-19 12:41:31.053", "user0_MagentaKangaroo,MagentaKangaroo,4,1447965690000,2015-11-19 12:41:31.053", "user2_AmberCockatoo,AmberCockatoo,13,1447965690000,2015-11-19 12:41:31.053", "user18_BananaEmu,BananaEmu,7,1447965690000,2015-11-19 12:41:31.053", "user3_BananaEmu,BananaEmu,17,1447965690000,2015-11-19 12:41:31.053", "user18_BananaEmu,BananaEmu,1,1447965690000,2015-11-19 12:41:31.053", "user18_ApricotCaneToad,ApricotCaneToad,14,1447965690000,2015-11-19 12:41:31.053" }; static final List<String> GAME_EVENTS = Arrays.asList(GAME_EVENTS_ARRAY); // Used to check the filtering. static final KV[] FILTERED_EVENTS = new KV[] { KV.of("user0_AndroidGreenEchidna", 0), KV.of("user0_MagentaKangaroo", 4), KV.of("user2_AmberCockatoo", 13), KV.of("user18_BananaEmu", 7), KV.of("user3_BananaEmu", 17), KV.of("user18_BananaEmu", 1), KV.of("user18_ApricotCaneToad", 14) }; /** Test the filtering. */ @Test @Category(RunnableOnService.class) public void testUserScoresFilter() throws Exception { Pipeline p = TestPipeline.create(); final Instant startMinTimestamp = new Instant(1447965680000L); PCollection<String> input = p.apply(Create.of(GAME_EVENTS).withCoder(StringUtf8Coder.of())); PCollection<KV<String, Integer>> output = input .apply(ParDo.named("ParseGameEvent").of(new ParseEventFn())) .apply("FilterStartTime", Filter.byPredicate( (GameActionInfo gInfo) -> gInfo.getTimestamp() > startMinTimestamp.getMillis())) // run a map to access the fields in the result. .apply(MapElements .via((GameActionInfo gInfo) -> KV.of(gInfo.getUser(), gInfo.getScore())) .withOutputType(new TypeDescriptor<KV<String, Integer>>() {})); PAssert.that(output).containsInAnyOrder(FILTERED_EVENTS); p.run(); } }
shakamunyi/beam
examples/java8/src/test/java/com/google/cloud/dataflow/examples/complete/game/HourlyTeamScoreTest.java
Java
apache-2.0
5,012
/* * UniformBuffer.hpp * * Created on: 21/08/2013 * Author: svp */ #ifndef UNIFORMBUFFER_HPP_ #define UNIFORMBUFFER_HPP_ #include <stddef.h> typedef unsigned int GLuint; typedef unsigned int GLenum; typedef int GLint; namespace renderer { namespace resources { class UniformBuffer { public: UniformBuffer(); virtual ~UniformBuffer(); void enable() const; void disable() const; void bind(GLuint index) const; void data(size_t size, const void* data) const; GLuint buffer; }; } /* namespace resources */ } /* namespace renderer */ #endif /* UNIFORMBUFFER_HPP_ */
vinther/rmit-rendering
include/renderer/resources/UniformBuffer.hpp
C++
apache-2.0
609
package warden import ( "net/http" "net/url" "github.com/ory-am/fosite" "github.com/ory-am/hydra/firewall" "github.com/ory-am/hydra/pkg" "github.com/pkg/errors" "golang.org/x/net/context" "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" ) type HTTPWarden struct { Client *http.Client Dry bool Endpoint *url.URL } func (w *HTTPWarden) TokenFromRequest(r *http.Request) string { return fosite.AccessTokenFromRequest(r) } func (w *HTTPWarden) SetClient(c *clientcredentials.Config) { w.Client = c.Client(oauth2.NoContext) } // TokenAllowed checks if a token is valid and if the token owner is allowed to perform an action on a resource. // This endpoint requires a token, a scope, a resource name, an action name and a context. // // The HTTP API is documented at http://docs.hydra13.apiary.io/#reference/warden:-access-control-for-resource-providers/check-if-an-access-tokens-subject-is-allowed-to-do-something func (w *HTTPWarden) TokenAllowed(ctx context.Context, token string, a *firewall.TokenAccessRequest, scopes ...string) (*firewall.Context, error) { var resp = struct { *firewall.Context Allowed bool `json:"allowed"` }{} var ep = *w.Endpoint ep.Path = TokenAllowedHandlerPath agent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client} if err := agent.POST(&wardenAccessRequest{ wardenAuthorizedRequest: &wardenAuthorizedRequest{ Token: token, Scopes: scopes, }, TokenAccessRequest: a, }, &resp); err != nil { return nil, err } else if !resp.Allowed { return nil, errors.New("Token is not valid") } return resp.Context, nil } // IsAllowed checks if an arbitrary subject is allowed to perform an action on a resource. // // The HTTP API is documented at http://docs.hydra13.apiary.io/#reference/warden:-access-control-for-resource-providers/check-if-a-subject-is-allowed-to-do-something func (w *HTTPWarden) IsAllowed(ctx context.Context, a *firewall.AccessRequest) error { var allowed = struct { Allowed bool `json:"allowed"` }{} var ep = *w.Endpoint ep.Path = AllowedHandlerPath agent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client} if err := agent.POST(a, &allowed); err != nil { return err } else if !allowed.Allowed { return errors.Wrap(fosite.ErrRequestForbidden, "") } return nil }
Bridg/hydra-1
warden/warden_http.go
GO
apache-2.0
2,295
package gumtree.spoon.diff.operations; import com.github.gumtreediff.actions.model.Move; public class MoveOperation extends AdditionOperation<Move> { public MoveOperation(Move action) { super(action); } }
XuSihan/gumtree-spoon-ast-diff
src/main/java/gumtree/spoon/diff/operations/MoveOperation.java
Java
apache-2.0
211
// 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. #ifndef __SLAVE_FLAGS_HPP__ #define __SLAVE_FLAGS_HPP__ #include <cstdint> #include <string> #include <stout/bytes.hpp> #include <stout/duration.hpp> #include <stout/json.hpp> #include <stout/option.hpp> #include <stout/path.hpp> #include <mesos/module/module.hpp> #include "logging/flags.hpp" #include "messages/flags.hpp" namespace mesos { namespace internal { namespace slave { class Flags : public virtual logging::Flags { public: Flags(); bool version; Option<std::string> hostname; bool hostname_lookup; Option<std::string> resources; Option<std::string> resource_provider_config_dir; Option<std::string> disk_profile_adaptor; std::string isolation; std::string launcher; Option<std::string> image_providers; Option<std::string> image_provisioner_backend; Option<ImageGcConfig> image_gc_config; std::string appc_simple_discovery_uri_prefix; std::string appc_store_dir; std::string docker_registry; std::string docker_store_dir; std::string docker_volume_checkpoint_dir; bool docker_ignore_runtime; std::string default_role; Option<std::string> attributes; Bytes fetcher_cache_size; std::string fetcher_cache_dir; Duration fetcher_stall_timeout; std::string work_dir; std::string runtime_dir; std::string launcher_dir; Option<std::string> hadoop_home; size_t max_completed_executors_per_framework; #ifndef __WINDOWS__ bool switch_user; Option<std::string> volume_gid_range; #endif // __WINDOWS__ Duration http_heartbeat_interval; std::string frameworks_home; // TODO(benh): Make an Option. Duration registration_backoff_factor; Duration authentication_backoff_factor; Duration authentication_timeout_min; Duration authentication_timeout_max; Option<JSON::Object> executor_environment_variables; Duration executor_registration_timeout; Duration executor_reregistration_timeout; Option<Duration> executor_reregistration_retry_interval; Duration executor_shutdown_grace_period; #ifdef USE_SSL_SOCKET Option<Path> jwt_secret_key; #endif // USE_SSL_SOCKET Duration gc_delay; double gc_disk_headroom; bool gc_non_executor_container_sandboxes; Duration disk_watch_interval; Option<std::string> container_logger; std::string reconfiguration_policy; std::string recover; Duration recovery_timeout; bool strict; Duration register_retry_interval_min; #ifdef __linux__ Duration cgroups_destroy_timeout; std::string cgroups_hierarchy; std::string cgroups_root; bool cgroups_enable_cfs; bool cgroups_limit_swap; bool cgroups_cpu_enable_pids_and_tids_count; Option<std::string> cgroups_net_cls_primary_handle; Option<std::string> cgroups_net_cls_secondary_handles; Option<DeviceWhitelist> allowed_devices; Option<std::string> agent_subsystems; Option<std::string> host_path_volume_force_creation; Option<std::vector<unsigned int>> nvidia_gpu_devices; Option<std::string> perf_events; Duration perf_interval; Duration perf_duration; bool revocable_cpu_low_priority; bool systemd_enable_support; std::string systemd_runtime_directory; Option<CapabilityInfo> effective_capabilities; Option<CapabilityInfo> bounding_capabilities; Option<Bytes> default_shm_size; bool disallow_sharing_agent_ipc_namespace; bool disallow_sharing_agent_pid_namespace; #endif Option<Firewall> firewall_rules; Option<Path> credential; Option<ACLs> acls; std::string containerizers; std::string docker; Option<std::string> docker_mesos_image; Duration docker_remove_delay; std::string sandbox_directory; Option<ContainerDNSInfo> default_container_dns; Option<ContainerInfo> default_container_info; // TODO(alexr): Remove this after the deprecation cycle (started in 1.0). Duration docker_stop_timeout; bool docker_kill_orphans; std::string docker_socket; Option<JSON::Object> docker_config; #ifdef ENABLE_PORT_MAPPING_ISOLATOR uint16_t ephemeral_ports_per_container; Option<std::string> eth0_name; Option<std::string> lo_name; Option<Bytes> egress_rate_limit_per_container; bool egress_unique_flow_per_container; std::string egress_flow_classifier_parent; bool network_enable_socket_statistics_summary; bool network_enable_socket_statistics_details; bool network_enable_snmp_statistics; #endif // ENABLE_PORT_MAPPING_ISOLATOR #ifdef ENABLE_NETWORK_PORTS_ISOLATOR Duration container_ports_watch_interval; bool check_agent_port_range_only; bool enforce_container_ports; Option<std::string> container_ports_isolated_range; #endif // ENABLE_NETWORK_PORTS_ISOLATOR Option<std::string> network_cni_plugins_dir; Option<std::string> network_cni_config_dir; bool network_cni_root_dir_persist; bool network_cni_metrics; Duration container_disk_watch_interval; bool enforce_container_disk_quota; Option<Modules> modules; Option<std::string> modulesDir; std::string authenticatee; std::string authorizer; Option<std::string> http_authenticators; bool authenticate_http_readonly; bool authenticate_http_readwrite; #ifdef USE_SSL_SOCKET bool authenticate_http_executors; #endif // USE_SSL_SOCKET Option<Path> http_credentials; Option<std::string> hooks; Option<std::string> secret_resolver; Option<std::string> resource_estimator; Option<std::string> qos_controller; Duration qos_correction_interval_min; Duration oversubscribed_resources_interval; Option<std::string> master_detector; #if ENABLE_XFS_DISK_ISOLATOR std::string xfs_project_range; bool xfs_kill_containers; #endif #if ENABLE_SECCOMP_ISOLATOR Option<std::string> seccomp_config_dir; Option<std::string> seccomp_profile_name; #endif bool http_command_executor; Option<SlaveCapabilities> agent_features; Option<DomainInfo> domain; // The following flags are executable specific (e.g., since we only // have one instance of libprocess per execution, we only want to // advertise the IP and port option once, here). Option<std::string> ip; uint16_t port; Option<std::string> advertise_ip; Option<std::string> advertise_port; Option<flags::SecurePathOrValue> master; bool memory_profiling; Duration zk_session_timeout; // Optional IP discover script that will set the slave's IP. // If set, its output is expected to be a valid parseable IP string. Option<std::string> ip_discovery_command; // IPv6 flags. // // NOTE: These IPv6 flags are currently input mechanisms // for the operator to specify v6 addresses on which containers // running on host network can listen. Mesos itself doesn't listen // or communicate over v6 addresses at this point. Option<std::string> ip6; // Similar to the `ip_discovery_command` this optional discover // script is expected to output a valid IPv6 string. Only one of the // two options `ip6` or `ip6_discovery_command` can be set at any // given point of time. Option<std::string> ip6_discovery_command; }; } // namespace slave { } // namespace internal { } // namespace mesos { #endif // __SLAVE_FLAGS_HPP__
gsantovena/mesos
src/slave/flags.hpp
C++
apache-2.0
7,795
/*! * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var path = require('path'); var uniq = require('array-uniq'); var globby = require('globby'); var spawn = require('child_process').spawnSync; require('shelljs/global'); /** * google-cloud-node root directory.. useful in case we need to cd */ var ROOT_DIR = path.join(__dirname, '..'); module.exports.ROOT_DIR = ROOT_DIR; /** * Helper class to make install dependencies + running tests easier to read * and less error prone. * * @class Module * @param {string} name - The module name (e.g. common, bigquery, etc.) */ function Module(name) { if (!(this instanceof Module)) { return new Module(name); } this.name = name; this.directory = path.join(ROOT_DIR, 'packages', name); var pkgJson = require(path.join(this.directory, 'package.json')); this.packageName = pkgJson.name; this.dependencies = Object.keys(pkgJson.devDependencies || {}); } /** * Umbrella module name. * * @static */ Module.UMBRELLA = 'google-cloud'; /** * Retrieves a list of modules that are ahead of origin/master. We do this by * creating a temporary remote branch that points official master branch. * We then do a git diff against the two to get a list of files. From there we * only care about either JS or JSON files being changed. * * @static * @return {Module[]} modules - The updated modules. */ Module.getUpdated = function() { var command = 'git'; var args = ['diff']; if (!isPushToMaster()) { run([ 'git remote add temp', 'https://github.com/GoogleCloudPlatform/google-cloud-node.git' ]); run('git fetch -q temp'); args.push('HEAD', 'temp/master'); } else { args.push('HEAD^'); } args.push('--name-only'); console.log(command, args.join(' ')); // There's a Windows bug where child_process.exec exits early on `git diff` // which in turn does not return all of the files that have changed. This can // cause a false positive when checking for package changes on AppVeyor var output = spawn(command, args, { cwd: ROOT_DIR, stdio: null }); if (output.status || output.error) { console.error(output.error || output.stderr.toString()); exit(output.status || 1); } var files = output.stdout.toString(); console.log(files); var modules = files .trim() .split('\n') .filter(function(file) { return /^packages\/.+\.js/.test(file); }) .map(function(file) { return file.split('/')[1]; }); return uniq(modules).map(Module); }; /** * Builds docs for all modules * * @static */ Module.buildDocs = function() { run('npm run docs', { cwd: ROOT_DIR }); }; /** * Returns a list containing ALL the modules. * * @static * @return {Module[]} modules - All of em'! */ Module.getAll = function() { cd(ROOT_DIR); return globby .sync('*', { cwd: 'packages' }) .map(Module); }; /** * Returns a list of modules that are dependent on one or more of the modules * specified. * * @static * @param {Module[]} modules - The dependency modules. * @return {Module[]} modules - The dependent modules. */ Module.getDependents = function(modules) { return Module.getAll().filter(function(mod) { return mod.hasDeps(modules); }); }; /** * Installs dependencies for all the modules! * * @static */ Module.installAll = function() { run('npm run postinstall', { cwd: ROOT_DIR }); }; /** * Generates an lcov coverage report for the specified modules. * * @static */ Module.runCoveralls = function() { run('npm run coveralls', { cwd: ROOT_DIR }); }; /** * Installs this modules dependencies via `npm install` */ Module.prototype.install = function() { run('npm install', { cwd: this.directory }); }; /** * Creates/uses symlink for a module (depending on if module was provided) * via `npm link` * * @param {Module=} mod - The module to use with `npm link ${mod.packageName}` */ Module.prototype.link = function(mod) { run(['npm link', mod && mod.packageName || ''], { cwd: this.directory }); }; /** * Runs unit tests for this module via `npm run test` */ Module.prototype.runUnitTests = function() { run('npm run test', { cwd: this.directory }); }; /** * Runs snippet tests for this module. */ Module.prototype.runSnippetTests = function() { process.env.TEST_MODULE = this.name; run('npm run snippet-test', { cwd: ROOT_DIR }); delete process.env.TEST_MODULE; }; /** * Runs system tests for this module via `npm run system-test` */ Module.prototype.runSystemTests = function() { run('npm run system-test', { cwd: this.directory }); }; /** * Checks to see if this module has one or more of the supplied modules * as a dev dependency. * * @param {Module[]} modules - The modules to check for. * @return {boolean} */ Module.prototype.hasDeps = function(modules) { var packageName; for (var i = 0; i < modules.length; i++) { packageName = modules[i].packageName; if (this.dependencies.indexOf(packageName) > -1) { return true; } } return false; }; module.exports.Module = Module; /** * Exec's command via child_process.spawnSync. * By default all output will be piped to the console unless `stdio` * is overridden. * * @param {string} command - The command to run. * @param {object=} options - Options to pass to `spawnSync`. * @return {string|null} */ function run(command, options) { options = options || {}; if (Array.isArray(command)) { command = command.join(' '); } console.log(command); var response = exec(command, options); if (response.code) { exit(response.code); } return response.stdout; } module.exports.run = run; /** * Used to make committing to git easier/etc.. * * @param {string=} cwd - Directory to commit/add/push from. */ function Git(cwd) { this.cwd = cwd || ROOT_DIR; } // We'll use this for cloning/submoduling/pushing purposes on CI Git.REPO = 'https://${GH_OAUTH_TOKEN}@github.com/${GH_OWNER}/${GH_PROJECT_NAME}'; /** * Creates a submodule in the root directory in quiet mode. * * @param {string} branch - The branch to use. * @param {string=} alias - Name of the folder that contains submodule. * @return {Git} */ Git.prototype.submodule = function(branch, alias) { alias = alias || branch; run(['git submodule add -q -b', branch, Git.REPO, alias], { cwd: this.cwd }); return new Git(path.join(this.cwd, alias)); }; /** * Check to see if git has any files it can commit. * * @return {boolean} */ Git.prototype.hasUpdates = function() { var output = run('git status --porcelain', { cwd: this.cwd }); return !!output && output.trim().length > 0; }; /** * Sets git user * * @param {string} name - User name * @param {string} email - User email */ Git.prototype.setUser = function(name, email) { run(['git config --global user.name', name], { cwd: this.cwd }); run(['git config --global user.email', email], { cwd: this.cwd }); }; /** * Adds all files passed in via git add * * @param {...string} file - File to add */ Git.prototype.add = function() { var files = [].slice.call(arguments); var command = ['git add'].concat(files); run(command, { cwd: this.cwd }); }; /** * Commits to git via commit message. * * @param {string} message - The commit message. */ Git.prototype.commit = function(message) { run(['git commit -m', '"' + message + ' [ci skip]"'], { cwd: this.cwd }); }; /** * Runs git status and pushes changes in quiet mode. * * @param {string} branch - The branch to push to. */ Git.prototype.push = function(branch) { run('git status', { cwd: this.cwd }); run(['git push -q', Git.REPO, branch], { cwd: this.cwd }); }; module.exports.git = new Git(); /** * The name of the branch currently being tested. * * @alias ci.BRANCH */ var BRANCH = process.env.TRAVIS_BRANCH || process.env.APPVEYOR_REPO_BRANCH; /** * The pull request number. * * @alias ci.PR_NUMBER; */ var PR_NUMBER = process.env.TRAVIS_PULL_REQUEST || process.env.APPVEYOR_PULL_REQUEST_NUMBER; /** * Checks to see if this is a pull request or not. * * @alias ci.IS_PR */ var IS_PR = !isNaN(parseInt(PR_NUMBER, 10)); /** * Returns the tag name (assuming this is a release) * * @alias ci.getTagName * @return {string|null} */ function getTagName() { return process.env.TRAVIS_TAG || process.env.APPVEYOR_REPO_TAG_NAME; } /** * Let's us know whether or not this is a release. * * @alias ci.isReleaseBuild * @return {string|null} */ function isReleaseBuild() { return !!getTagName(); } /** * Returns name/version of release. * * @alias ci.getRelease * @return {object|null} */ function getRelease() { var tag = getTagName(); if (!tag) { return null; } var parts = tag.split('-'); return { version: parts.pop(), name: parts.pop() || Module.UMBRELLA }; } /** * Checks to see if this is a push to master. * * @alias ci.isPushToMaster * @return {boolean} */ function isPushToMaster() { return BRANCH === 'master' && !IS_PR; } /** * Checks to see if this the CI's first pass (Travis only) * * @alias ci.isFirstPass * @return {boolean} */ function isFirstPass() { return /\.1$/.test(process.env.TRAVIS_JOB_NUMBER); } module.exports.ci = { BRANCH: BRANCH, IS_PR: IS_PR, PR_NUMBER: PR_NUMBER, getTagName: getTagName, isReleaseBuild: isReleaseBuild, getRelease: getRelease, isPushToMaster: isPushToMaster, isFirstPass: isFirstPass };
tcrognon/google-cloud-node
scripts/helpers.js
JavaScript
apache-2.0
10,052
/* * Copyright 2010-2016 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.directconnect.model.transform; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.directconnect.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DescribeConnectionsOnInterconnectResult JSON Unmarshaller */ public class DescribeConnectionsOnInterconnectResultJsonUnmarshaller implements Unmarshaller<DescribeConnectionsOnInterconnectResult, JsonUnmarshallerContext> { public DescribeConnectionsOnInterconnectResult unmarshall( JsonUnmarshallerContext context) throws Exception { DescribeConnectionsOnInterconnectResult describeConnectionsOnInterconnectResult = new DescribeConnectionsOnInterconnectResult(); 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("connections", targetDepth)) { context.nextToken(); describeConnectionsOnInterconnectResult .setConnections(new ListUnmarshaller<Connection>( ConnectionJsonUnmarshaller.getInstance()) .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 describeConnectionsOnInterconnectResult; } private static DescribeConnectionsOnInterconnectResultJsonUnmarshaller instance; public static DescribeConnectionsOnInterconnectResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DescribeConnectionsOnInterconnectResultJsonUnmarshaller(); return instance; } }
dump247/aws-sdk-java
aws-java-sdk-directconnect/src/main/java/com/amazonaws/services/directconnect/model/transform/DescribeConnectionsOnInterconnectResultJsonUnmarshaller.java
Java
apache-2.0
3,202
package com.laimiux.rxactivity; import android.app.Activity; public abstract class LifecycleEvent { private final Kind kind; private final Activity activity; public LifecycleEvent(Kind kind, Activity activity) { this.kind = kind; this.activity = activity; } public Activity activity() { return activity; } public Kind kind() { return kind; } public enum Kind { CREATE, START, RESUME, PAUSE, SAVE_INSTANCE, STOP, DESTROY } }
Laimiux/RxActivity
rxactivity/src/main/java/com/laimiux/rxactivity/LifecycleEvent.java
Java
apache-2.0
495
<?php /* +-------------------------------------------------------------------------+ | Engine of the Enigma Plugin | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License version 2 | | as published by the Free Software Foundation. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License along | | with this program; if not, write to the Free Software Foundation, Inc., | | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. | | | +-------------------------------------------------------------------------+ | Author: Aleksander Machniak <alec@alec.pl> | +-------------------------------------------------------------------------+ */ /* RFC2440: OpenPGP Message Format RFC3156: MIME Security with OpenPGP RFC3851: S/MIME */ class enigma_engine { private $rc; private $enigma; private $pgp_driver; private $smime_driver; public $decryptions = array(); public $signatures = array(); public $signed_parts = array(); const PASSWORD_TIME = 120; /** * Plugin initialization. */ function __construct($enigma) { $this->rc = rcmail::get_instance(); $this->enigma = $enigma; // this will remove passwords from session after some time $this->get_passwords(); } /** * PGP driver initialization. */ function load_pgp_driver() { if ($this->pgp_driver) { return; } $driver = 'enigma_driver_' . $this->rc->config->get('enigma_pgp_driver', 'gnupg'); $username = $this->rc->user->get_username(); // Load driver $this->pgp_driver = new $driver($username); if (!$this->pgp_driver) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: Unable to load PGP driver: $driver" ), true, true); } // Initialise driver $result = $this->pgp_driver->init(); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: ".$result->getMessage() ), true, true); } } /** * S/MIME driver initialization. */ function load_smime_driver() { if ($this->smime_driver) { return; } $driver = 'enigma_driver_' . $this->rc->config->get('enigma_smime_driver', 'phpssl'); $username = $this->rc->user->get_username(); // Load driver $this->smime_driver = new $driver($username); if (!$this->smime_driver) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: Unable to load S/MIME driver: $driver" ), true, true); } // Initialise driver $result = $this->smime_driver->init(); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: ".$result->getMessage() ), true, true); } } /** * Handler for message_part_structure hook. * Called for every part of the message. * * @param array Original parameters * * @return array Modified parameters */ function part_structure($p) { if ($p['mimetype'] == 'text/plain' || $p['mimetype'] == 'application/pgp') { $this->parse_plain($p); } else if ($p['mimetype'] == 'multipart/signed') { $this->parse_signed($p); } else if ($p['mimetype'] == 'multipart/encrypted') { $this->parse_encrypted($p); } else if ($p['mimetype'] == 'application/pkcs7-mime') { $this->parse_encrypted($p); } return $p; } /** * Handler for message_part_body hook. * * @param array Original parameters * * @return array Modified parameters */ function part_body($p) { // encrypted attachment, see parse_plain_encrypted() if ($p['part']->need_decryption && $p['part']->body === null) { $storage = $this->rc->get_storage(); $body = $storage->get_message_part($p['object']->uid, $p['part']->mime_id, $p['part'], null, null, true, 0, false); $result = $this->pgp_decrypt($body); // @TODO: what to do on error? if ($result === true) { $p['part']->body = $body; $p['part']->size = strlen($body); $p['part']->body_modified = true; } } return $p; } /** * Handler for plain/text message. * * @param array Reference to hook's parameters */ function parse_plain(&$p) { $part = $p['structure']; // exit, if we're already inside a decrypted message if ($part->encrypted) { return; } // Get message body from IMAP server $body = $this->get_part_body($p['object'], $part->mime_id); // @TODO: big message body could be a file resource // PGP signed message if (preg_match('/^-----BEGIN PGP SIGNED MESSAGE-----/', $body)) { $this->parse_plain_signed($p, $body); } // PGP encrypted message else if (preg_match('/^-----BEGIN PGP MESSAGE-----/', $body)) { $this->parse_plain_encrypted($p, $body); } } /** * Handler for multipart/signed message. * * @param array Reference to hook's parameters */ function parse_signed(&$p) { $struct = $p['structure']; // S/MIME if ($struct->parts[1] && $struct->parts[1]->mimetype == 'application/pkcs7-signature') { $this->parse_smime_signed($p); } // PGP/MIME: RFC3156 // The multipart/signed body MUST consist of exactly two parts. // The first part contains the signed data in MIME canonical format, // including a set of appropriate content headers describing the data. // The second body MUST contain the PGP digital signature. It MUST be // labeled with a content type of "application/pgp-signature". else if ($struct->ctype_parameters['protocol'] == 'application/pgp-signature' && count($struct->parts) == 2 && $struct->parts[1] && $struct->parts[1]->mimetype == 'application/pgp-signature' ) { $this->parse_pgp_signed($p); } } /** * Handler for multipart/encrypted message. * * @param array Reference to hook's parameters */ function parse_encrypted(&$p) { $struct = $p['structure']; // S/MIME if ($struct->mimetype == 'application/pkcs7-mime') { $this->parse_smime_encrypted($p); } // PGP/MIME: RFC3156 // The multipart/encrypted MUST consist of exactly two parts. The first // MIME body part must have a content type of "application/pgp-encrypted". // This body contains the control information. // The second MIME body part MUST contain the actual encrypted data. It // must be labeled with a content type of "application/octet-stream". else if ($struct->ctype_parameters['protocol'] == 'application/pgp-encrypted' && count($struct->parts) == 2 && $struct->parts[0] && $struct->parts[0]->mimetype == 'application/pgp-encrypted' && $struct->parts[1] && $struct->parts[1]->mimetype == 'application/octet-stream' ) { $this->parse_pgp_encrypted($p); } } /** * Handler for plain signed message. * Excludes message and signature bodies and verifies signature. * * @param array Reference to hook's parameters * @param string Message (part) body */ private function parse_plain_signed(&$p, $body) { $this->load_pgp_driver(); $part = $p['structure']; // Verify signature if ($this->rc->action == 'show' || $this->rc->action == 'preview') { $sig = $this->pgp_verify($body); } // @TODO: Handle big bodies using (temp) files // In this way we can use fgets on string as on file handle $fh = fopen('php://memory', 'br+'); // @TODO: fopen/fwrite errors handling if ($fh) { fwrite($fh, $body); rewind($fh); } $body = $part->body = null; $part->body_modified = true; // Extract body (and signature?) while (!feof($fh)) { $line = fgets($fh, 1024); if ($part->body === null) $part->body = ''; else if (preg_match('/^-----BEGIN PGP SIGNATURE-----/', $line)) break; else $part->body .= $line; } // Remove "Hash" Armor Headers $part->body = preg_replace('/^.*\r*\n\r*\n/', '', $part->body); // de-Dash-Escape (RFC2440) $part->body = preg_replace('/(^|\n)- -/', '\\1-', $part->body); // Store signature data for display if (!empty($sig)) { $this->signed_parts[$part->mime_id] = $part->mime_id; $this->signatures[$part->mime_id] = $sig; } fclose($fh); } /** * Handler for PGP/MIME signed message. * Verifies signature. * * @param array Reference to hook's parameters */ private function parse_pgp_signed(&$p) { // Verify signature if ($this->rc->action == 'show' || $this->rc->action == 'preview') { $this->load_pgp_driver(); $struct = $p['structure']; $msg_part = $struct->parts[0]; $sig_part = $struct->parts[1]; // Get bodies // Note: The first part body need to be full part body with headers // it also cannot be decoded $msg_body = $this->get_part_body($p['object'], $msg_part->mime_id, true); $sig_body = $this->get_part_body($p['object'], $sig_part->mime_id); // Verify $sig = $this->pgp_verify($msg_body, $sig_body); // Store signature data for display $this->signatures[$struct->mime_id] = $sig; // Message can be multipart (assign signature to each subpart) if (!empty($msg_part->parts)) { foreach ($msg_part->parts as $part) $this->signed_parts[$part->mime_id] = $struct->mime_id; } else { $this->signed_parts[$msg_part->mime_id] = $struct->mime_id; } // Remove signature file from attachments list (?) unset($struct->parts[1]); } } /** * Handler for S/MIME signed message. * Verifies signature. * * @param array Reference to hook's parameters */ private function parse_smime_signed(&$p) { return; // @TODO // Verify signature if ($this->rc->action == 'show' || $this->rc->action == 'preview') { $this->load_smime_driver(); $struct = $p['structure']; $msg_part = $struct->parts[0]; // Verify $sig = $this->smime_driver->verify($struct, $p['object']); // Store signature data for display $this->signatures[$struct->mime_id] = $sig; // Message can be multipart (assign signature to each subpart) if (!empty($msg_part->parts)) { foreach ($msg_part->parts as $part) $this->signed_parts[$part->mime_id] = $struct->mime_id; } else { $this->signed_parts[$msg_part->mime_id] = $struct->mime_id; } // Remove signature file from attachments list unset($struct->parts[1]); } } /** * Handler for plain encrypted message. * * @param array Reference to hook's parameters * @param string Message (part) body */ private function parse_plain_encrypted(&$p, $body) { $this->load_pgp_driver(); $part = $p['structure']; // Decrypt $result = $this->pgp_decrypt($body); // Store decryption status $this->decryptions[$part->mime_id] = $result; // Parse decrypted message if ($result === true) { $part->body = $body; $part->body_modified = true; $part->encrypted = true; // Encrypted plain message may contain encrypted attachments // in such case attachments have .pgp extension and application/octet-stream. // This is what happens when you select "Encrypt each attachment separately // and send the message using inline PGP" in Thunderbird's Enigmail. // find parent part ID if (strpos($part->mime_id, '.')) { $items = explode('.', $part->mime_id); array_pop($items); $parent = implode('.', $items); } else { $parent = 0; } if ($p['object']->mime_parts[$parent]) { foreach ((array)$p['object']->mime_parts[$parent]->parts as $p) { if ($p->disposition == 'attachment' && $p->mimetype == 'application/octet-stream' && preg_match('/^(.*)\.pgp$/i', $p->filename, $m) ) { // modify filename $p->filename = $m[1]; // flag the part, it will be decrypted when needed $p->need_decryption = true; // disable caching $p->body_modified = true; } } } } } /** * Handler for PGP/MIME encrypted message. * * @param array Reference to hook's parameters */ private function parse_pgp_encrypted(&$p) { $this->load_pgp_driver(); $struct = $p['structure']; $part = $struct->parts[1]; // Get body $body = $this->get_part_body($p['object'], $part->mime_id); // Decrypt $result = $this->pgp_decrypt($body); if ($result === true) { // Parse decrypted message $struct = $this->parse_body($body); // Modify original message structure $this->modify_structure($p, $struct); // Attach the decryption message to all parts $this->decryptions[$struct->mime_id] = $result; foreach ((array) $struct->parts as $sp) { $this->decryptions[$sp->mime_id] = $result; } } else { $this->decryptions[$part->mime_id] = $result; // Make sure decryption status message will be displayed $part->type = 'content'; $p['object']->parts[] = $part; } } /** * Handler for S/MIME encrypted message. * * @param array Reference to hook's parameters */ private function parse_smime_encrypted(&$p) { // $this->load_smime_driver(); } /** * PGP signature verification. * * @param mixed Message body * @param mixed Signature body (for MIME messages) * * @return mixed enigma_signature or enigma_error */ private function pgp_verify(&$msg_body, $sig_body=null) { // @TODO: Handle big bodies using (temp) files // @TODO: caching of verification result $sig = $this->pgp_driver->verify($msg_body, $sig_body); if (($sig instanceof enigma_error) && $sig->getCode() != enigma_error::E_KEYNOTFOUND) rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $sig->getMessage() ), true, false); return $sig; } /** * PGP message decryption. * * @param mixed Message body * * @return mixed True or enigma_error */ private function pgp_decrypt(&$msg_body) { // @TODO: Handle big bodies using (temp) files // @TODO: caching of verification result $keys = $this->get_passwords(); $result = $this->pgp_driver->decrypt($msg_body, $keys); if ($result instanceof enigma_error) { $err_code = $result->getCode(); if (!in_array($err_code, array(enigma_error::E_KEYNOTFOUND, enigma_error::E_BADPASS))) rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); return $result; } $msg_body = $result; return true; } /** * PGP keys listing. * * @param mixed Key ID/Name pattern * * @return mixed Array of keys or enigma_error */ function list_keys($pattern = '') { $this->load_pgp_driver(); $result = $this->pgp_driver->list_keys($pattern); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); } return $result; } /** * PGP key details. * * @param mixed Key ID * * @return mixed enigma_key or enigma_error */ function get_key($keyid) { $this->load_pgp_driver(); $result = $this->pgp_driver->get_key($keyid); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); } return $result; } /** * PGP key delete. * * @param string Key ID * * @return enigma_error|bool True on success */ function delete_key($keyid) { $this->load_pgp_driver(); $result = $this->pgp_driver->delete_key($keyid); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); } return $result; } /** * PGP keys/certs importing. * * @param mixed Import file name or content * @param boolean True if first argument is a filename * * @return mixed Import status data array or enigma_error */ function import_key($content, $isfile=false) { $this->load_pgp_driver(); $result = $this->pgp_driver->import($content, $isfile); if ($result instanceof enigma_error) { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Enigma plugin: " . $result->getMessage() ), true, false); } else { $result['imported'] = $result['public_imported'] + $result['private_imported']; $result['unchanged'] = $result['public_unchanged'] + $result['private_unchanged']; } return $result; } /** * Handler for keys/certs import request action */ function import_file() { $uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST); $mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST); $mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST); $storage = $this->rc->get_storage(); if ($uid && $mime_id) { $storage->set_folder($mbox); $part = $storage->get_message_part($uid, $mime_id); } if ($part && is_array($result = $this->import_key($part))) { $this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation', array('new' => $result['imported'], 'old' => $result['unchanged'])); } else $this->rc->output->show_message('enigma.keysimportfailed', 'error'); $this->rc->output->send(); } function password_handler() { $keyid = rcube_utils::get_input_value('_keyid', rcube_utils::INPUT_POST); $passwd = rcube_utils::get_input_value('_passwd', rcube_utils::INPUT_POST, true); if ($keyid && $passwd !== null && strlen($passwd)) { $this->save_password($keyid, $passwd); } } function save_password($keyid, $password) { // we store passwords in session for specified time if ($config = $_SESSION['enigma_pass']) { $config = $this->rc->decrypt($config); $config = @unserialize($config); } $config[$keyid] = array($password, time()); $_SESSION['enigma_pass'] = $this->rc->encrypt(serialize($config)); } function get_passwords() { if ($config = $_SESSION['enigma_pass']) { $config = $this->rc->decrypt($config); $config = @unserialize($config); } $threshold = time() - self::PASSWORD_TIME; $keys = array(); // delete expired passwords foreach ((array) $config as $key => $value) { if ($value[1] < $threshold) { unset($config[$key]); $modified = true; } else { $keys[$key] = $value[0]; } } if ($modified) { $_SESSION['enigma_pass'] = $this->rc->encrypt(serialize($config)); } return $keys; } /** * Get message part body. * * @param rcube_message Message object * @param string Message part ID * @param bool Return raw body with headers */ private function get_part_body($msg, $part_id, $full = false) { // @TODO: Handle big bodies using file handles if ($full) { $storage = $this->rc->get_storage(); $body = $storage->get_raw_headers($msg->uid, $part_id); $body .= $storage->get_raw_body($msg->uid, null, $part_id); } else { $body = $msg->get_part_body($part_id, false); } return $body; } /** * Parse decrypted message body into structure * * @param string Message body * * @return array Message structure */ private function parse_body(&$body) { // Mail_mimeDecode need \r\n end-line, but gpg may return \n $body = preg_replace('/\r?\n/', "\r\n", $body); // parse the body into structure $struct = rcube_mime::parse_message($body); return $struct; } /** * Replace message encrypted structure with decrypted message structure * * @param array * @param rcube_message_part */ private function modify_structure(&$p, $struct) { // modify mime_parts property of the message object $old_id = $p['structure']->mime_id; foreach (array_keys($p['object']->mime_parts) as $idx) { if (!$old_id || $idx == $old_id || strpos($idx, $old_id . '.') === 0) { unset($p['object']->mime_parts[$idx]); } } // modify the new structure to be correctly handled by Roundcube $this->modify_structure_part($struct, $p['object'], $old_id); // replace old structure with the new one $p['structure'] = $struct; $p['mimetype'] = $struct->mimetype; } /** * Modify decrypted message part * * @param rcube_message_part * @param rcube_message */ private function modify_structure_part($part, $msg, $old_id) { // never cache the body $part->body_modified = true; $part->encoding = 'stream'; // Cache the fact it was decrypted $part->encrypted = true; // modify part identifier if ($old_id) { $part->mime_id = !$part->mime_id ? $old_id : ($old_id . '.' . $part->mime_id); } $msg->mime_parts[$part->mime_id] = $part; // modify sub-parts foreach ((array) $part->parts as $p) { $this->modify_structure_part($p, $msg, $old_id); } } /** * Checks if specified message part is a PGP-key or S/MIME cert data * * @param rcube_message_part Part object * * @return boolean True if part is a key/cert */ public function is_keys_part($part) { // @TODO: S/MIME return ( // Content-Type: application/pgp-keys $part->mimetype == 'application/pgp-keys' ); } }
kfmaster/cicdlab
modules/docker-roundcubemail/plugins/enigma/lib/enigma_engine.php
PHP
apache-2.0
26,398
# Copyright 2021 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional, Sequence from pyquil import get_qc from pyquil.api import QuantumComputer import cirq from cirq_rigetti import circuit_transformers as transformers from cirq_rigetti import circuit_sweep_executors as executors _default_executor = executors.with_quilc_compilation_and_cirq_parameter_resolution class RigettiQCSSampler(cirq.Sampler): """This class supports running circuits on QCS quantum hardware as well as pyQuil's quantum virtual machine (QVM). It implements the `cirq.Sampler` interface and thereby supports sampling parameterized circuits across parameter sweeps. """ def __init__( self, quantum_computer: QuantumComputer, executor: executors.CircuitSweepExecutor = _default_executor, transformer: transformers.CircuitTransformer = transformers.default, ): """Initializes a `RigettiQCSSampler`. Args: quantum_computer: A `pyquil.api.QuantumComputer` against which to run the `cirq.Circuit`s. executor: A callable that first uses the below `transformer` on `cirq.Circuit` s and then executes the transformed circuit on the `quantum_computer`. You may pass your own callable or any static method on `CircuitSweepExecutors`. transformer: A callable that transforms the `cirq.Circuit` into a `pyquil.Program`. You may pass your own callable or any static method on `CircuitTransformers`. """ self._quantum_computer = quantum_computer self.executor = executor self.transformer = transformer def run_sweep( self, program: cirq.AbstractCircuit, params: cirq.Sweepable, repetitions: int = 1, ) -> Sequence[cirq.Result]: """This will evaluate results on the circuit for every set of parameters in `params`. Args: program: Circuit to evaluate for each set of parameters in `params`. params: `cirq.Sweepable` of parameters which this function passes to `cirq.protocols.resolve_parameters` for evaluating the circuit. repetitions: Number of times to run each iteration through the `params`. For a given set of parameters, the `cirq.Result` will include a measurement for each repetition. Returns: A list of `cirq.Result` s. """ resolvers = [r for r in cirq.to_resolvers(params)] return self.executor( quantum_computer=self._quantum_computer, circuit=program.unfreeze(copy=False), resolvers=resolvers, repetitions=repetitions, transformer=self.transformer, ) def get_rigetti_qcs_sampler( quantum_processor_id: str, *, as_qvm: Optional[bool] = None, noisy: Optional[bool] = None, executor: executors.CircuitSweepExecutor = _default_executor, transformer: transformers.CircuitTransformer = transformers.default, ) -> RigettiQCSSampler: """Calls `pyquil.get_qc` to initialize a `pyquil.api.QuantumComputer` and uses this to initialize `RigettiQCSSampler`. Args: quantum_processor_id: The name of the desired quantum computer. This should correspond to a name returned by `pyquil.api.list_quantum_computers`. Names ending in "-qvm" will return a QVM. Names ending in "-pyqvm" will return a `pyquil.PyQVM`. Otherwise, we will return a Rigetti QCS QPU if one exists with the requested name. as_qvm: An optional flag to force construction of a QVM (instead of a QPU). If specified and set to `True`, a QVM-backed quantum computer will be returned regardless of the name's suffix noisy: An optional flag to force inclusion of a noise model. If specified and set to `True`, a quantum computer with a noise model will be returned. The generic QVM noise model is simple T1 and T2 noise plus readout error. At the time of this writing, this has no effect on a QVM initialized based on a Rigetti QCS `qcs_api_client.models.InstructionSetArchitecture`. executor: A callable that first uses the below transformer on cirq.Circuit s and then executes the transformed circuit on the quantum_computer. You may pass your own callable or any static method on CircuitSweepExecutors. transformer: A callable that transforms the cirq.Circuit into a pyquil.Program. You may pass your own callable or any static method on CircuitTransformers. Returns: A `RigettiQCSSampler` with the specified quantum processor, executor, and transformer. """ qc = get_qc( quantum_processor_id, as_qvm=as_qvm, noisy=noisy, ) return RigettiQCSSampler( quantum_computer=qc, executor=executor, transformer=transformer, )
quantumlib/Cirq
cirq-rigetti/cirq_rigetti/sampler.py
Python
apache-2.0
5,548
package com.afeng.xf.utils.AFengUtils; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.support.annotation.ColorInt; import android.support.design.widget.CoordinatorLayout; import android.support.v4.widget.DrawerLayout; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.LinearLayout; import com.afeng.xf.R; /** * Created by Jaeger on 16/2/14. * <p> * Email: chjie.jaeger@gmail.com * GitHub: https://github.com/laobie */ public class StatusBarUtil { public static final int DEFAULT_STATUS_BAR_ALPHA = 112; private static final int FAKE_STATUS_BAR_VIEW_ID = R.id.statusbarutil_fake_status_bar_view; private static final int FAKE_TRANSLUCENT_VIEW_ID = R.id.statusbarutil_translucent_view; private static final int TAG_KEY_HAVE_SET_OFFSET = -123; /** * ้š่—่œๅ•ใ€‚ๆฒ‰ๆตธๅผ้˜…่ฏป */ public static void hideSystemUI(Activity activity) { // Set the IMMERSIVE flag. // Set the content to appear under the system bars so that the content // doesn't resize when the system bars hide and show. activity.getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY ); } public static void showSystemUI(Activity activity) { activity.getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE // | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY ); } /** * ่ฎพ็ฝฎ็Šถๆ€ๆ ้ขœ่‰ฒ * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„ activity * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ */ public static void setColor(Activity activity, @ColorInt int color) { setColor(activity, color, DEFAULT_STATUS_BAR_ALPHA); } /** * ่ฎพ็ฝฎ็Šถๆ€ๆ ้ขœ่‰ฒ * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ * @param statusBarAlpha ็Šถๆ€ๆ ้€ๆ˜Žๅบฆ */ public static void setColor(Activity activity, @ColorInt int color, int statusBarAlpha) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().setStatusBarColor(calculateStatusColor(color, statusBarAlpha)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); } else { decorView.addView(createStatusBarView(activity, color, statusBarAlpha)); } setRootView(activity); } } /** * ไธบๆป‘ๅŠจ่ฟ”ๅ›ž็•Œ้ข่ฎพ็ฝฎ็Šถๆ€ๆ ้ขœ่‰ฒ * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ */ public static void setColorForSwipeBack(Activity activity, int color) { setColorForSwipeBack(activity, color, DEFAULT_STATUS_BAR_ALPHA); } /** * ไธบๆป‘ๅŠจ่ฟ”ๅ›ž็•Œ้ข่ฎพ็ฝฎ็Šถๆ€ๆ ้ขœ่‰ฒ * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ * @param statusBarAlpha ็Šถๆ€ๆ ้€ๆ˜Žๅบฆ */ public static void setColorForSwipeBack(Activity activity, @ColorInt int color, int statusBarAlpha) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { ViewGroup contentView = ((ViewGroup) activity.findViewById(android.R.id.content)); View rootView = contentView.getChildAt(0); int statusBarHeight = getStatusBarHeight(activity); if (rootView != null && rootView instanceof CoordinatorLayout) { final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) rootView; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { coordinatorLayout.setFitsSystemWindows(false); contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); boolean isNeedRequestLayout = contentView.getPaddingTop() < statusBarHeight; if (isNeedRequestLayout) { contentView.setPadding(0, statusBarHeight, 0, 0); coordinatorLayout.post(new Runnable() { @Override public void run() { coordinatorLayout.requestLayout(); } }); } } else { coordinatorLayout.setStatusBarBackgroundColor(calculateStatusColor(color, statusBarAlpha)); } } else { contentView.setPadding(0, statusBarHeight, 0, 0); contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha)); } setTransparentForWindow(activity); } } /** * ่ฎพ็ฝฎ็Šถๆ€ๆ ็บฏ่‰ฒ ไธๅŠ ๅŠ้€ๆ˜Žๆ•ˆๆžœ * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„ activity * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ */ public static void setColorNoTranslucent(Activity activity, @ColorInt int color) { setColor(activity, color, 0); } /** * ่ฎพ็ฝฎ็Šถๆ€ๆ ้ขœ่‰ฒ(5.0ไปฅไธ‹ๆ— ๅŠ้€ๆ˜Žๆ•ˆๆžœ,ไธๅปบ่ฎฎไฝฟ็”จ) * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„ activity * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ */ @Deprecated public static void setColorDiff(Activity activity, @ColorInt int color) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } transparentStatusBar(activity); ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); // ็งป้™คๅŠ้€ๆ˜Ž็Ÿฉๅฝข,ไปฅๅ…ๅ ๅŠ  View fakeStatusBarView = contentView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(color); } else { contentView.addView(createStatusBarView(activity, color)); } setRootView(activity); } /** * ไฝฟ็Šถๆ€ๆ ๅŠ้€ๆ˜Ž * <p> * ้€‚็”จไบŽๅ›พ็‰‡ไฝœไธบ่ƒŒๆ™ฏ็š„็•Œ้ข,ๆญคๆ—ถ้œ€่ฆๅ›พ็‰‡ๅกซๅ……ๅˆฐ็Šถๆ€ๆ  * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity */ public static void setTranslucent(Activity activity) { setTranslucent(activity, DEFAULT_STATUS_BAR_ALPHA); } /** * ไฝฟ็Šถๆ€ๆ ๅŠ้€ๆ˜Ž * <p> * ้€‚็”จไบŽๅ›พ็‰‡ไฝœไธบ่ƒŒๆ™ฏ็š„็•Œ้ข,ๆญคๆ—ถ้œ€่ฆๅ›พ็‰‡ๅกซๅ……ๅˆฐ็Šถๆ€ๆ  * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param statusBarAlpha ็Šถๆ€ๆ ้€ๆ˜Žๅบฆ */ public static void setTranslucent(Activity activity, int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } setTransparent(activity); addTranslucentView(activity, statusBarAlpha); } /** * ้’ˆๅฏนๆ นๅธƒๅฑ€ๆ˜ฏ CoordinatorLayout, ไฝฟ็Šถๆ€ๆ ๅŠ้€ๆ˜Ž * <p> * ้€‚็”จไบŽๅ›พ็‰‡ไฝœไธบ่ƒŒๆ™ฏ็š„็•Œ้ข,ๆญคๆ—ถ้œ€่ฆๅ›พ็‰‡ๅกซๅ……ๅˆฐ็Šถๆ€ๆ  * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param statusBarAlpha ็Šถๆ€ๆ ้€ๆ˜Žๅบฆ */ public static void setTranslucentForCoordinatorLayout(Activity activity, int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } transparentStatusBar(activity); addTranslucentView(activity, statusBarAlpha); } /** * ่ฎพ็ฝฎ็Šถๆ€ๆ ๅ…จ้€ๆ˜Ž * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity */ public static void setTransparent(Activity activity) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } transparentStatusBar(activity); setRootView(activity); } /** * ไฝฟ็Šถๆ€ๆ ้€ๆ˜Ž(5.0ไปฅไธŠๅŠ้€ๆ˜Žๆ•ˆๆžœ,ไธๅปบ่ฎฎไฝฟ็”จ) * <p> * ้€‚็”จไบŽๅ›พ็‰‡ไฝœไธบ่ƒŒๆ™ฏ็š„็•Œ้ข,ๆญคๆ—ถ้œ€่ฆๅ›พ็‰‡ๅกซๅ……ๅˆฐ็Šถๆ€ๆ  * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity */ @Deprecated public static void setTranslucentDiff(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // ่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); setRootView(activity); } } /** * ไธบDrawerLayout ๅธƒๅฑ€่ฎพ็ฝฎ็Šถๆ€ๆ ๅ˜่‰ฒ * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param drawerLayout DrawerLayout * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ */ public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { setColorForDrawerLayout(activity, drawerLayout, color, DEFAULT_STATUS_BAR_ALPHA); } /** * ไธบDrawerLayout ๅธƒๅฑ€่ฎพ็ฝฎ็Šถๆ€ๆ ้ขœ่‰ฒ,็บฏ่‰ฒ * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param drawerLayout DrawerLayout * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ */ public static void setColorNoTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { setColorForDrawerLayout(activity, drawerLayout, color, 0); } /** * ไธบDrawerLayout ๅธƒๅฑ€่ฎพ็ฝฎ็Šถๆ€ๆ ๅ˜่‰ฒ * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param drawerLayout DrawerLayout * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ * @param statusBarAlpha ็Šถๆ€ๆ ้€ๆ˜Žๅบฆ */ public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, @ColorInt int color, int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } else { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } // ็”Ÿๆˆไธ€ไธช็Šถๆ€ๆ ๅคงๅฐ็š„็Ÿฉๅฝข // ๆทปๅŠ  statusBarView ๅˆฐๅธƒๅฑ€ไธญ ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); View fakeStatusBarView = contentLayout.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(color); } else { contentLayout.addView(createStatusBarView(activity, color), 0); } // ๅ†…ๅฎนๅธƒๅฑ€ไธๆ˜ฏ LinearLayout ๆ—ถ,่ฎพ็ฝฎpadding top if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { contentLayout.getChildAt(1) .setPadding(contentLayout.getPaddingLeft(), getStatusBarHeight(activity) + contentLayout.getPaddingTop(), contentLayout.getPaddingRight(), contentLayout.getPaddingBottom()); } // ่ฎพ็ฝฎๅฑžๆ€ง setDrawerLayoutProperty(drawerLayout, contentLayout); addTranslucentView(activity, statusBarAlpha); } /** * ่ฎพ็ฝฎ DrawerLayout ๅฑžๆ€ง * * @param drawerLayout DrawerLayout * @param drawerLayoutContentLayout DrawerLayout ็š„ๅ†…ๅฎนๅธƒๅฑ€ */ private static void setDrawerLayoutProperty(DrawerLayout drawerLayout, ViewGroup drawerLayoutContentLayout) { ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); drawerLayout.setFitsSystemWindows(false); drawerLayoutContentLayout.setFitsSystemWindows(false); drawerLayoutContentLayout.setClipToPadding(true); drawer.setFitsSystemWindows(false); } /** * ไธบDrawerLayout ๅธƒๅฑ€่ฎพ็ฝฎ็Šถๆ€ๆ ๅ˜่‰ฒ(5.0ไปฅไธ‹ๆ— ๅŠ้€ๆ˜Žๆ•ˆๆžœ,ไธๅปบ่ฎฎไฝฟ็”จ) * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param drawerLayout DrawerLayout * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ */ @Deprecated public static void setColorForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout, @ColorInt int color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // ็”Ÿๆˆไธ€ไธช็Šถๆ€ๆ ๅคงๅฐ็š„็Ÿฉๅฝข ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); View fakeStatusBarView = contentLayout.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(calculateStatusColor(color, DEFAULT_STATUS_BAR_ALPHA)); } else { // ๆทปๅŠ  statusBarView ๅˆฐๅธƒๅฑ€ไธญ contentLayout.addView(createStatusBarView(activity, color), 0); } // ๅ†…ๅฎนๅธƒๅฑ€ไธๆ˜ฏ LinearLayout ๆ—ถ,่ฎพ็ฝฎpadding top if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0); } // ่ฎพ็ฝฎๅฑžๆ€ง setDrawerLayoutProperty(drawerLayout, contentLayout); } } /** * ไธบ DrawerLayout ๅธƒๅฑ€่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param drawerLayout DrawerLayout */ public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) { setTranslucentForDrawerLayout(activity, drawerLayout, DEFAULT_STATUS_BAR_ALPHA); } /** * ไธบ DrawerLayout ๅธƒๅฑ€่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param drawerLayout DrawerLayout */ public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, int statusBarAlpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } setTransparentForDrawerLayout(activity, drawerLayout); addTranslucentView(activity, statusBarAlpha); } /** * ไธบ DrawerLayout ๅธƒๅฑ€่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param drawerLayout DrawerLayout */ public static void setTransparentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } else { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); // ๅ†…ๅฎนๅธƒๅฑ€ไธๆ˜ฏ LinearLayout ๆ—ถ,่ฎพ็ฝฎpadding top if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) { contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0); } // ่ฎพ็ฝฎๅฑžๆ€ง setDrawerLayoutProperty(drawerLayout, contentLayout); } /** * ไธบ DrawerLayout ๅธƒๅฑ€่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž(5.0ไปฅไธŠๅŠ้€ๆ˜Žๆ•ˆๆžœ,ไธๅปบ่ฎฎไฝฟ็”จ) * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param drawerLayout DrawerLayout */ @Deprecated public static void setTranslucentForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // ่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // ่ฎพ็ฝฎๅ†…ๅฎนๅธƒๅฑ€ๅฑžๆ€ง ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0); contentLayout.setFitsSystemWindows(true); contentLayout.setClipToPadding(true); // ่ฎพ็ฝฎๆŠฝๅฑ‰ๅธƒๅฑ€ๅฑžๆ€ง ViewGroup vg = (ViewGroup) drawerLayout.getChildAt(1); vg.setFitsSystemWindows(false); // ่ฎพ็ฝฎ DrawerLayout ๅฑžๆ€ง drawerLayout.setFitsSystemWindows(false); } } /** * ไธบๅคด้ƒจๆ˜ฏ ImageView ็š„็•Œ้ข่ฎพ็ฝฎ็Šถๆ€ๆ ๅ…จ้€ๆ˜Ž * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param needOffsetView ้œ€่ฆๅ‘ไธ‹ๅ็งป็š„ View */ public static void setTransparentForImageView(Activity activity, View needOffsetView) { setTranslucentForImageView(activity, 0, needOffsetView); } /** * ไธบๅคด้ƒจๆ˜ฏ ImageView ็š„็•Œ้ข่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž(ไฝฟ็”จ้ป˜่ฎค้€ๆ˜Žๅบฆ) * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param needOffsetView ้œ€่ฆๅ‘ไธ‹ๅ็งป็š„ View */ public static void setTranslucentForImageView(Activity activity, View needOffsetView) { setTranslucentForImageView(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); } /** * ไธบๅคด้ƒจๆ˜ฏ ImageView ็š„็•Œ้ข่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param statusBarAlpha ็Šถๆ€ๆ ้€ๆ˜Žๅบฆ * @param needOffsetView ้œ€่ฆๅ‘ไธ‹ๅ็งป็š„ View */ public static void setTranslucentForImageView(Activity activity, int statusBarAlpha, View needOffsetView) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } setTransparentForWindow(activity); addTranslucentView(activity, statusBarAlpha); if (needOffsetView != null) { Object haveSetOffset = needOffsetView.getTag(TAG_KEY_HAVE_SET_OFFSET); if (haveSetOffset != null && (Boolean) haveSetOffset) { return; } ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) needOffsetView.getLayoutParams(); layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin + getStatusBarHeight(activity), layoutParams.rightMargin, layoutParams.bottomMargin); needOffsetView.setTag(TAG_KEY_HAVE_SET_OFFSET, true); } } /** * ไธบ fragment ๅคด้ƒจๆ˜ฏ ImageView ็š„่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž * * @param activity fragment ๅฏนๅบ”็š„ activity * @param needOffsetView ้œ€่ฆๅ‘ไธ‹ๅ็งป็š„ View */ public static void setTranslucentForImageViewInFragment(Activity activity, View needOffsetView) { setTranslucentForImageViewInFragment(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView); } /** * ไธบ fragment ๅคด้ƒจๆ˜ฏ ImageView ็š„่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž * * @param activity fragment ๅฏนๅบ”็š„ activity * @param needOffsetView ้œ€่ฆๅ‘ไธ‹ๅ็งป็š„ View */ public static void setTransparentForImageViewInFragment(Activity activity, View needOffsetView) { setTranslucentForImageViewInFragment(activity, 0, needOffsetView); } /** * ไธบ fragment ๅคด้ƒจๆ˜ฏ ImageView ็š„่ฎพ็ฝฎ็Šถๆ€ๆ ้€ๆ˜Ž * * @param activity fragment ๅฏนๅบ”็š„ activity * @param statusBarAlpha ็Šถๆ€ๆ ้€ๆ˜Žๅบฆ * @param needOffsetView ้œ€่ฆๅ‘ไธ‹ๅ็งป็š„ View */ public static void setTranslucentForImageViewInFragment(Activity activity, int statusBarAlpha, View needOffsetView) { setTranslucentForImageView(activity, statusBarAlpha, needOffsetView); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { clearPreviousSetting(activity); } } /** * ้š่—ไผช็Šถๆ€ๆ  View * * @param activity ่ฐƒ็”จ็š„ Activity */ public static void hideFakeStatusBarView(Activity activity) { ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { fakeStatusBarView.setVisibility(View.GONE); } View fakeTranslucentView = decorView.findViewById(FAKE_TRANSLUCENT_VIEW_ID); if (fakeTranslucentView != null) { fakeTranslucentView.setVisibility(View.GONE); } } /////////////////////////////////////////////////////////////////////////////////// @TargetApi(Build.VERSION_CODES.KITKAT) private static void clearPreviousSetting(Activity activity) { ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); View fakeStatusBarView = decorView.findViewById(FAKE_STATUS_BAR_VIEW_ID); if (fakeStatusBarView != null) { decorView.removeView(fakeStatusBarView); ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); rootView.setPadding(0, 0, 0, 0); } } /** * ๆทปๅŠ ๅŠ้€ๆ˜Ž็Ÿฉๅฝขๆก * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„ activity * @param statusBarAlpha ้€ๆ˜Žๅ€ผ */ private static void addTranslucentView(Activity activity, int statusBarAlpha) { ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); View fakeTranslucentView = contentView.findViewById(FAKE_TRANSLUCENT_VIEW_ID); if (fakeTranslucentView != null) { if (fakeTranslucentView.getVisibility() == View.GONE) { fakeTranslucentView.setVisibility(View.VISIBLE); } fakeTranslucentView.setBackgroundColor(Color.argb(statusBarAlpha, 0, 0, 0)); } else { contentView.addView(createTranslucentStatusBarView(activity, statusBarAlpha)); } } /** * ็”Ÿๆˆไธ€ไธชๅ’Œ็Šถๆ€ๆ ๅคงๅฐ็›ธๅŒ็š„ๅฝฉ่‰ฒ็Ÿฉๅฝขๆก * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„ activity * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ * @return ็Šถๆ€ๆ ็Ÿฉๅฝขๆก */ private static View createStatusBarView(Activity activity, @ColorInt int color) { return createStatusBarView(activity, color, 0); } /** * ็”Ÿๆˆไธ€ไธชๅ’Œ็Šถๆ€ๆ ๅคงๅฐ็›ธๅŒ็š„ๅŠ้€ๆ˜Ž็Ÿฉๅฝขๆก * * @param activity ้œ€่ฆ่ฎพ็ฝฎ็š„activity * @param color ็Šถๆ€ๆ ้ขœ่‰ฒๅ€ผ * @param alpha ้€ๆ˜Žๅ€ผ * @return ็Šถๆ€ๆ ็Ÿฉๅฝขๆก */ private static View createStatusBarView(Activity activity, @ColorInt int color, int alpha) { // ็ป˜ๅˆถไธ€ไธชๅ’Œ็Šถๆ€ๆ ไธ€ๆ ท้ซ˜็š„็Ÿฉๅฝข View statusBarView = new View(activity); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity)); statusBarView.setLayoutParams(params); statusBarView.setBackgroundColor(calculateStatusColor(color, alpha)); statusBarView.setId(FAKE_STATUS_BAR_VIEW_ID); return statusBarView; } /** * ่ฎพ็ฝฎๆ นๅธƒๅฑ€ๅ‚ๆ•ฐ */ private static void setRootView(Activity activity) { ViewGroup parent = (ViewGroup) activity.findViewById(android.R.id.content); for (int i = 0, count = parent.getChildCount(); i < count; i++) { View childView = parent.getChildAt(i); if (childView instanceof ViewGroup) { childView.setFitsSystemWindows(true); ((ViewGroup) childView).setClipToPadding(true); } } } /** * ่ฎพ็ฝฎ้€ๆ˜Ž */ private static void setTransparentForWindow(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().setStatusBarColor(Color.TRANSPARENT); activity.getWindow() .getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow() .setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } /** * ไฝฟ็Šถๆ€ๆ ้€ๆ˜Ž */ @TargetApi(Build.VERSION_CODES.KITKAT) private static void transparentStatusBar(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } else { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } /** * ๅˆ›ๅปบๅŠ้€ๆ˜Ž็Ÿฉๅฝข View * * @param alpha ้€ๆ˜Žๅ€ผ * @return ๅŠ้€ๆ˜Ž View */ private static View createTranslucentStatusBarView(Activity activity, int alpha) { // ็ป˜ๅˆถไธ€ไธชๅ’Œ็Šถๆ€ๆ ไธ€ๆ ท้ซ˜็š„็Ÿฉๅฝข View statusBarView = new View(activity); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity)); statusBarView.setLayoutParams(params); statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0)); statusBarView.setId(FAKE_TRANSLUCENT_VIEW_ID); return statusBarView; } /** * ่Žทๅ–็Šถๆ€ๆ ้ซ˜ๅบฆ * * @param context context * @return ็Šถๆ€ๆ ้ซ˜ๅบฆ */ private static int getStatusBarHeight(Context context) { // ่Žทๅพ—็Šถๆ€ๆ ้ซ˜ๅบฆ int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); return context.getResources().getDimensionPixelSize(resourceId); } /** * ่ฎก็ฎ—็Šถๆ€ๆ ้ขœ่‰ฒ * * @param color colorๅ€ผ * @param alpha alphaๅ€ผ * @return ๆœ€็ปˆ็š„็Šถๆ€ๆ ้ขœ่‰ฒ */ private static int calculateStatusColor(@ColorInt int color, int alpha) { if (alpha == 0) { return color; } float a = 1 - alpha / 255f; int red = color >> 16 & 0xff; int green = color >> 8 & 0xff; int blue = color & 0xff; red = (int) (red * a + 0.5); green = (int) (green * a + 0.5); blue = (int) (blue * a + 0.5); return 0xff << 24 | red << 16 | green << 8 | blue; } }
GitHubAFeng/AFengAndroid
app/src/main/java/com/afeng/xf/utils/AFengUtils/StatusBarUtil.java
Java
apache-2.0
28,369
package com.fiberlink.ninjaparser.output; public class StdOut implements Output{ public void print() { } }
anandaverma/NinjaParser
src/com/fiberlink/ninjaparser/output/StdOut.java
Java
apache-2.0
123
/* * Copyright (C) 2012-2015 DataStax 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 org.apache.cassandra2.cql.jdbc; import java.sql.Driver; /** * The Class CassandraDriver. */ public class CassandraDriver extends com.github.adejanovski.cassandra.jdbc.CassandraDriver implements Driver {}
adejanovski/cassandra-jdbc-wrapper
src/main/java/org/apache/cassandra2/cql/jdbc/CassandraDriver.java
Java
apache-2.0
844
"""Reverse complement reads with Seqtk.""" import os from plumbum import TEE from resolwe.process import ( Cmd, DataField, FileField, FileHtmlField, ListField, Process, StringField, ) class ReverseComplementSingle(Process): """Reverse complement single-end FASTQ reads file using Seqtk.""" slug = "seqtk-rev-complement-single" process_type = "data:reads:fastq:single:seqtk" name = "Reverse complement FASTQ (single-end)" requirements = { "expression-engine": "jinja", "executor": { "docker": {"image": "public.ecr.aws/s4q6j6e8/resolwebio/common:3.0.0"}, }, "resources": { "cores": 1, "memory": 16384, }, } entity = { "type": "sample", } data_name = '{{ reads|sample_name|default("?") }}' version = "1.2.0" class Input: """Input fields to process ReverseComplementSingle.""" reads = DataField("reads:fastq:single", label="Reads") class Output: """Output fields.""" fastq = ListField(FileField(), label="Reverse complemented FASTQ file") fastqc_url = ListField(FileHtmlField(), label="Quality control with FastQC") fastqc_archive = ListField(FileField(), label="Download FastQC archive") def run(self, inputs, outputs): """Run the analysis.""" basename = os.path.basename(inputs.reads.output.fastq[0].path) assert basename.endswith(".fastq.gz") name = basename[:-9] complemented_name = f"{name}_complemented.fastq" # Concatenate multilane reads ( Cmd["cat"][[reads.path for reads in inputs.reads.output.fastq]] > "input_reads.fastq.gz" )() # Reverse complement reads (Cmd["seqtk"]["seq", "-r", "input_reads.fastq.gz"] > complemented_name)() _, _, stderr = ( Cmd["fastqc"][complemented_name, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr or "Skipping" in stderr: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_name])() outputs.fastq = [f"{complemented_name}.gz"] outputs.fastqc_url = [f"{name}_complemented_fastqc.html"] outputs.fastqc_archive = [f"{name}_complemented_fastqc.zip"] class ReverseComplementPaired(Process): """Reverse complement paired-end FASTQ reads file using Seqtk.""" slug = "seqtk-rev-complement-paired" process_type = "data:reads:fastq:paired:seqtk" name = "Reverse complement FASTQ (paired-end)" requirements = { "expression-engine": "jinja", "executor": { "docker": {"image": "public.ecr.aws/s4q6j6e8/resolwebio/common:3.0.0"}, }, "resources": { "cores": 1, "memory": 16384, }, } entity = { "type": "sample", } data_name = '{{ reads|sample_name|default("?") }}' version = "1.1.0" class Input: """Input fields to process ReverseComplementPaired.""" reads = DataField("reads:fastq:paired", label="Reads") select_mate = StringField( label="Select mate", description="Select the which mate should be reverse complemented.", choices=[("Mate 1", "Mate 1"), ("Mate 2", "Mate 2"), ("Both", "Both")], default="Mate 1", ) class Output: """Output fields.""" fastq = ListField(FileField(), label="Reverse complemented FASTQ file") fastq2 = ListField(FileField(), label="Remaining mate") fastqc_url = ListField( FileHtmlField(), label="Quality control with FastQC (Mate 1)" ) fastqc_archive = ListField( FileField(), label="Download FastQC archive (Mate 1)" ) fastqc_url2 = ListField( FileHtmlField(), label="Quality control with FastQC (Mate 2)" ) fastqc_archive2 = ListField( FileField(), label="Download FastQC archive (Mate 2)" ) def run(self, inputs, outputs): """Run the analysis.""" basename_mate1 = os.path.basename(inputs.reads.output.fastq[0].path) basename_mate2 = os.path.basename(inputs.reads.output.fastq2[0].path) assert basename_mate1.endswith(".fastq.gz") assert basename_mate2.endswith(".fastq.gz") name_mate1 = basename_mate1[:-9] name_mate2 = basename_mate2[:-9] original_mate1 = f"{name_mate1}_original.fastq.gz" original_mate2 = f"{name_mate2}_original.fastq.gz" ( Cmd["cat"][[reads.path for reads in inputs.reads.output.fastq]] > original_mate1 )() ( Cmd["cat"][[reads.path for reads in inputs.reads.output.fastq2]] > original_mate2 )() if inputs.select_mate == "Mate 1": complemented_mate1 = f"{name_mate1}_complemented.fastq" (Cmd["seqtk"]["seq", "-r", original_mate1] > complemented_mate1)() _, _, stderr = ( Cmd["fastqc"][complemented_mate1, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr or "Skipping" in stderr: self.error("Failed while processing with FastQC.") _, _, stderr2 = ( Cmd["fastqc"][original_mate2, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr2 or "Skipping" in stderr2: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_mate1])() outputs.fastq = [f"{complemented_mate1}.gz"] outputs.fastq2 = [original_mate2] outputs.fastqc_url = [f"{name_mate1}_complemented_fastqc.html"] outputs.fastqc_archive = [f"{name_mate1}_complemented_fastqc.zip"] outputs.fastqc_url2 = [f"{name_mate2}_original_fastqc.html"] outputs.fastqc_archive2 = [f"{name_mate2}_original_fastqc.zip"] elif inputs.select_mate == "Mate 2": complemented_mate2 = f"{name_mate2}_complemented.fastq" ( Cmd["seqtk"]["seq", "-r", f"{name_mate2}_original.fastq.gz"] > complemented_mate2 )() _, _, stderr = ( Cmd["fastqc"][original_mate1, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr or "Skipping" in stderr: self.error("Failed while processing with FastQC.") _, _, stderr2 = ( Cmd["fastqc"][complemented_mate2, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr2 or "Skipping" in stderr2: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_mate2])() outputs.fastq = [original_mate1] outputs.fastq2 = [f"{complemented_mate2}.gz"] outputs.fastqc_url = [f"{name_mate1}_original_fastqc.html"] outputs.fastqc_archive = [f"{name_mate1}_original_fastqc.zip"] outputs.fastqc_url2 = [f"{name_mate2}_complemented_fastqc.html"] outputs.fastqc_archive2 = [f"{name_mate2}_complemented_fastqc.zip"] else: complemented_mate1 = f"{name_mate1}_complemented.fastq" complemented_mate2 = f"{name_mate2}_complemented.fastq" ( Cmd["seqtk"]["seq", "-r", f"{name_mate1}_original.fastq.gz"] > complemented_mate1 )() _, _, stderr = ( Cmd["fastqc"][complemented_mate1, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr or "Skipping" in stderr: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_mate1])() ( Cmd["seqtk"]["seq", "-r", f"{name_mate2}_original.fastq.gz"] > complemented_mate2 )() _, _, stderr2 = ( Cmd["fastqc"][complemented_mate2, "--extract", "--outdir=./"] & TEE ) if "Failed to process" in stderr2 or "Skipping" in stderr2: self.error("Failed while processing with FastQC.") (Cmd["gzip"][complemented_mate2])() outputs.fastq = [f"{complemented_mate1}.gz"] outputs.fastq2 = [f"{complemented_mate2}.gz"] outputs.fastqc_url = [f"{name_mate1}_complemented_fastqc.html"] outputs.fastqc_archive = [f"{name_mate1}_complemented_fastqc.zip"] outputs.fastqc_url2 = [f"{name_mate2}_complemented_fastqc.html"] outputs.fastqc_archive2 = [f"{name_mate2}_complemented_fastqc.zip"]
genialis/resolwe-bio
resolwe_bio/processes/support_processors/seqtk_reverse_complement.py
Python
apache-2.0
8,764
"""TcEx Framework Service Common module""" # standard library import json import threading import time import traceback import uuid from datetime import datetime from typing import Callable, Optional, Union from .mqtt_message_broker import MqttMessageBroker class CommonService: """TcEx Framework Service Common module Shared service logic between the supported service types: * API Service * Custom Trigger Service * Webhook Trigger Service """ def __init__(self, tcex: object): """Initialize the Class properties. Args: tcex: Instance of TcEx. """ self.tcex = tcex # properties self._ready = False self._start_time = datetime.now() self.args: object = tcex.default_args self.configs = {} self.heartbeat_max_misses = 3 self.heartbeat_sleep_time = 1 self.heartbeat_watchdog = 0 self.ij = tcex.ij self.key_value_store = self.tcex.key_value_store self.log = tcex.log self.logger = tcex.logger self.message_broker = MqttMessageBroker( broker_host=self.args.tc_svc_broker_host, broker_port=self.args.tc_svc_broker_port, broker_timeout=self.args.tc_svc_broker_conn_timeout, broker_token=self.args.tc_svc_broker_token, broker_cacert=self.args.tc_svc_broker_cacert_file, logger=tcex.log, ) self.ready = False self.redis_client = self.tcex.redis_client self.token = tcex.token # config callbacks self.shutdown_callback = None def _create_logging_handler(self): """Create a logging handler.""" if self.logger.handler_exist(self.thread_name): return # create trigger id logging filehandler self.logger.add_pattern_file_handler( name=self.thread_name, filename=f'''{datetime.today().strftime('%Y%m%d')}/{self.session_id}.log''', level=self.args.tc_log_level, path=self.args.tc_log_path, # uuid4 pattern for session_id pattern=r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}.log$', handler_key=self.session_id, thread_key='session_id', ) def add_metric(self, label: str, value: Union[int, str]) -> None: """Add a metric. Metrics are reported in heartbeat message. Args: label: The metric label (e.g., hits) to add. value: The value for the metric. """ self._metrics[label] = value @property def command_map(self) -> dict: """Return the command map for the current Service type.""" return { 'heartbeat': self.process_heartbeat_command, 'loggingchange': self.process_logging_change_command, 'shutdown': self.process_shutdown_command, } @staticmethod def create_session_id() -> str: # pylint: disable=unused-argument """Return a uuid4 session id. Returns: str: A unique UUID string value. """ return str(uuid.uuid4()) def heartbeat(self) -> None: """Start heartbeat process.""" self.service_thread(name='heartbeat', target=self.heartbeat_monitor) def heartbeat_monitor(self) -> None: """Publish heartbeat on timer.""" self.log.info('feature=service, event=heartbeat-monitor-started') while True: if self.heartbeat_watchdog > ( int(self.args.tc_svc_hb_timeout_seconds) / int(self.heartbeat_sleep_time) ): self.log.error( 'feature=service, event=missed-heartbeat, action=shutting-service-down' ) self.process_shutdown_command({'reason': 'Missed heartbeat commands.'}) break time.sleep(self.heartbeat_sleep_time) self.heartbeat_watchdog += 1 def increment_metric(self, label: str, value: Optional[int] = 1) -> None: """Increment a metric if already exists. Args: label: The metric label (e.g., hits) to increment. value: The increment value. Defaults to 1. """ if self._metrics.get(label) is not None: self._metrics[label] += value def listen(self) -> None: """List for message coming from broker.""" self.message_broker.add_on_connect_callback(self.on_connect_handler) self.message_broker.add_on_message_callback( self.on_message_handler, topics=[self.args.tc_svc_server_topic] ) self.message_broker.register_callbacks() # start listener thread self.service_thread(name='broker-listener', target=self.message_broker.connect) def loop_forever(self, sleep: Optional[int] = 1) -> bool: """Block and wait for shutdown. Args: sleep: The amount of time to sleep between iterations. Defaults to 1. Returns: Bool: Returns True until shutdown received. """ while True: deadline = time.time() + sleep while time.time() < deadline: if self.message_broker.shutdown: return False time.sleep(1) return True @property def metrics(self) -> dict: """Return current metrics.""" # TODO: move to trigger command and handle API Service if self._metrics.get('Active Playbooks') is not None: self.update_metric('Active Playbooks', len(self.configs)) return self._metrics @metrics.setter def metrics(self, metrics: dict): """Return current metrics.""" if isinstance(metrics, dict): self._metrics = metrics else: self.log.error('feature=service, event=invalid-metrics') def on_connect_handler( self, client, userdata, flags, rc # pylint: disable=unused-argument ) -> None: """On connect method for mqtt broker.""" self.log.info( f'feature=service, event=topic-subscription, topic={self.args.tc_svc_server_topic}' ) self.message_broker.client.subscribe(self.args.tc_svc_server_topic) self.message_broker.client.disable_logger() def on_message_handler( self, client, userdata, message # pylint: disable=unused-argument ) -> None: """On message for mqtt.""" try: # messages on server topic must be json objects m = json.loads(message.payload) except ValueError: self.log.warning( f'feature=service, event=parsing-issue, message="""{message.payload}"""' ) return # use the command to call the appropriate method defined in command_map command: str = m.get('command', 'invalid').lower() trigger_id: Optional[int] = m.get('triggerId') if trigger_id is not None: # coerce trigger_id to int in case a string was provided (testing framework) trigger_id = int(trigger_id) self.log.info(f'feature=service, event=command-received, command="{command}"') # create unique session id to be used as thread name # and stored as property of thread for logging emit session_id = self.create_session_id() # get the target method from command_map for the current command thread_method = self.command_map.get(command, self.process_invalid_command) self.service_thread( # use session_id as thread name to provide easy debugging per thread name=session_id, target=thread_method, args=(m,), session_id=session_id, trigger_id=trigger_id, ) def process_heartbeat_command(self, message: dict) -> None: # pylint: disable=unused-argument """Process the HeartBeat command. .. code-block:: python :linenos: :lineno-start: 1 { "command": "Heartbeat", "metric": {}, "memoryPercent": 0, "cpuPercent": 0 } Args: message: The message payload from the server topic. """ self.heartbeat_watchdog = 0 # send heartbeat -acknowledge- command response = {'command': 'Heartbeat', 'metric': self.metrics} self.message_broker.publish( message=json.dumps(response), topic=self.args.tc_svc_client_topic ) self.log.info(f'feature=service, event=heartbeat-sent, metrics={self.metrics}') def process_logging_change_command(self, message: dict) -> None: """Process the LoggingChange command. .. code-block:: python :linenos: :lineno-start: 1 { "command": "LoggingChange", "level": "DEBUG" } Args: message: The message payload from the server topic. """ level: str = message.get('level') self.log.info(f'feature=service, event=logging-change, level={level}') self.logger.update_handler_level(level) def process_invalid_command(self, message: dict) -> None: """Process all invalid commands. Args: message: The message payload from the server topic. """ self.log.warning( f'feature=service, event=invalid-command-received, message="""({message})""".' ) def process_shutdown_command(self, message: dict) -> None: """Implement parent method to process the shutdown command. .. code-block:: python :linenos: :lineno-start: 1 { "command": "Shutdown", "reason": "Service disabled by user." } Args: message: The message payload from the server topic. """ reason = message.get('reason') or ( 'A shutdown command was received on server topic. Service is shutting down.' ) self.log.info(f'feature=service, event=shutdown, reason={reason}') # acknowledge shutdown command self.message_broker.publish( json.dumps({'command': 'Acknowledged', 'type': 'Shutdown'}), self.args.tc_svc_client_topic, ) # call App shutdown callback if callable(self.shutdown_callback): try: # call callback for shutdown and handle exceptions to protect thread self.shutdown_callback() # pylint: disable=not-callable except Exception as e: self.log.error( f'feature=service, event=shutdown-callback-error, error="""({e})""".' ) self.log.trace(traceback.format_exc()) # unsubscribe and disconnect from the broker self.message_broker.client.unsubscribe(self.args.tc_svc_server_topic) self.message_broker.client.disconnect() # update shutdown flag self.message_broker.shutdown = True # delay shutdown to give App time to cleanup time.sleep(5) self.tcex.exit(0) # final shutdown in case App did not @property def ready(self) -> bool: """Return ready boolean.""" return self._ready @ready.setter def ready(self, bool_val: bool): """Set ready boolean.""" if isinstance(bool_val, bool) and bool_val is True: # wait until connected to send ready command while not self.message_broker._connected: if self.message_broker.shutdown: break time.sleep(1) else: # pylint: disable=useless-else-on-loop self.log.info('feature=service, event=service-ready') ready_command = {'command': 'Ready'} if self.ij.runtime_level.lower() in ['apiservice']: ready_command['discoveryTypes'] = self.ij.service_discovery_types self.message_broker.publish( json.dumps(ready_command), self.args.tc_svc_client_topic ) self._ready = True def service_thread( self, name: str, target: Callable[[], bool], args: Optional[tuple] = None, kwargs: Optional[dict] = None, session_id: Optional[str] = None, trigger_id: Optional[int] = None, ) -> None: """Start a message thread. Args: name: The name of the thread. target: The method to call for the thread. args: The args to pass to the target method. kwargs: Additional args. session_id: The current session id. trigger_id: The current trigger id. """ self.log.info(f'feature=service, event=service-thread-creation, name={name}') args = args or () try: t = threading.Thread(name=name, target=target, args=args, kwargs=kwargs, daemon=True) # add session_id to thread to use in logger emit t.session_id = session_id # add trigger_id to thread to use in logger emit t.trigger_id = trigger_id t.start() except Exception: self.log.trace(traceback.format_exc()) @property def session_id(self) -> Optional[str]: """Return the current session_id.""" if not hasattr(threading.current_thread(), 'session_id'): threading.current_thread().session_id = self.create_session_id() return threading.current_thread().session_id @property def thread_name(self) -> str: """Return a uuid4 session id.""" return threading.current_thread().name @property def trigger_id(self) -> Optional[int]: """Return the current trigger_id.""" trigger_id = None if hasattr(threading.current_thread(), 'trigger_id'): trigger_id = threading.current_thread().trigger_id if trigger_id is not None: trigger_id = int(trigger_id) return trigger_id def update_metric(self, label: str, value: Union[int, str]) -> None: """Update a metric if already exists. Args: label: The metric label (e.g., hits) to update. value: The updated value for the metric. """ if self._metrics.get(label) is not None: self._metrics[label] = value
kstilwell/tcex
tcex/services/common_service.py
Python
apache-2.0
14,584
package whelk.gui; import whelk.ScriptGenerator; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; class ReplaceRecordsPanel extends WizardCard implements ActionListener { final Wizard window; private final JFileChooser chooser = new JFileChooser(); private File chosenFile; private final JTextField chosenFileField; public ReplaceRecordsPanel(Wizard wizard) { super(wizard); window = wizard; chooser.setPreferredSize(new Dimension(1024, 768)); Box vbox = Box.createVerticalBox(); vbox.add(new JLabel("<html>Vรคnligen vรคlj en fil med par av XL-IDn (EJ KONTROLLNUMMER!).<br/>" + "<br/>Filen mรฅste innehรฅlla tvรฅ IDn per rad, separerade av ett mellanslag." + "<br/>Det fรถrsta IDt pรฅ varje rad ersรคtter det andra IDt pรฅ samma rad." + "<br/><br/>Exempel:" + "<br/>vd6njp162pcr3zd c9ps03vw0cpqgx6" + "<br/>jvtbf1w0g7jhgttx fcrtxkcz4dxttr5" + "<br/><br/>Tolkas som:" + "<br/>c9ps03vw0cpqgx6 ersรคtts av vd6njp162pcr3zd." + "<br/>fcrtxkcz4dxttr5 ersรคtts av jvtbf1w0g7jhgttx." + "</html>")); vbox.add(Box.createVerticalStrut(10)); JButton chooseFileButton = new JButton("Vรคlj fil"); chooseFileButton.setActionCommand("open"); chooseFileButton.addActionListener(this); vbox.add(chooseFileButton); vbox.add(Box.createVerticalStrut(10)); chosenFileField = new JTextField(); chosenFileField.setEditable(false); vbox.add(chosenFileField); vbox.add(Box.createVerticalStrut(10)); add(vbox); } @Override protected void beforeNext() { Set<String> ids = new HashSet<>(); try (BufferedReader reader = new BufferedReader(new FileReader(chosenFile))) { for (String line; (line = reader.readLine()) != null; ) { ids.add(line); } } catch (Throwable e) { Wizard.exitFatal(e); } try { setParameterForNextCard(ScriptGenerator.generateReplaceRecordsScript(ids)); } catch (IOException ioe) { Wizard.exitFatal(ioe); } } @Override void onShow(Object parameterFromPreviousCard) { setNextCard(Wizard.RUN); chosenFile = null; disableNext(); } @Override public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getActionCommand().equals("open")) { int returnVal = chooser.showOpenDialog(window); if(returnVal == JFileChooser.APPROVE_OPTION) { chosenFile = chooser.getSelectedFile(); chosenFileField.setText( chooser.getSelectedFile().getName() ); enableNext(); } } } }
libris/librisxl
gui-whelktool/src/main/java/whelk/gui/ReplaceRecordsPanel.java
Java
apache-2.0
3,153
๏ปฟusing System; using System.Threading; using bytePassion.Lib.Communication.State; using bytePassion.Lib.ConcurrencyLib; using OQF.AnalysisAndProgress.ProgressUtils; using OQF.Bot.Contracts; using OQF.Bot.Contracts.Coordination; using OQF.Bot.Contracts.GameElements; using OQF.Bot.Contracts.Moves; using OQF.PlayerVsBot.Contracts; using OQF.Utils.Enum; namespace OQF.PlayerVsBot.GameLogic { public class GameService : IGameService { private readonly bool disableBotTimeout; private readonly ISharedStateWriteOnly<bool> isBoardRotatedVariable; public event Action<BoardState> NewBoardStateAvailable; public event Action<string> NewDebugMsgAvailable; public event Action<Player, WinningReason, Move> WinnerAvailable; public event Action<GameStatus> NewGameStatusAvailable; private TimeoutBlockingQueue<Move> humenMoves; private IGameLoopThread gameLoopThread; private IQuoridorBot quoridorBot; private BoardState currentBoardState; private GameStatus currentGameStatus; public GameService(bool disableBotTimeout, ISharedStateWriteOnly<bool> isBoardRotatedVariable) { this.disableBotTimeout = disableBotTimeout; this.isBoardRotatedVariable = isBoardRotatedVariable; CurrentBoardState = null; gameLoopThread = null; CurrentGameStatus = GameStatus.Unloaded; } public BoardState CurrentBoardState { get { return currentBoardState; } private set { if (value != currentBoardState) { currentBoardState = value; NewBoardStateAvailable?.Invoke(currentBoardState); } } } public GameStatus CurrentGameStatus { get { return currentGameStatus; } private set { if (currentGameStatus != value) { currentGameStatus = value; NewGameStatusAvailable?.Invoke(currentGameStatus); } } } public PlayerType HumanPlayerPosition { get; private set; } public void CreateGame(IQuoridorBot uninitializedBot, string botName, GameConstraints gameConstraints, PlayerType startingPosition, QProgress initialProgress) { HumanPlayerPosition = startingPosition; isBoardRotatedVariable.Value = startingPosition == PlayerType.TopPlayer; if (gameLoopThread != null) { StopGame(); } var finalGameConstraints = disableBotTimeout ? new GameConstraints(Timeout.InfiniteTimeSpan,gameConstraints.MaximalMovesPerPlayer) : gameConstraints; quoridorBot = uninitializedBot; quoridorBot.DebugMessageAvailable += OnDebugMessageAvailable; humenMoves = new TimeoutBlockingQueue<Move>(200); gameLoopThread = startingPosition == PlayerType.BottomPlayer ? (IGameLoopThread) new GameLoopThreadPvB(quoridorBot, botName, humenMoves, finalGameConstraints, initialProgress) : (IGameLoopThread) new GameLoopThreadBvP(quoridorBot, botName, humenMoves, finalGameConstraints, initialProgress); gameLoopThread.NewBoardStateAvailable += OnNewBoardStateAvailable; gameLoopThread.WinnerAvailable += OnWinnerAvailable; CurrentGameStatus = GameStatus.Active; new Thread(gameLoopThread.Run).Start(); } private void OnWinnerAvailable(Player player, WinningReason winningReason, Move invalidMove) { WinnerAvailable?.Invoke(player, winningReason, invalidMove); CurrentGameStatus = GameStatus.Finished; } private void OnNewBoardStateAvailable (BoardState boardState) { CurrentBoardState = boardState; } private void OnDebugMessageAvailable(string s) { NewDebugMsgAvailable?.Invoke(s); } public void ReportHumanMove(Move move) { humenMoves.Put(move); } public void StopGame() { if (gameLoopThread != null) { quoridorBot.DebugMessageAvailable -= OnDebugMessageAvailable; gameLoopThread.Stop(); gameLoopThread.NewBoardStateAvailable -= OnNewBoardStateAvailable; gameLoopThread.WinnerAvailable -= OnWinnerAvailable; gameLoopThread = null; CurrentBoardState = null; } CurrentGameStatus = GameStatus.Unloaded; } } }
bytePassion/OpenQuoridorFramework
OpenQuoridorFramework/OQF.PlayerVsBot.GameLogic/GameService.cs
C#
apache-2.0
4,020
/* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cd.go.contrib.elasticagents.docker.requests; import cd.go.contrib.elasticagents.docker.*; import cd.go.contrib.elasticagents.docker.executors.JobCompletionRequestExecutor; import cd.go.contrib.elasticagents.docker.models.JobIdentifier; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Map; public class JobCompletionRequest { private static final Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); @Expose @SerializedName("elastic_agent_id") private String elasticAgentId; @Expose @SerializedName("job_identifier") private JobIdentifier jobIdentifier; @Expose @SerializedName("elastic_agent_profile_properties") private Map<String, String> properties; @Expose @SerializedName("cluster_profile_properties") private ClusterProfileProperties clusterProfileProperties; public JobCompletionRequest() { } public JobCompletionRequest(String elasticAgentId, JobIdentifier jobIdentifier, Map<String, String> properties, Map<String, String> clusterProfile) { this.elasticAgentId = elasticAgentId; this.jobIdentifier = jobIdentifier; this.properties = properties; this.clusterProfileProperties = ClusterProfileProperties.fromConfiguration(clusterProfile); } public JobCompletionRequest(String elasticAgentId, JobIdentifier jobIdentifier, Map<String, String> properties, ClusterProfileProperties clusterProfileProperties) { this.elasticAgentId = elasticAgentId; this.jobIdentifier = jobIdentifier; this.properties = properties; this.clusterProfileProperties = clusterProfileProperties; } public static JobCompletionRequest fromJSON(String json) { JobCompletionRequest jobCompletionRequest = GSON.fromJson(json, JobCompletionRequest.class); return jobCompletionRequest; } public String getElasticAgentId() { return elasticAgentId; } public JobIdentifier jobIdentifier() { return jobIdentifier; } public ClusterProfileProperties getClusterProfileProperties() { return clusterProfileProperties; } public Map<String, String> getProperties() { return properties; } public RequestExecutor executor(AgentInstances<DockerContainer> agentInstances, PluginRequest pluginRequest) { return new JobCompletionRequestExecutor(this, agentInstances, pluginRequest); } @Override public String toString() { return "JobCompletionRequest{" + "elasticAgentId='" + elasticAgentId + '\'' + ", jobIdentifier=" + jobIdentifier + ", properties=" + properties + ", clusterProfileProperties=" + clusterProfileProperties + '}'; } }
gocd-contrib/docker-elastic-agents
src/main/java/cd/go/contrib/elasticagents/docker/requests/JobCompletionRequest.java
Java
apache-2.0
3,654
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1/metadata_service.proto package com.google.cloud.aiplatform.v1; public interface DeleteContextRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1.DeleteContextRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The resource name of the Context to delete. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/contexts/{context}` * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ java.lang.String getName(); /** * * * <pre> * Required. The resource name of the Context to delete. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/contexts/{context}` * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * * * <pre> * The force deletion semantics is still undefined. * Users should not use this field. * </pre> * * <code>bool force = 2;</code> * * @return The force. */ boolean getForce(); /** * * * <pre> * Optional. The etag of the Context to delete. * If this is provided, it must match the server's etag. Otherwise, the * request will fail with a FAILED_PRECONDITION. * </pre> * * <code>string etag = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The etag. */ java.lang.String getEtag(); /** * * * <pre> * Optional. The etag of the Context to delete. * If this is provided, it must match the server's etag. Otherwise, the * request will fail with a FAILED_PRECONDITION. * </pre> * * <code>string etag = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for etag. */ com.google.protobuf.ByteString getEtagBytes(); }
googleapis/java-aiplatform
proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/DeleteContextRequestOrBuilder.java
Java
apache-2.0
2,785
# Copyright (c) 2014 Rackspace, 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. """ Some useful getters for thread local request style validation. """ def pecan_getter(parm): """pecan getter.""" pecan_module = __import__('pecan', globals(), locals(), ['request']) return getattr(pecan_module, 'request')
obulpathi/poppy
poppy/transport/validators/stoplight/helpers.py
Python
apache-2.0
823
""" * Copyright 2007 Fred Sauer * * 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 AbstractLocation """* * A position represented by a left (x) and top (y) coordinate. """ class CoordinateLocation(AbstractLocation): def __init__(self, left, top): self.left = left self.top = top """ * (non-Javadoc) * * @see com.allen_sauer.gwt.dnd.client.util.Location#getLeft() """ def getLeft(self): return left """ * (non-Javadoc) * * @see com.allen_sauer.gwt.dnd.client.util.Location#getTop() """ def getTop(self): return top
jaredly/pyjamas
library/pyjamas/dnd/util/CoordinateLocation.py
Python
apache-2.0
1,133
๏ปฟnamespace TreeConstructionFromQuartets.Model { using System; using System.Collections.Generic; using System.Linq; public class PartitionSet { public PartitionSet(string PartitionSetName) { this._PartitionSetName = PartitionSetName; this._Final_Score = 0; this._IsolatedCount = 0; this._ViotatedCount = 0; this._SatisfiedCount = 0; this._DifferedCount = 0; this._taxValueForGainCalculation = string.Empty; this._Gain = 0; this.PartitionList = new List<Partition>(); this._ListQuatrets = new List<Quartet>(); } public PartitionSet(string PartitionSetName, int _Final_Score, int _IsolatedCount, int _ViotatedCount, int _SatisfiedCount, int _DifferedCount, string _taxValueForGainCalculation, int _Gain, List<Partition> PartitionList, List<Quartet> _ListQuatrets) { this._PartitionSetName = PartitionSetName; this._Final_Score = _Final_Score; this._IsolatedCount = _IsolatedCount; this._ViotatedCount = _ViotatedCount; this._SatisfiedCount = _SatisfiedCount; this._DifferedCount = _DifferedCount; this._taxValueForGainCalculation = _taxValueForGainCalculation; this._Gain = _Gain; this.PartitionList = new List<Partition>(PartitionList.Select(x => new Partition(x._PartitionName) { _PartitionName = x._PartitionName, TaxaList = new List<Taxa>(x.TaxaList.Select(m => new Taxa() { _Taxa_Value = m._Taxa_Value, _Quartet_Name = m._Quartet_Name, _Taxa_ValuePosition_In_Quartet = m._Taxa_ValuePosition_In_Quartet, _Gain = m._Gain, _CumulativeGain = m._CumulativeGain, IsFreeze = m.IsFreeze, _IsolatedCount = m._IsolatedCount, _ViotatedCount = m._ViotatedCount, _DifferedCount = m._DifferedCount, _SatisfiedCount = m._SatisfiedCount, _TaxaPartitionSet = m._TaxaPartitionSet != null ? new PartitionSet(m._TaxaPartitionSet._PartitionSetName, m._TaxaPartitionSet._Final_Score, m._TaxaPartitionSet._IsolatedCount, m._TaxaPartitionSet._ViotatedCount, m._TaxaPartitionSet._SatisfiedCount, m._TaxaPartitionSet._DifferedCount, m._TaxaPartitionSet._taxValueForGainCalculation, m._TaxaPartitionSet._Gain, m._TaxaPartitionSet.PartitionList, m._TaxaPartitionSet._ListQuatrets) : null, StepK = m.StepK })) })); this._ListQuatrets = new List<Quartet>(_ListQuatrets.Select(x => new Quartet() { _First_Taxa_Value = x._First_Taxa_Value, _Second_Taxa_Value = x._Second_Taxa_Value, _Third_Taxa_Value = x._Third_Taxa_Value, _Fourth_Taxa_Value = x._Fourth_Taxa_Value, _Quartet_Name = x._Quartet_Name, _Quartet_Input = x._Quartet_Input, _Quartet_LeftPart = x._Quartet_LeftPart, _Quartet_LeftPartReverse = x._Quartet_LeftPartReverse, _Quartet_RightPart = x._Quartet_RightPart, _Quartet_RightPartReverse = x._Quartet_RightPartReverse, _isDistinct = x._isDistinct, _Frequency = x._Frequency, _DuplicateQuatrets = x._DuplicateQuatrets, _PartitionStatus = x._PartitionStatus, _ConsistancyStatus = x._ConsistancyStatus, _TaxaSplitLeft = x._TaxaSplitLeft, _TaxaSplitRight = x._TaxaSplitRight })); } public string _PartitionSetName { get; set; } public string _taxValueForGainCalculation { get; set; } public int _Gain { get; set; } public int _Final_Score { get; set; } public int _IsolatedCount { get; set; } public int _ViotatedCount { get; set; } public int _DifferedCount { get; set; } public int _SatisfiedCount { get; set; } public List<Quartet> _ListQuatrets { get; set; } private List<Partition> _PartitionList = new List<Partition>(); public List<Partition> PartitionList { get { return _PartitionList; } set { _PartitionList = value; } } } }
tanvirehsan/TreeConstructionFromQuartets
TreeConstructionFromQuartets/Model/PartitionSet.cs
C#
apache-2.0
4,522
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module SecuritycenterV1beta1 # Security Command Center API # # Security Command Center API provides access to temporal views of assets and # findings within an organization. # # @example # require 'google/apis/securitycenter_v1beta1' # # Securitycenter = Google::Apis::SecuritycenterV1beta1 # Alias the module # service = Securitycenter::SecurityCommandCenterService.new # # @see https://console.cloud.google.com/apis/api/securitycenter.googleapis.com/overview class SecurityCommandCenterService < Google::Apis::Core::BaseService # @return [String] # API key. Your API key identifies your project and provides you with API access, # quota, and reports. Required unless you provide an OAuth 2.0 token. attr_accessor :key # @return [String] # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. attr_accessor :quota_user def initialize super('https://securitycenter.googleapis.com/', '') @batch_path = 'batch' end # Gets the settings for an organization. # @param [String] name # Required. Name of the organization to get organization settings for. Its # format is "organizations/[organization_id]/organizationSettings". # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_organization_organization_settings(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::OrganizationSettings::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::OrganizationSettings command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates an organization's settings. # @param [String] name # The relative resource name of the settings. See: https://cloud.google.com/apis/ # design/resource_names#relative_resource_name Example: "organizations/` # organization_id`/organizationSettings". # @param [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] organization_settings_object # @param [String] update_mask # The FieldMask to use when updating the settings resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::OrganizationSettings] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_organization_organization_settings(name, organization_settings_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::OrganizationSettings::Representation command.request_object = organization_settings_object command.response_representation = Google::Apis::SecuritycenterV1beta1::OrganizationSettings::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::OrganizationSettings command.params['name'] = name unless name.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Filters an organization's assets and groups them by their specified properties. # @param [String] parent # Required. Name of the organization to groupBy. Its format is "organizations/[ # organization_id]". # @param [Google::Apis::SecuritycenterV1beta1::GroupAssetsRequest] group_assets_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GroupAssetsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GroupAssetsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def group_assets(parent, group_assets_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/assets:group', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GroupAssetsRequest::Representation command.request_object = group_assets_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GroupAssetsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GroupAssetsResponse command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists an organization's assets. # @param [String] parent # Required. Name of the organization assets should belong to. Its format is " # organizations/[organization_id]". # @param [String] compare_duration # When compare_duration is set, the ListAssetResult's "state" attribute is # updated to indicate whether the asset was added, removed, or remained present # during the compare_duration period of time that precedes the read_time. This # is the time between (read_time - compare_duration) and read_time. The state # value is derived based on the presence of the asset at the two points in time. # Intermediate state changes between the two times don't affect the result. For # example, the results aren't affected if the asset is removed and re-created # again. Possible "state" values when compare_duration is specified: * "ADDED": # indicates that the asset was not present before compare_duration, but present # at read_time. * "REMOVED": indicates that the asset was present at the start # of compare_duration, but not present at read_time. * "ACTIVE": indicates that # the asset was present at both the start and the end of the time period defined # by compare_duration and read_time. If compare_duration is not specified, then # the only possible state is "UNUSED", which indicates that the asset is present # at read_time. # @param [String] field_mask # Optional. A field mask to specify the ListAssetsResult fields to be listed in # the response. An empty field mask will list all fields. # @param [String] filter # Expression that defines the filter to apply across assets. The expression is a # list of zero or more restrictions combined via logical operators `AND` and `OR` # . Parentheses are not supported, and `OR` has higher precedence than `AND`. # Restrictions have the form ` ` and may have a `-` character in front of them # to indicate negation. The fields map to those defined in the Asset resource. # Examples include: * name * security_center_properties.resource_name * # resource_properties.a_property * security_marks.marks.marka The supported # operators are: * `=` for all value types. * `>`, `<`, `>=`, `<=` for integer # values. * `:`, meaning substring matching, for strings. The supported value # types are: * string literals in quotes. * integer literals without quotes. * # boolean literals `true` and `false` without quotes. For example, ` # resource_properties.size = 100` is a valid filter string. # @param [String] order_by # Expression that defines what fields and order to use for sorting. The string # value should follow SQL syntax: comma separated list of fields. For example: " # name,resource_properties.a_property". The default sorting order is ascending. # To specify descending order for a field, a suffix " desc" should be appended # to the field name. For example: "name desc,resource_properties.a_property". # Redundant space characters in the syntax are insignificant. "name desc, # resource_properties.a_property" and " name desc , resource_properties. # a_property " are equivalent. # @param [Fixnum] page_size # The maximum number of results to return in a single response. Default is 10, # minimum is 1, maximum is 1000. # @param [String] page_token # The value returned by the last `ListAssetsResponse`; indicates that this is a # continuation of a prior `ListAssets` call, and that the system should return # the next page of data. # @param [String] read_time # Time used as a reference point when filtering assets. The filter is limited to # assets existing at the supplied time and their values are those at that # specific time. Absence of this field will default to the API's version of NOW. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::ListAssetsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::ListAssetsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_organization_assets(parent, compare_duration: nil, field_mask: nil, filter: nil, order_by: nil, page_size: nil, page_token: nil, read_time: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+parent}/assets', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::ListAssetsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::ListAssetsResponse command.params['parent'] = parent unless parent.nil? command.query['compareDuration'] = compare_duration unless compare_duration.nil? command.query['fieldMask'] = field_mask unless field_mask.nil? command.query['filter'] = filter unless filter.nil? command.query['orderBy'] = order_by unless order_by.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['readTime'] = read_time unless read_time.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Runs asset discovery. The discovery is tracked with a long-running operation. # This API can only be called with limited frequency for an organization. If it # is called too frequently the caller will receive a TOO_MANY_REQUESTS error. # @param [String] parent # Required. Name of the organization to run asset discovery for. Its format is " # organizations/[organization_id]". # @param [Google::Apis::SecuritycenterV1beta1::RunAssetDiscoveryRequest] run_asset_discovery_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def run_organization_asset_discovery(parent, run_asset_discovery_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/assets:runDiscovery', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::RunAssetDiscoveryRequest::Representation command.request_object = run_asset_discovery_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Operation::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Operation command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates security marks. # @param [String] name # The relative resource name of the SecurityMarks. See: https://cloud.google.com/ # apis/design/resource_names#relative_resource_name Examples: "organizations/` # organization_id`/assets/`asset_id`/securityMarks" "organizations/` # organization_id`/sources/`source_id`/findings/`finding_id`/securityMarks". # @param [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] google_cloud_securitycenter_v1beta1_security_marks_object # @param [String] start_time # The time at which the updated SecurityMarks take effect. # @param [String] update_mask # The FieldMask to use when updating the security marks resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_organization_asset_security_marks(name, google_cloud_securitycenter_v1beta1_security_marks_object = nil, start_time: nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks::Representation command.request_object = google_cloud_securitycenter_v1beta1_security_marks_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks command.params['name'] = name unless name.nil? command.query['startTime'] = start_time unless start_time.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Starts asynchronous cancellation on a long-running operation. The server makes # a best effort to cancel the operation, but success is not guaranteed. If the # server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. # Clients can use Operations.GetOperation or other methods to check whether the # cancellation succeeded or whether the operation completed despite cancellation. # On successful cancellation, the operation is not deleted; instead, it becomes # an operation with an Operation.error value with a google.rpc.Status.code of 1, # corresponding to `Code.CANCELLED`. # @param [String] name # The name of the operation resource to be cancelled. # @param [Google::Apis::SecuritycenterV1beta1::CancelOperationRequest] cancel_operation_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Empty] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Empty] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def cancel_operation(name, cancel_operation_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+name}:cancel', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::CancelOperationRequest::Representation command.request_object = cancel_operation_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Empty::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Empty command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Deletes a long-running operation. This method indicates that the client is no # longer interested in the operation result. It does not cancel the operation. # If the server doesn't support this method, it returns `google.rpc.Code. # UNIMPLEMENTED`. # @param [String] name # The name of the operation resource to be deleted. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Empty] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Empty] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def delete_organization_operation(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:delete, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::Empty::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Empty command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the latest state of a long-running operation. Clients can use this method # to poll the operation result at intervals as recommended by the API service. # @param [String] name # The name of the operation resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_organization_operation(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::Operation::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Operation command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists operations that match the specified filter in the request. If the server # doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` # binding allows API services to override the binding to use different resource # name schemes, such as `users/*/operations`. To override the binding, API # services can add a binding such as `"/v1/`name=users/*`/operations"` to their # service configuration. For backwards compatibility, the default name includes # the operations collection id, however overriding users must ensure the name # binding is the parent resource, without the operations collection id. # @param [String] name # The name of the operation's parent resource. # @param [String] filter # The standard list filter. # @param [Fixnum] page_size # The standard list page size. # @param [String] page_token # The standard list page token. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::ListOperationsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::ListOperationsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_organization_operations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::ListOperationsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::ListOperationsResponse command.params['name'] = name unless name.nil? command.query['filter'] = filter unless filter.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Creates a source. # @param [String] parent # Required. Resource name of the new source's parent. Its format should be " # organizations/[organization_id]". # @param [Google::Apis::SecuritycenterV1beta1::Source] source_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Source] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Source] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def create_organization_source(parent, source_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/sources', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.request_object = source_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Source command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets a source. # @param [String] name # Required. Relative resource name of the source. Its format is "organizations/[ # organization_id]/source/[source_id]". # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Source] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Source] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_organization_source(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+name}', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Source command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the access control policy on the specified Source. # @param [String] resource # REQUIRED: The resource for which the policy is being requested. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::SecuritycenterV1beta1::GetIamPolicyRequest] get_iam_policy_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Policy] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Policy] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_source_iam_policy(resource, get_iam_policy_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+resource}:getIamPolicy', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GetIamPolicyRequest::Representation command.request_object = get_iam_policy_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Policy::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Policy command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists all sources belonging to an organization. # @param [String] parent # Required. Resource name of the parent of sources to list. Its format should be # "organizations/[organization_id]". # @param [Fixnum] page_size # The maximum number of results to return in a single response. Default is 10, # minimum is 1, maximum is 1000. # @param [String] page_token # The value returned by the last `ListSourcesResponse`; indicates that this is a # continuation of a prior `ListSources` call, and that the system should return # the next page of data. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::ListSourcesResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::ListSourcesResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_organization_sources(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+parent}/sources', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::ListSourcesResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::ListSourcesResponse command.params['parent'] = parent unless parent.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates a source. # @param [String] name # The relative resource name of this source. See: https://cloud.google.com/apis/ # design/resource_names#relative_resource_name Example: "organizations/` # organization_id`/sources/`source_id`" # @param [Google::Apis::SecuritycenterV1beta1::Source] source_object # @param [String] update_mask # The FieldMask to use when updating the source resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Source] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Source] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def patch_organization_source(name, source_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.request_object = source_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Source::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Source command.params['name'] = name unless name.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Sets the access control policy on the specified Source. # @param [String] resource # REQUIRED: The resource for which the policy is being specified. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::SecuritycenterV1beta1::SetIamPolicyRequest] set_iam_policy_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::Policy] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::Policy] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def set_source_iam_policy(resource, set_iam_policy_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+resource}:setIamPolicy', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::SetIamPolicyRequest::Representation command.request_object = set_iam_policy_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::Policy::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::Policy command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Returns the permissions that a caller has on the specified source. # @param [String] resource # REQUIRED: The resource for which the policy detail is being requested. See the # operation documentation for the appropriate value for this field. # @param [Google::Apis::SecuritycenterV1beta1::TestIamPermissionsRequest] test_iam_permissions_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::TestIamPermissionsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::TestIamPermissionsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def test_source_iam_permissions(resource, test_iam_permissions_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+resource}:testIamPermissions', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::TestIamPermissionsRequest::Representation command.request_object = test_iam_permissions_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::TestIamPermissionsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::TestIamPermissionsResponse command.params['resource'] = resource unless resource.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Creates a finding. The corresponding source must exist for finding creation to # succeed. # @param [String] parent # Required. Resource name of the new finding's parent. Its format should be " # organizations/[organization_id]/sources/[source_id]". # @param [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] google_cloud_securitycenter_v1beta1_finding_object # @param [String] finding_id # Required. Unique identifier provided by the client within the parent scope. It # must be alphanumeric and less than or equal to 32 characters and greater than # 0 characters in length. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def create_organization_source_finding(parent, google_cloud_securitycenter_v1beta1_finding_object = nil, finding_id: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/findings', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.request_object = google_cloud_securitycenter_v1beta1_finding_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding command.params['parent'] = parent unless parent.nil? command.query['findingId'] = finding_id unless finding_id.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Filters an organization or source's findings and groups them by their # specified properties. To group across all sources provide a `-` as the source # id. Example: /v1beta1/organizations/`organization_id`/sources/-/findings # @param [String] parent # Required. Name of the source to groupBy. Its format is "organizations/[ # organization_id]/sources/[source_id]". To groupBy across all sources provide a # source_id of `-`. For example: organizations/`organization_id`/sources/- # @param [Google::Apis::SecuritycenterV1beta1::GroupFindingsRequest] group_findings_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GroupFindingsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GroupFindingsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def group_findings(parent, group_findings_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+parent}/findings:group', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GroupFindingsRequest::Representation command.request_object = group_findings_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GroupFindingsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GroupFindingsResponse command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists an organization or source's findings. To list across all sources provide # a `-` as the source id. Example: /v1beta1/organizations/`organization_id`/ # sources/-/findings # @param [String] parent # Required. Name of the source the findings belong to. Its format is " # organizations/[organization_id]/sources/[source_id]". To list across all # sources provide a source_id of `-`. For example: organizations/` # organization_id`/sources/- # @param [String] field_mask # Optional. A field mask to specify the Finding fields to be listed in the # response. An empty field mask will list all fields. # @param [String] filter # Expression that defines the filter to apply across findings. The expression is # a list of one or more restrictions combined via logical operators `AND` and ` # OR`. Parentheses are not supported, and `OR` has higher precedence than `AND`. # Restrictions have the form ` ` and may have a `-` character in front of them # to indicate negation. Examples include: * name * source_properties.a_property * # security_marks.marks.marka The supported operators are: * `=` for all value # types. * `>`, `<`, `>=`, `<=` for integer values. * `:`, meaning substring # matching, for strings. The supported value types are: * string literals in # quotes. * integer literals without quotes. * boolean literals `true` and ` # false` without quotes. For example, `source_properties.size = 100` is a valid # filter string. # @param [String] order_by # Expression that defines what fields and order to use for sorting. The string # value should follow SQL syntax: comma separated list of fields. For example: " # name,resource_properties.a_property". The default sorting order is ascending. # To specify descending order for a field, a suffix " desc" should be appended # to the field name. For example: "name desc,source_properties.a_property". # Redundant space characters in the syntax are insignificant. "name desc, # source_properties.a_property" and " name desc , source_properties.a_property " # are equivalent. # @param [Fixnum] page_size # The maximum number of results to return in a single response. Default is 10, # minimum is 1, maximum is 1000. # @param [String] page_token # The value returned by the last `ListFindingsResponse`; indicates that this is # a continuation of a prior `ListFindings` call, and that the system should # return the next page of data. # @param [String] read_time # Time used as a reference point when filtering findings. The filter is limited # to findings existing at the supplied time and their values are those at that # specific time. Absence of this field will default to the API's version of NOW. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::ListFindingsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::ListFindingsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_organization_source_findings(parent, field_mask: nil, filter: nil, order_by: nil, page_size: nil, page_token: nil, read_time: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v1beta1/{+parent}/findings', options) command.response_representation = Google::Apis::SecuritycenterV1beta1::ListFindingsResponse::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::ListFindingsResponse command.params['parent'] = parent unless parent.nil? command.query['fieldMask'] = field_mask unless field_mask.nil? command.query['filter'] = filter unless filter.nil? command.query['orderBy'] = order_by unless order_by.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['readTime'] = read_time unless read_time.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Creates or updates a finding. The corresponding source must exist for a # finding creation to succeed. # @param [String] name # The relative resource name of this finding. See: https://cloud.google.com/apis/ # design/resource_names#relative_resource_name Example: "organizations/` # organization_id`/sources/`source_id`/findings/`finding_id`" # @param [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] google_cloud_securitycenter_v1beta1_finding_object # @param [String] update_mask # The FieldMask to use when updating the finding resource. This field should not # be specified when creating a finding. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def patch_organization_source_finding(name, google_cloud_securitycenter_v1beta1_finding_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.request_object = google_cloud_securitycenter_v1beta1_finding_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding command.params['name'] = name unless name.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates the state of a finding. # @param [String] name # Required. The relative resource name of the finding. See: https://cloud.google. # com/apis/design/resource_names#relative_resource_name Example: "organizations/` # organization_id`/sources/`source_id`/finding/`finding_id`". # @param [Google::Apis::SecuritycenterV1beta1::SetFindingStateRequest] set_finding_state_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def set_organization_source_finding_state(name, set_finding_state_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v1beta1/{+name}:setState', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::SetFindingStateRequest::Representation command.request_object = set_finding_state_request_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1Finding command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Updates security marks. # @param [String] name # The relative resource name of the SecurityMarks. See: https://cloud.google.com/ # apis/design/resource_names#relative_resource_name Examples: "organizations/` # organization_id`/assets/`asset_id`/securityMarks" "organizations/` # organization_id`/sources/`source_id`/findings/`finding_id`/securityMarks". # @param [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] google_cloud_securitycenter_v1beta1_security_marks_object # @param [String] start_time # The time at which the updated SecurityMarks take effect. # @param [String] update_mask # The FieldMask to use when updating the security marks resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def update_organization_source_finding_security_marks(name, google_cloud_securitycenter_v1beta1_security_marks_object = nil, start_time: nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:patch, 'v1beta1/{+name}', options) command.request_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks::Representation command.request_object = google_cloud_securitycenter_v1beta1_security_marks_object command.response_representation = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks::Representation command.response_class = Google::Apis::SecuritycenterV1beta1::GoogleCloudSecuritycenterV1beta1SecurityMarks command.params['name'] = name unless name.nil? command.query['startTime'] = start_time unless start_time.nil? command.query['updateMask'] = update_mask unless update_mask.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end protected def apply_command_defaults(command) command.query['key'] = key unless key.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? end end end end end
googleapis/google-api-ruby-client
google-api-client/generated/google/apis/securitycenter_v1beta1/service.rb
Ruby
apache-2.0
66,146
<?php $TRANSLATIONS = array( "Not all calendars are completely cached" => "Ikke alle kalendere er fuldstรฆndig cached", "Everything seems to be completely cached" => "Alt ser ud til at vรฆre cached", "No calendars found." => "Der blev ikke fundet nogen kalendere.", "No events found." => "Der blev ikke fundet nogen begivenheder.", "Wrong calendar" => "Forkert kalender", "You do not have the permissions to edit this event." => "Du har ikke rettigheder til at redigere denne begivenhed.", "The file contained either no events or all events are already saved in your calendar." => "Enten indeholdt filen ingen begivenheder, eller ogsรฅ er alle begivenheder allerede gemt i din kalender.", "events has been saved in the new calendar" => "begivenheder er gemt i den nye kalender", "Import failed" => "Import mislykkedes", "events has been saved in your calendar" => "begivenheder er gemt i din kalender", "New Timezone:" => "Ny tidszone:", "Timezone changed" => "Tidszone รฆndret", "Invalid request" => "Ugyldig forespรธrgsel", "Calendar" => "Kalender", "Deletion failed" => "Fejl ved sletning", "ddd d MMMM[ yyyy]{ - [ddd d] MMMM yyyy}" => "ddd d MMMM[ yyyy]{ - [ddd d] MMMM yyyy}", "ddd d MMMM[ yyyy] HH:mm{ - [ ddd d MMMM yyyy] HH:mm}" => "ddd d MMMM[ yyyy] HH:mm{ - [ ddd d MMMM yyyy] HH:mm}", "group" => "gruppe", "can edit" => "kan redigere", "ddd" => "ddd", "ddd M/d" => "ddd M/d", "dddd M/d" => "dddd M/d", "MMMM yyyy" => "MMMM yyyy", "MMM d[ yyyy]{ 'โ€“'[ MMM] d yyyy}" => "MMM d[ yyyy]{ 'โ€“'[ MMM] d yyyy}", "dddd, MMM d, yyyy" => "dddd, MMM d, yyyy", "Sunday" => "Sรธndag", "Monday" => "Mandag", "Tuesday" => "Tirsdag", "Wednesday" => "Onsdag", "Thursday" => "Torsdag", "Friday" => "Fredag", "Saturday" => "Lรธrdag", "Sun." => "Sรธn.", "Mon." => "Man.", "Tue." => "Tir.", "Wed." => "Ons.", "Thu." => "Tor.", "Fri." => "Fre.", "Sat." => "Lรธr.", "January" => "Januar", "February" => "Februar", "March" => "Marts", "April" => "April", "May" => "Maj", "June" => "Juni", "July" => "Juli", "August" => "August", "September" => "September", "October" => "Oktober", "November" => "November", "December" => "December", "Jan." => "Jan.", "Feb." => "Feb.", "Mar." => "Mar.", "Apr." => "Apr.", "May." => "Maj", "Jun." => "Jun.", "Jul." => "Jul.", "Aug." => "Aug.", "Sep." => "Sep.", "Oct." => "Okt.", "Nov." => "Nov.", "Dec." => "Dec.", "All day" => "Hele dagen", "New Calendar" => "Ny kalender", "Missing or invalid fields" => "Manglende eller ugyldige felter", "Title" => "Titel", "From Date" => "Fra dato", "From Time" => "Fra tidspunkt", "To Date" => "Til dato", "To Time" => "Til tidspunkt", "The event ends before it starts" => "Begivenheden slutter, inden den begynder", "There was a database fail" => "Der var en fejl i databasen", "Birthday" => "Fรธdselsdag", "Business" => "Erhverv", "Call" => "Ring", "Clients" => "Kunder", "Deliverer" => "Leverance", "Holidays" => "Helligdage", "Ideas" => "Ideer", "Journey" => "Rejse", "Jubilee" => "Jubilรฆum", "Meeting" => "Mรธde", "Other" => "Andet", "Personal" => "Privat", "Projects" => "Projekter", "Questions" => "Spรธrgsmรฅl", "Work" => "Arbejde", "by" => "af", "unnamed" => "unavngivet", "You do not have the permissions to update this calendar." => "Du har ikke rettigheder til at opdatere denne kalender.", "You do not have the permissions to delete this calendar." => "Du har ikke rettigheder til at slette denne kalender.", "You do not have the permissions to add to this calendar." => "Du har ikke rettigheder til at tilfรธje til denne kalender.", "You do not have the permissions to add events to this calendar." => "Du har ikke rettigheder til at tilfรธje begivenheder til denne kalender.", "You do not have the permissions to delete this event." => "Du har ikke rettigheder til at slette denne begivenhed.", "Busy" => "Optaget", "Does not repeat" => "Gentages ikke", "Daily" => "Dagligt", "Weekly" => "Ugentligt", "Every Weekday" => "Alle hverdage", "Bi-Weekly" => "Hver anden uge", "Monthly" => "Mรฅnedligt", "Yearly" => "ร…rligt", "never" => "aldrig", "by occurrences" => "efter forekomster", "by date" => "efter dato", "by monthday" => "efter dag i mรฅneden", "by weekday" => "efter ugedag", "events week of month" => "begivenhedens uge i mรฅneden", "first" => "fรธrste", "second" => "anden", "third" => "tredje", "fourth" => "fjerde", "fifth" => "femte", "last" => "sidste", "by events date" => "efter begivenheders dato", "by yearday(s)" => "efter dag(e) i รฅret", "by weeknumber(s)" => "efter ugenummer/-numre", "by day and month" => "efter dag og mรฅned", "Contact birthdays" => "Kontakt fรธdselsdage", "Date" => "Dato", "Cal." => "Kal.", "Day" => "Dag", "Week" => "Uge", "Month" => "Mรฅned", "Today" => "I dag", "Settings" => "Indstillinger", "Share Calendar" => "Del kalender", "CalDav Link" => "CalDav-link", "Download" => "Hent", "Edit" => "Rediger", "Delete" => "Slet", "New calendar" => "Ny kalender", "Edit calendar" => "Rediger kalender", "Displayname" => "Vist navn", "Calendar color" => "Kalenderfarve", "Save" => "Gem", "Submit" => "Send", "Cancel" => "Annuller", "Eventinfo" => "Begivenhedsinfo", "Repeating" => "Gentagende", "Alarm" => "Alarm", "Attendees" => "Deltagere", "Share" => "Del", "Title of the Event" => "Titel pรฅ begivenheden", "from" => "fra", "All Day Event" => "Heldagsarrangement", "Advanced options" => "Avancerede indstillinger", "Location" => "Sted", "Edit categories" => "Rediger kategorier", "Description" => "Beskrivelse", "Repeat" => "Gentag", "Advanced" => "Avanceret", "Select weekdays" => "Vรฆlg ugedage", "Select days" => "Vรฆlg dage", "and the events day of year." => "og begivenhedens dag i รฅret.", "and the events day of month." => "og begivenhedens dag i mรฅneden", "Select months" => "Vรฆlg mรฅneder", "Select weeks" => "Vรฆlg uger", "and the events week of year." => "og begivenhedens uge i รฅret.", "Interval" => "Interval", "End" => "Afslutning", "occurrences" => "forekomster", "create a new calendar" => "opret en ny kalender", "Import a calendar file" => "Importer en kalenderfil", "Please choose a calendar" => "Vรฆlg en kalender", "Name of new calendar" => "Navn pรฅ ny kalender", "Take an available name!" => "Vรฆlg et ledigt navn!", "A Calendar with this name already exists. If you continue anyhow, these calendars will be merged." => "En kalender med dette navn findes allerede. Hvis du fortsรฆtter alligevel, vil disse kalendere blive sammenlagt.", "Remove all events from the selected calendar" => "Fjern alle events fra den valgte kalender", "Import" => "Importer", "Close Dialog" => "Luk dialog", "Create a new event" => "Opret en ny begivenhed", "Unshare" => "Fjern deling", "Send Email" => "Send Email", "Shared via calendar" => "Delt via kalender", "View an event" => "Vis en begivenhed", "Category" => "Kategori", "No categories selected" => "Ingen categorier valgt", "of" => "fra", "Access Class" => "Adgangsklasse", "From" => "Fra", "at" => "kl.", "To" => "Til", "Your calendars" => "Dine kalendere", "General" => "Generel", "Timezone" => "Tidszone", "Update timezone automatically" => "Opdater tidszone automatisk", "Time format" => "Tidsformat", "24h" => "24T", "12h" => "12T", "Start week on" => "Start ugen med", "Cache" => "Cache", "Clear cache for repeating events" => "Ryd cache for gentagende begivenheder", "URLs" => "URLs", "Calendar CalDAV syncing addresses" => "Adresser til kalendersynkronisering over CalDAV", "more info" => "flere oplysninger", "Primary address (Kontact et al)" => "Primรฆr adresse (Kontakt o.a.)", "iOS/OS X" => "iOS/OS X", "Read only iCalendar link(s)" => "Skrivebeskyttet iCalendar-link(s)" );
ArcherCraftStore/ArcherVMPeridot
apps/owncloud/htdocs/apps/calendar/l10n/da.php
PHP
apache-2.0
7,568
#include <iostream> #include <vector> #include <cmath> #include <algorithm> #include <fstream> #include "gflags/gflags.h" #include "Common/log.h" DEFINE_string(res_file, "", "predict res"); DEFINE_int32(log_level, 2, "LogLevel :" "0 : TRACE " "1 : DEBUG " "2 : INFO " "3 : ERROR"); uint32_t log_level = 0; namespace ML { struct Elem { double p; double y; }; bool LessThan(const Elem& a, const Elem& b) { return a.p < b.p; } bool Equal(const Elem& a, const Elem& b) { return fabs(a.p - b.p) < 1.e-10; } void check(const Elem& e, int& n, int& p) { if (e.y < 0.5) { n++; } else { p++; } } double logistic_loss(Elem& e) { if (e.y > 0.5) { return -log(e.p); } else { return -log(1-e.p); } } double auc(std::vector<Elem>& res) { if (res.size() <= 0) { return 0.5; } std::sort(res.begin(), res.end(), LessThan); int n = 0; int p = 0; int cur_n = 0; int cur_p = 0; double correct = 0; check(res[0], cur_n, cur_p); for (size_t i=1; i<res.size(); ++i) { if (Equal(res[i], res[i-1])) { check(res[i], cur_n, cur_p); } else { correct += cur_p*n + 0.5*cur_p*cur_n; p += cur_p; n += cur_n; cur_p = 0; cur_n = 0; check(res[i], cur_n, cur_p); } } correct += cur_p*n + 0.5*cur_p*cur_n; p += cur_p; n += cur_n; LOG_INFO("POSITIVE : %d , NEGATIVE : %d, CORRECT : %lf", p, n, correct); if (n == 0) return 1.0; if (p == 0) return 0.0; return correct*1.0/p/n; } } using namespace ML; int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); log_level = FLAGS_log_level; if (FLAGS_res_file.empty()) { std::cout<< "res file is empty!" << std::endl; return 0; } std::ifstream infile(FLAGS_res_file.c_str()); if (!infile) { LOG_ERROR("Load res file : %s failed!", FLAGS_res_file.c_str()); return 0; } std::string line; std::vector<Elem> res; Elem e; e.p = 0.0; e.y = 1.0; double total_loss = 0; getline(infile, line); while (!infile.eof()) { sscanf(line.c_str(), "%lf %lf", &(e.y), &(e.p)); LOG_TRACE("Elem p : %lf, y : %lf", e.p, e.y); res.push_back(e); total_loss += logistic_loss(e); getline(infile, line); } LOG_TRACE("Res size : %lu", res.size()); printf("[%s]AUC = %.5lf, LOSS = %.3lf\n", FLAGS_res_file.c_str(), auc(res), total_loss); return 0; }
uwroute/study
ML/eval/auc.cpp
C++
apache-2.0
2,402
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Mobet.Runtime.Cookie { public static class CookieManager { /// <summary> /// ๅˆ›ๅปบcookie /// </summary> /// <param name="name">cookieๅ</param> /// <param name="value">cookieๅ€ผ</param> /// <param name="expires">่ฟ‡ๆœŸๆ—ถ้—ด</param> public static void CreateCookie(string name, string value, DateTime expires) { HttpCookie hc = value.Trim() == "" ? new HttpCookie(name) : new HttpCookie(name, value.Trim()); hc.Path = "/"; // ๅฝ“่ฟ‡ๆœŸๆ—ถ้—ดไธบMinValueๆ—ถ๏ผŒไธ่ฎพ็ฝฎcookie็š„่ฟ‡ๆœŸๆ—ถ้—ด๏ผŒไนŸๅฐฑๆ˜ฏ่ฏด๏ผŒๅ…ณ้—ญๆต่งˆๅ™จๅŽcookieๅณ่ฟ‡ๆœŸ if (expires != DateTime.MinValue) { hc.Expires = expires; } HttpContext.Current.Response.Cookies.Set(hc); } /// <summary> /// ๆธ…้™คcookie /// </summary> /// <param name="name">cookieๅ</param> /// <param name="domain">ๅŸŸๅ</param> public static void ClearCookie(string name) { CreateCookie(name, "", DateTime.Now.AddDays(-1)); } /// <summary> /// ่Žทๅ–cookieๅ€ผ /// </summary> /// <param name="name"></param> /// <returns></returns> public static string GetCookieValue(string name) { var cookie = HttpContext.Current.Request.Cookies[name]; if (cookie == null) { return null; } else { return cookie.Value; } } } }
Mobet/Mobet-Net
Mobet-Net/Mobet/Runtime/Cookie/CookieManager.cs
C#
apache-2.0
1,723
<tr> <td><?php echo $area->id ?></td> <td><?php echo $area->lat ?></td> <td><?php echo $area->lng ?></td> <td><?php echo $area->radius ?></td> <td width="300px"><?php echo $area->url ?></td> <td><?php echo $area->area ?></td> <td><?php echo $area->min_radius_area ?></td> <td><?php echo $area->radius_area ?></td> <td> <?php echo link_to('Tแบกo flow','pos/newGoogleFlow?area='.$area->area) ?> | <?php echo link_to('Sแปญa','pos/edit?id='.$area->id) ?> | </td> </tr>
smart-e/lifemap
plugins/lfPosPlugin/apps/pc_backend/modules/pos/templates/_googlearea.php
PHP
apache-2.0
520
package dbutil import ( "github.com/wpxiong/beargo/log" ) func init() { log.InitLog() }
wpxiong/beargo
util/dbutil/db_util.go
GO
apache-2.0
94
import java.util.HashMap; import java.util.Map; public class WordPattern { public static boolean wordPattern(String pattern, String str) { Map<String, String> a2b = new HashMap<String, String>(); Map<String, String> b2a = new HashMap<String, String>(); String[] tokens = str.split(" "); if (tokens.length != pattern.length()) return false; int i = 0; for (String token : tokens) { StringBuilder tmp = new StringBuilder(); tmp.append(pattern.charAt(i)); if (a2b.containsKey(tmp.toString())) { String r = a2b.get(tmp.toString()); if (!r.equals(token)) return false; } else if (b2a.containsKey(token)) { String r = b2a.get(token); if (!r.equals(tmp.toString())) return false; } else { a2b.put(tmp.toString(), token); b2a.put(token, tmp.toString()); } ++i; } return true; } }
wittyResry/leetcode
src/main/java/WordPattern.java
Java
apache-2.0
1,026
package org.aksw.sparqlify.qa.pinpointing; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.aksw.sparqlify.core.algorithms.CandidateViewSelectorImpl; import org.aksw.sparqlify.core.algorithms.ViewQuad; import org.aksw.sparqlify.core.domain.input.ViewDefinition; import org.aksw.sparqlify.database.Clause; import org.aksw.sparqlify.database.NestedNormalForm; import org.aksw.sparqlify.restriction.RestrictionManagerImpl; import org.springframework.stereotype.Component; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.sparql.core.Quad; import com.hp.hpl.jena.sparql.core.Var; import com.hp.hpl.jena.sparql.expr.E_Equals; import com.hp.hpl.jena.sparql.expr.ExprVar; import com.hp.hpl.jena.sparql.expr.NodeValue; @Component public class Pinpointer { // private Collection<ViewDefinition> viewDefs; CandidateViewSelectorImpl candidateSelector; /* * TODO: * - add query method * - add caching */ public void registerViewDefs(Collection<ViewDefinition> viewDefs) { candidateSelector = new CandidateViewSelectorImpl(); for (ViewDefinition viewDef : viewDefs) { candidateSelector.addView(viewDef); } } public Set<ViewQuad<ViewDefinition>> getViewCandidates(Triple triple) { Var g = Var.alloc("g"); Var s = Var.alloc("s"); Var p = Var.alloc("p"); Var o = Var.alloc("o"); Node gv = Quad.defaultGraphNodeGenerated; Node sv = triple.getSubject(); Node pv = triple.getPredicate(); Node ov = triple.getObject(); Quad tmpQuad = new Quad(g, s, p, o); RestrictionManagerImpl r = new RestrictionManagerImpl(); Set<Clause> clauses = new HashSet<Clause>(); clauses.add(new Clause(new E_Equals(new ExprVar(g), NodeValue.makeNode(gv)))); clauses.add(new Clause(new E_Equals(new ExprVar(s), NodeValue.makeNode(sv)))); clauses.add(new Clause(new E_Equals(new ExprVar(p), NodeValue.makeNode(pv)))); clauses.add(new Clause(new E_Equals(new ExprVar(o), NodeValue.makeNode(ov)))); NestedNormalForm nnf = new NestedNormalForm(clauses); r.stateCnf(nnf); Set<ViewQuad<ViewDefinition>> result = candidateSelector.findCandidates(tmpQuad, r); return result; } }
AKSW/R2RLint
src/main/java/org/aksw/sparqlify/qa/pinpointing/Pinpointer.java
Java
apache-2.0
2,208
/* * Copyright 2014 Martin W. Kirst * * 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 CaveatPacket = require('./CaveatPacket'); import CaveatPacketType = require('./CaveatPacketType'); import Macaroon = require('./Macaroon'); import MacaroonsConstants = require('./MacaroonsConstants'); import BufferTools = require('./BufferTools'); import CryptoTools = require('./CryptoTools'); export = MacaroonsVerifier; /** * Used to verify Macaroons */ class MacaroonsVerifier { "use strict"; private predicates:string[] = []; private boundMacaroons:Macaroon[] = []; private generalCaveatVerifiers:GeneralCaveatVerifier[] = []; private macaroon:Macaroon; constructor(macaroon:Macaroon) { this.macaroon = macaroon; } /** * @param secret string this secret will be enhanced, in case it's shorter than {@link MacaroonsConstants.MACAROON_SUGGESTED_SECRET_LENGTH} * @throws Error if macaroon isn't valid */ public assertIsValid(secret:string):void; /** * @param secret a Buffer, that will be used, a minimum length of {@link MacaroonsConstants.MACAROON_SUGGESTED_SECRET_LENGTH} is highly recommended * @throws Error if macaroon isn't valid */ public assertIsValid(secret:Buffer):void; public assertIsValid(secret:any):void { var secretBuffer = (secret instanceof Buffer) ? secret : CryptoTools.generate_derived_key(secret); var result = this.isValid_verify_raw(this.macaroon, secretBuffer); if (result.fail) { var msg = result.failMessage != null ? result.failMessage : "This macaroon isn't valid."; throw new Error(msg); } } /** * @param secret string this secret will be enhanced, in case it's shorter than {@link MacaroonsConstants.MACAROON_SUGGESTED_SECRET_LENGTH} * @return true/false if the macaroon is valid */ public isValid(secret:string):boolean; /** * @param secret a Buffer, that will be used, a minimum length of {@link MacaroonsConstants.MACAROON_SUGGESTED_SECRET_LENGTH} is highly recommended * @return true/false if the macaroon is valid */ public isValid(secret:Buffer):boolean; public isValid(secret:any):boolean { var secretBuffer = (secret instanceof Buffer) ? secret : CryptoTools.generate_derived_key(secret); return !this.isValid_verify_raw(this.macaroon, secretBuffer).fail; } /** * Caveats like these are called "exact caveats" because there is exactly one way * to satisfy them. Either the given caveat matches, or it doesn't. At * verification time, the verifier will check each caveat in the macaroon against * the list of satisfied caveats provided to satisfyExact(String). * When it finds a match, it knows that the caveat holds and it can move onto the next caveat in * the macaroon. * * @param caveat caveat * @return this {@link MacaroonsVerifier} */ public satisfyExact(caveat:string):MacaroonsVerifier { if (caveat) { this.predicates.push(caveat); } return this; } /** * Binds a prepared macaroon. * * @param preparedMacaroon preparedMacaroon * @return this {@link MacaroonsVerifier} */ public satisfy3rdParty(preparedMacaroon:Macaroon):MacaroonsVerifier { if (preparedMacaroon) { this.boundMacaroons.push(preparedMacaroon); } return this; } /** * Another technique for informing the verifier that a caveat is satisfied * allows for expressive caveats. Whereas exact caveats are checked * by simple byte-wise equality, general caveats are checked using * an application-provided callback that returns true if and only if the caveat * is true within the context of the request. * There's no limit on the contents of a general caveat, * so long as the callback understands how to determine whether it is satisfied. * This technique is called "general caveats". * * @param generalVerifier generalVerifier a function(caveat:string):boolean which does the verification * @return this {@link MacaroonsVerifier} */ public satisfyGeneral(generalVerifier:(caveat:string)=>boolean):MacaroonsVerifier { if (generalVerifier) { this.generalCaveatVerifiers.push(generalVerifier); } return this; } private isValid_verify_raw(M:Macaroon, secret:Buffer):VerificationResult { var vresult = this.macaroon_verify_inner(M, secret); if (!vresult.fail) { vresult.fail = !BufferTools.equals(vresult.csig, this.macaroon.signatureBuffer); if (vresult.fail) { vresult = new VerificationResult("Verification failed. Signature doesn't match. Maybe the key was wrong OR some caveats aren't satisfied."); } } return vresult; } private macaroon_verify_inner(M:Macaroon, key:Buffer):VerificationResult { var csig:Buffer = CryptoTools.macaroon_hmac(key, M.identifier); if (M.caveatPackets != null) { var caveatPackets = M.caveatPackets; for (var i = 0; i < caveatPackets.length; i++) { var caveat = caveatPackets[i]; if (caveat == null) continue; if (caveat.type == CaveatPacketType.cl) continue; if (!(caveat.type == CaveatPacketType.cid && caveatPackets[Math.min(i + 1, caveatPackets.length - 1)].type == CaveatPacketType.vid)) { if (MacaroonsVerifier.containsElement(this.predicates, caveat.getValueAsText()) || this.verifiesGeneral(caveat.getValueAsText())) { csig = CryptoTools.macaroon_hmac(csig, caveat.rawValue); } } else { i++; var caveat_vid = caveatPackets[i]; var boundMacaroon = this.findBoundMacaroon(caveat.getValueAsText()); if (boundMacaroon == null) { var msg = "Couldn't verify 3rd party macaroon, because no discharged macaroon was provided to the verifier."; return new VerificationResult(msg); } if (!this.macaroon_verify_inner_3rd(boundMacaroon, caveat_vid, csig)) { var msg = "Couldn't verify 3rd party macaroon, identifier= " + boundMacaroon.identifier; return new VerificationResult(msg); } var data = caveat.rawValue; var vdata = caveat_vid.rawValue; csig = CryptoTools.macaroon_hash2(csig, vdata, data); } } } return new VerificationResult(csig); } private macaroon_verify_inner_3rd(M:Macaroon, C:CaveatPacket, sig:Buffer):boolean { if (!M) return false; var enc_plaintext = Buffer.alloc(MacaroonsConstants.MACAROON_SECRET_TEXT_ZERO_BYTES + MacaroonsConstants.MACAROON_HASH_BYTES); var enc_ciphertext = Buffer.alloc(MacaroonsConstants.MACAROON_HASH_BYTES + MacaroonsConstants.SECRET_BOX_OVERHEAD); enc_plaintext.fill(0); enc_ciphertext.fill(0); var vid_data = C.rawValue; //assert vid_data.length == VID_NONCE_KEY_SZ; /** * the nonce is in the first MACAROON_SECRET_NONCE_BYTES * of the vid; the ciphertext is in the rest of it. */ var enc_nonce = Buffer.alloc(MacaroonsConstants.MACAROON_SECRET_NONCE_BYTES); vid_data.copy(enc_nonce, 0, 0, enc_nonce.length); /* fill in the ciphertext */ vid_data.copy(enc_ciphertext, 0, MacaroonsConstants.MACAROON_SECRET_NONCE_BYTES, MacaroonsConstants.MACAROON_SECRET_NONCE_BYTES + vid_data.length - MacaroonsConstants.MACAROON_SECRET_NONCE_BYTES); try { var enc_plaintext = CryptoTools.macaroon_secretbox_open(sig, enc_nonce, enc_ciphertext); } catch (error) { if (/Cipher bytes fail verification/.test(error.message)) { return false; } else { throw new Error("Error while deciphering 3rd party caveat, msg=" + error); } } var key = Buffer.alloc(MacaroonsConstants.MACAROON_HASH_BYTES); key.fill(0); enc_plaintext.copy(key, 0, 0, MacaroonsConstants.MACAROON_HASH_BYTES); var vresult = this.macaroon_verify_inner(M, key); var data = this.macaroon.signatureBuffer; var csig = CryptoTools.macaroon_bind(data, vresult.csig); return BufferTools.equals(csig, M.signatureBuffer); } private findBoundMacaroon(identifier:string):Macaroon { for (var i = 0; i < this.boundMacaroons.length; i++) { var boundMacaroon = this.boundMacaroons[i]; if (identifier === boundMacaroon.identifier) { return boundMacaroon; } } return null; } private verifiesGeneral(caveat:string):boolean { var found:boolean = false; for (var i = 0; i < this.generalCaveatVerifiers.length; i++) { var verifier:GeneralCaveatVerifier = this.generalCaveatVerifiers[i]; found = found || verifier(caveat); } return found; } private static containsElement(elements:string[], anElement:string):boolean { if (elements != null) { for (var i = 0; i < elements.length; i++) { var element = elements[i]; if (element === anElement) return true; } } return false; } } class VerificationResult { csig:Buffer = null; fail:boolean = false; failMessage:string = null; constructor(csig:Buffer); constructor(failMessage:string); constructor(arg:any) { if (typeof arg === 'string') { this.failMessage = arg; this.fail = true; } else if (typeof arg === 'object') { this.csig = arg; } } } interface GeneralCaveatVerifier { /** * @param caveat caveat * @return True, if this caveat is satisfies the applications requirements. False otherwise. */ (caveat:string):boolean; }
nitram509/macaroons.js
src/main/ts/MacaroonsVerifier.ts
TypeScript
apache-2.0
9,915
const _ = require('lodash'); const teFlow = require('te-flow'); const AnimManager = require('./anim-manager.js'); const _H = require('./../helpers/helper-index.js'); const animConfig = function (_key, _data) { /** * Preps the data to be processed * @param {str} key -> anim key * @param {obj} data -> anim data * @return {---} -> {key, data, globalData} */ const formatData = function (key, data) { let globalData; ({data, globalData} = _H.util.getGlobal(data)); //plural container check, don't want to format if plural if (!_H.util.regularExp.pluralTest(key, 'animation')) { data = _H.util.formatData(data, key, { addOnKeys: ['timeline', 'tl'], globalData }); } return { key, data, globalData }; }; /** * Inits the manager and then sets the data from the raw data obj * to create a itteration to cycle over in extract * @return {---} -> {animMgr} animation class with configed data */ const initSetData = function (key, data, globalData) { //init the manager to set data to const animMgr = new AnimManager(key, globalData); //loop through data and the objs _.forEach(data, function (val, objKey) { animMgr.set(val, objKey); }); return { animMgr }; }; //-> passing data to anim-extract return teFlow.call({ args: { key: _key, data: _data }}, formatData, initSetData ); }; module.exports = animConfig;
ctr-lang/ctr
lib/ctr-nodes/animation/anim-config.js
JavaScript
apache-2.0
1,529
/** * */ package com.f1000.rank.helper; import java.util.List; import com.f1000.rank.journal.model.Rank; /** * The Interface RankingHelper. * * @author mattiam */ public interface RankingHelper { /** * Ranking. * * @param <T> the generic type * @param list the list */ public <T extends Rank<T>> void ranking(List<T> list); }
mattiamascia/jrank
src/main/java/com/f1000/rank/helper/RankingHelper.java
Java
apache-2.0
361
package me.chen_wei.zhihu; import android.app.Application; import android.support.v7.app.AppCompatDelegate; /** * Created by Hander on 16/2/28. * <p/> * Email : hander_wei@163.com */ public class MyApplication extends Application { static{ //่ฎพ็ฝฎDayNightThemeๆจกๅผ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO); } @Override public void onCreate() { super.onCreate(); // LeakCanary.install(this); } }
HanderWei/ZhihuDaily
app/src/main/java/me/chen_wei/zhihu/MyApplication.java
Java
apache-2.0
489
package leetcode; /** * https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ * https://leetcode.com/explore/learn/card/array-and-string/205/array-two-pointer-technique/1153/ */ public final class Problem167TwoSumII { public int[] twoSum(int[] numbers, int target) { if (numbers == null || numbers.length == 0) { return new int[0]; } int i = 0; int j = numbers.length - 1; while (i < j) { int sum = numbers[i] + numbers[j]; if (sum == target) { return new int[] {i + 1, j + 1}; } else if (sum < target) { i++; } else { j--; } } return new int[0]; } }
jaredsburrows/cs-interview-questions
java/src/main/java/leetcode/Problem167TwoSumII.java
Java
apache-2.0
752
/* * Copyright 2013-2019 consulo.io * * 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.intellij.ide.actions.runAnything; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import com.intellij.util.xmlb.XmlSerializerUtil; import jakarta.inject.Singleton; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; /** * from kotlin */ @Singleton @State(name = "RunAnythingContextRecentDirectoryCache", storages = @Storage(StoragePathMacros.WORKSPACE_FILE)) public class RunAnythingContextRecentDirectoryCache implements PersistentStateComponent<RunAnythingContextRecentDirectoryCache.State> { static class State { public List<String> paths = new ArrayList<>(); } @Nonnull public static RunAnythingContextRecentDirectoryCache getInstance(@Nonnull Project project) { return ServiceManager.getService(project, RunAnythingContextRecentDirectoryCache.class); } private State myState = new State(); @Nonnull @Override public State getState() { return myState; } @Override public void loadState(State state) { XmlSerializerUtil.copyBean(state, myState); } }
consulo/consulo
modules/base/lang-impl/src/main/java/com/intellij/ide/actions/runAnything/RunAnythingContextRecentDirectoryCache.java
Java
apache-2.0
1,682
module Synthea module World class BirthRate def initialize @area = Synthea::Config.population.area @population_variance = Synthea::Config.population.birth_variance @rate_per_sq_mile = (Synthea::Config.population.daily_births_per_square_mile * Synthea::Config.time_step) mean = @rate_per_sq_mile * @area @distribution = Distribution::Normal.rng(mean, mean * @population_variance) end def births @distribution.call end end end end
AmartC/synthea
lib/world/birth_rate.rb
Ruby
apache-2.0
515
/******************************************************************************* * Copyright 2015 Maximilian Stark | Dakror <mail@dakror.de> * * 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 de.dakror.vloxlands.generate; import com.badlogic.gdx.math.Vector3; import de.dakror.vloxlands.game.Game; import de.dakror.vloxlands.game.world.Island; /** * @author Dakror */ public class WorldGenerator extends Thread { public float progress; public boolean done; public WorldGenerator() { setName("WorldGenerator Thread"); } @Override public void run() { for (int i = 0; i < Game.world.getWidth(); i++) { for (int j = 0; j < Game.world.getDepth(); j++) { Island island = IslandGenerator.generate(this); island.setPos(new Vector3(i * Island.SIZE, island.pos.y, j * Island.SIZE)); Game.world.addIsland(i, j, island); } } done = true; } public void step() { int total = Game.world.getWidth() * Game.world.getDepth() * 6; progress += 1f / total; } }
Dakror/Vloxlands
core/src/de/dakror/vloxlands/generate/WorldGenerator.java
Java
apache-2.0
1,624
package com.havryliuk.itarticles.data.local.preferences; import javax.inject.Inject; /** * Created by Igor Havrylyuk on 23.10.2017. */ public class AppPreferencesHelper implements IPreferencesHelper { private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN"; private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE"; private static final String PREF_KEY_USER_TOKEN = "PREF_KEY_USER_TOKEN_VALUE"; private CommonPreferencesHelper commonPreferencesHelper; @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) { this.commonPreferencesHelper = commonPreferencesHelper; } @Override public void setLoggedIn(boolean value) { commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, value); } @Override public boolean isLoggedIn() { return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN); } @Override public void setUserName(String userName) { commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName); } @Override public String getUserName() { return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME); } @Override public String getAccessToken() { return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_TOKEN); } @Override public void setAccessToken(String accessToken) { commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_TOKEN, accessToken); } }
graviton57/ITArticles
app/src/main/java/com/havryliuk/itarticles/data/local/preferences/AppPreferencesHelper.java
Java
apache-2.0
1,546
/* * 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.ignite.ml.math.impls.matrix; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Spliterator; import java.util.function.Consumer; import org.apache.ignite.lang.IgniteUuid; import org.apache.ignite.ml.math.Blas; import org.apache.ignite.ml.math.Matrix; import org.apache.ignite.ml.math.MatrixStorage; import org.apache.ignite.ml.math.Vector; import org.apache.ignite.ml.math.decompositions.LUDecomposition; import org.apache.ignite.ml.math.exceptions.CardinalityException; import org.apache.ignite.ml.math.exceptions.ColumnIndexException; import org.apache.ignite.ml.math.exceptions.RowIndexException; import org.apache.ignite.ml.math.functions.Functions; import org.apache.ignite.ml.math.functions.IgniteBiFunction; import org.apache.ignite.ml.math.functions.IgniteDoubleFunction; import org.apache.ignite.ml.math.functions.IgniteFunction; import org.apache.ignite.ml.math.functions.IgniteTriFunction; import org.apache.ignite.ml.math.functions.IntIntToDoubleFunction; import org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector; import org.apache.ignite.ml.math.impls.vector.MatrixVectorView; import org.apache.ignite.ml.math.util.MatrixUtil; /** * This class provides a helper implementation of the {@link Matrix} * interface to minimize the effort required to implement it. * Subclasses may override some of the implemented methods if a more * specific or optimized implementation is desirable. */ public abstract class AbstractMatrix implements Matrix { // Stochastic sparsity analysis. /** */ private static final double Z95 = 1.959964; /** */ private static final double Z80 = 1.281552; /** */ private static final int MAX_SAMPLES = 500; /** */ private static final int MIN_SAMPLES = 15; /** Cached minimum element. */ private Element minElm; /** Cached maximum element. */ private Element maxElm = null; /** Matrix storage implementation. */ private MatrixStorage sto; /** Meta attributes storage. */ private Map<String, Object> meta = new HashMap<>(); /** Matrix's GUID. */ private IgniteUuid guid = IgniteUuid.randomUuid(); /** * @param sto Backing {@link MatrixStorage}. */ public AbstractMatrix(MatrixStorage sto) { this.sto = sto; } /** * */ public AbstractMatrix() { // No-op. } /** * @param sto Backing {@link MatrixStorage}. */ protected void setStorage(MatrixStorage sto) { assert sto != null; this.sto = sto; } /** * @param row Row index in the matrix. * @param col Column index in the matrix. * @param v Value to set. */ protected void storageSet(int row, int col, double v) { sto.set(row, col, v); // Reset cached values. minElm = maxElm = null; } /** * @param row Row index in the matrix. * @param col Column index in the matrix. */ protected double storageGet(int row, int col) { return sto.get(row, col); } /** {@inheritDoc} */ @Override public Element maxElement() { if (maxElm == null) { double max = Double.NEGATIVE_INFINITY; int row = 0, col = 0; int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) { double d = storageGet(x, y); if (d > max) { max = d; row = x; col = y; } } maxElm = mkElement(row, col); } return maxElm; } /** {@inheritDoc} */ @Override public Element minElement() { if (minElm == null) { double min = Double.MAX_VALUE; int row = 0, col = 0; int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) { double d = storageGet(x, y); if (d < min) { min = d; row = x; col = y; } } minElm = mkElement(row, col); } return minElm; } /** {@inheritDoc} */ @Override public double maxValue() { return maxElement().get(); } /** {@inheritDoc} */ @Override public double minValue() { return minElement().get(); } /** * @param row Row index in the matrix. * @param col Column index in the matrix. */ private Element mkElement(int row, int col) { return new Element() { /** {@inheritDoc} */ @Override public double get() { return storageGet(row, col); } /** {@inheritDoc} */ @Override public int row() { return row; } /** {@inheritDoc} */ @Override public int column() { return col; } /** {@inheritDoc} */ @Override public void set(double d) { storageSet(row, col, d); } }; } /** {@inheritDoc} */ @Override public Element getElement(int row, int col) { return mkElement(row, col); } /** {@inheritDoc} */ @Override public Matrix swapRows(int row1, int row2) { checkRowIndex(row1); checkRowIndex(row2); int cols = columnSize(); for (int y = 0; y < cols; y++) { double v = getX(row1, y); setX(row1, y, getX(row2, y)); setX(row2, y, v); } return this; } /** {@inheritDoc} */ @Override public Matrix swapColumns(int col1, int col2) { checkColumnIndex(col1); checkColumnIndex(col2); int rows = rowSize(); for (int x = 0; x < rows; x++) { double v = getX(x, col1); setX(x, col1, getX(x, col2)); setX(x, col2, v); } return this; } /** {@inheritDoc} */ @Override public MatrixStorage getStorage() { return sto; } /** {@inheritDoc} */ @Override public boolean isSequentialAccess() { return sto.isSequentialAccess(); } /** {@inheritDoc} */ @Override public boolean isDense() { return sto.isDense(); } /** {@inheritDoc} */ @Override public boolean isRandomAccess() { return sto.isRandomAccess(); } /** {@inheritDoc} */ @Override public boolean isDistributed() { return sto.isDistributed(); } /** {@inheritDoc} */ @Override public boolean isArrayBased() { return sto.isArrayBased(); } /** * Check row index bounds. * * @param row Row index. */ void checkRowIndex(int row) { if (row < 0 || row >= rowSize()) throw new RowIndexException(row); } /** * Check column index bounds. * * @param col Column index. */ void checkColumnIndex(int col) { if (col < 0 || col >= columnSize()) throw new ColumnIndexException(col); } /** * Check column and row index bounds. * * @param row Row index. * @param col Column index. */ private void checkIndex(int row, int col) { checkRowIndex(row); checkColumnIndex(col); } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(sto); out.writeObject(meta); out.writeObject(guid); } /** {@inheritDoc} */ @Override public Map<String, Object> getMetaStorage() { return meta; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { sto = (MatrixStorage)in.readObject(); meta = (Map<String, Object>)in.readObject(); guid = (IgniteUuid)in.readObject(); } /** {@inheritDoc} */ @Override public Matrix assign(double val) { if (sto.isArrayBased()) Arrays.fill(sto.data(), val); else { int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, val); } return this; } /** {@inheritDoc} */ @Override public Matrix assign(IntIntToDoubleFunction fun) { int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, fun.apply(x, y)); return this; } /** */ private void checkCardinality(Matrix mtx) { checkCardinality(mtx.rowSize(), mtx.columnSize()); } /** */ private void checkCardinality(int rows, int cols) { if (rows != rowSize()) throw new CardinalityException(rowSize(), rows); if (cols != columnSize()) throw new CardinalityException(columnSize(), cols); } /** {@inheritDoc} */ @Override public Matrix assign(double[][] vals) { checkCardinality(vals.length, vals[0].length); int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, vals[x][y]); return this; } /** {@inheritDoc} */ @Override public Matrix assign(Matrix mtx) { checkCardinality(mtx); int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, mtx.getX(x, y)); return this; } /** {@inheritDoc} */ @Override public Matrix map(IgniteDoubleFunction<Double> fun) { int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, fun.apply(storageGet(x, y))); return this; } /** {@inheritDoc} */ @Override public Matrix map(Matrix mtx, IgniteBiFunction<Double, Double, Double> fun) { checkCardinality(mtx); int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) storageSet(x, y, fun.apply(storageGet(x, y), mtx.getX(x, y))); return this; } /** {@inheritDoc} */ @Override public Spliterator<Double> allSpliterator() { return new Spliterator<Double>() { /** {@inheritDoc} */ @Override public boolean tryAdvance(Consumer<? super Double> act) { int rLen = rowSize(); int cLen = columnSize(); for (int i = 0; i < rLen; i++) for (int j = 0; j < cLen; j++) act.accept(storageGet(i, j)); return true; } /** {@inheritDoc} */ @Override public Spliterator<Double> trySplit() { return null; // No Splitting. } /** {@inheritDoc} */ @Override public long estimateSize() { return rowSize() * columnSize(); } /** {@inheritDoc} */ @Override public int characteristics() { return ORDERED | SIZED; } }; } /** {@inheritDoc} */ @Override public int nonZeroElements() { int cnt = 0; for (int i = 0; i < rowSize(); i++) for (int j = 0; j < rowSize(); j++) if (get(i, j) != 0.0) cnt++; return cnt; } /** {@inheritDoc} */ @Override public Spliterator<Double> nonZeroSpliterator() { return new Spliterator<Double>() { /** {@inheritDoc} */ @Override public boolean tryAdvance(Consumer<? super Double> act) { int rLen = rowSize(); int cLen = columnSize(); for (int i = 0; i < rLen; i++) for (int j = 0; j < cLen; j++) { double val = storageGet(i, j); if (val != 0.0) act.accept(val); } return true; } /** {@inheritDoc} */ @Override public Spliterator<Double> trySplit() { return null; // No Splitting. } /** {@inheritDoc} */ @Override public long estimateSize() { return nonZeroElements(); } /** {@inheritDoc} */ @Override public int characteristics() { return ORDERED | SIZED; } }; } /** {@inheritDoc} */ @Override public Matrix assignColumn(int col, Vector vec) { checkColumnIndex(col); int rows = rowSize(); for (int x = 0; x < rows; x++) storageSet(x, col, vec.getX(x)); return this; } /** {@inheritDoc} */ @Override public Matrix assignRow(int row, Vector vec) { checkRowIndex(row); int cols = columnSize(); if (cols != vec.size()) throw new CardinalityException(cols, vec.size()); // TODO: IGNITE-5777, use Blas for this. for (int y = 0; y < cols; y++) storageSet(row, y, vec.getX(y)); return this; } /** {@inheritDoc} */ @Override public Vector foldRows(IgniteFunction<Vector, Double> fun) { int rows = rowSize(); Vector vec = likeVector(rows); for (int i = 0; i < rows; i++) vec.setX(i, fun.apply(viewRow(i))); return vec; } /** {@inheritDoc} */ @Override public Vector foldColumns(IgniteFunction<Vector, Double> fun) { int cols = columnSize(); Vector vec = likeVector(cols); for (int i = 0; i < cols; i++) vec.setX(i, fun.apply(viewColumn(i))); return vec; } /** {@inheritDoc} */ @Override public <T> T foldMap(IgniteBiFunction<T, Double, T> foldFun, IgniteDoubleFunction<Double> mapFun, T zeroVal) { T res = zeroVal; int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) res = foldFun.apply(res, mapFun.apply(storageGet(x, y))); return res; } /** {@inheritDoc} */ @Override public int columnSize() { return sto.columnSize(); } /** {@inheritDoc} */ @Override public int rowSize() { return sto.rowSize(); } /** {@inheritDoc} */ @Override public double determinant() { //TODO: IGNITE-5799, This decomposition should be cached LUDecomposition dec = new LUDecomposition(this); double res = dec.determinant(); dec.destroy(); return res; } /** {@inheritDoc} */ @Override public Matrix inverse() { if (rowSize() != columnSize()) throw new CardinalityException(rowSize(), columnSize()); //TODO: IGNITE-5799, This decomposition should be cached LUDecomposition dec = new LUDecomposition(this); Matrix res = dec.solve(likeIdentity()); dec.destroy(); return res; } /** */ protected Matrix likeIdentity() { int n = rowSize(); Matrix res = like(n, n); for (int i = 0; i < n; i++) res.setX(i, i, 1.0); return res; } /** {@inheritDoc} */ @Override public Matrix divide(double d) { int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) setX(x, y, getX(x, y) / d); return this; } /** {@inheritDoc} */ @Override public double get(int row, int col) { checkIndex(row, col); return storageGet(row, col); } /** {@inheritDoc} */ @Override public double getX(int row, int col) { return storageGet(row, col); } /** {@inheritDoc} */ @Override public Matrix minus(Matrix mtx) { int rows = rowSize(); int cols = columnSize(); checkCardinality(rows, cols); Matrix res = like(rows, cols); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) res.setX(x, y, getX(x, y) - mtx.getX(x, y)); return res; } /** {@inheritDoc} */ @Override public Matrix plus(double x) { Matrix cp = copy(); cp.map(Functions.plus(x)); return cp; } /** {@inheritDoc} */ @Override public Matrix plus(Matrix mtx) { int rows = rowSize(); int cols = columnSize(); checkCardinality(rows, cols); Matrix res = like(rows, cols); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) res.setX(x, y, getX(x, y) + mtx.getX(x, y)); return res; } /** {@inheritDoc} */ @Override public IgniteUuid guid() { return guid; } /** {@inheritDoc} */ @Override public Matrix set(int row, int col, double val) { checkIndex(row, col); storageSet(row, col, val); return this; } /** {@inheritDoc} */ @Override public Matrix setRow(int row, double[] data) { checkRowIndex(row); int cols = columnSize(); if (cols != data.length) throw new CardinalityException(cols, data.length); // TODO: IGNITE-5777, use Blas for this. for (int y = 0; y < cols; y++) setX(row, y, data[y]); return this; } /** {@inheritDoc} */ @Override public Vector getRow(int row) { checkRowIndex(row); Vector res = new DenseLocalOnHeapVector(columnSize()); for (int i = 0; i < columnSize(); i++) res.setX(i, getX(row, i)); return res; } /** {@inheritDoc} */ @Override public Matrix setColumn(int col, double[] data) { checkColumnIndex(col); int rows = rowSize(); if (rows != data.length) throw new CardinalityException(rows, data.length); for (int x = 0; x < rows; x++) setX(x, col, data[x]); return this; } /** {@inheritDoc} */ @Override public Vector getCol(int col) { checkColumnIndex(col); Vector res; if (isDistributed()) res = MatrixUtil.likeVector(this, rowSize()); else res = new DenseLocalOnHeapVector(rowSize()); for (int i = 0; i < rowSize(); i++) res.setX(i, getX(i, col)); return res; } /** {@inheritDoc} */ @Override public Matrix setX(int row, int col, double val) { storageSet(row, col, val); return this; } /** {@inheritDoc} */ @Override public double maxAbsRowSumNorm() { double max = 0.0; int rows = rowSize(); int cols = columnSize(); for (int x = 0; x < rows; x++) { double sum = 0; for (int y = 0; y < cols; y++) sum += Math.abs(getX(x, y)); if (sum > max) max = sum; } return max; } /** {@inheritDoc} */ @Override public Matrix times(double x) { Matrix cp = copy(); cp.map(Functions.mult(x)); return cp; } /** {@inheritDoc} */ @Override public Vector times(Vector vec) { int cols = columnSize(); if (cols != vec.size()) throw new CardinalityException(cols, vec.size()); int rows = rowSize(); Vector res = likeVector(rows); Blas.gemv(1, this, vec, 0, res); return res; } /** {@inheritDoc} */ @Override public Matrix times(Matrix mtx) { int cols = columnSize(); if (cols != mtx.rowSize()) throw new CardinalityException(cols, mtx.rowSize()); Matrix res = like(rowSize(), mtx.columnSize()); Blas.gemm(1, this, mtx, 0, res); return res; } /** {@inheritDoc} */ @Override public double sum() { int rows = rowSize(); int cols = columnSize(); double sum = 0.0; for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) sum += getX(x, y); return sum; } /** {@inheritDoc} */ @Override public Matrix transpose() { int rows = rowSize(); int cols = columnSize(); Matrix mtx = like(cols, rows); for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) mtx.setX(y, x, getX(x, y)); return mtx; } /** {@inheritDoc} */ @Override public boolean density(double threshold) { assert threshold >= 0.0 && threshold <= 1.0; int n = MIN_SAMPLES; int rows = rowSize(); int cols = columnSize(); double mean = 0.0; double pq = threshold * (1 - threshold); Random rnd = new Random(); for (int i = 0; i < MIN_SAMPLES; i++) if (getX(rnd.nextInt(rows), rnd.nextInt(cols)) != 0.0) mean++; mean /= MIN_SAMPLES; double iv = Z80 * Math.sqrt(pq / n); if (mean < threshold - iv) return false; // Sparse. else if (mean > threshold + iv) return true; // Dense. while (n < MAX_SAMPLES) { // Determine upper bound we may need for 'n' to likely relinquish the uncertainty. // Here, we use confidence interval formula but solved for 'n'. double ivX = Math.max(Math.abs(threshold - mean), 1e-11); double stdErr = ivX / Z80; double nX = Math.min(Math.max((int)Math.ceil(pq / (stdErr * stdErr)), n), MAX_SAMPLES) - n; if (nX < 1.0) // IMPL NOTE this can happen with threshold 1.0 nX = 1.0; double meanNext = 0.0; for (int i = 0; i < nX; i++) if (getX(rnd.nextInt(rows), rnd.nextInt(cols)) != 0.0) meanNext++; mean = (n * mean + meanNext) / (n + nX); n += nX; // Are we good now? iv = Z80 * Math.sqrt(pq / n); if (mean < threshold - iv) return false; // Sparse. else if (mean > threshold + iv) return true; // Dense. } return mean > threshold; // Dense if mean > threshold. } /** {@inheritDoc} */ @Override public Matrix viewPart(int[] off, int[] size) { return new MatrixView(this, off[0], off[1], size[0], size[1]); } /** {@inheritDoc} */ @Override public Matrix viewPart(int rowOff, int rows, int colOff, int cols) { return viewPart(new int[] {rowOff, colOff}, new int[] {rows, cols}); } /** {@inheritDoc} */ @Override public Vector viewRow(int row) { return new MatrixVectorView(this, row, 0, 0, 1); } /** {@inheritDoc} */ @Override public Vector viewColumn(int col) { return new MatrixVectorView(this, 0, col, 1, 0); } /** {@inheritDoc} */ @Override public Vector viewDiagonal() { return new MatrixVectorView(this, 0, 0, 1, 1); } /** {@inheritDoc} */ @Override public void destroy() { getStorage().destroy(); } /** {@inheritDoc} */ @Override public Matrix copy() { Matrix cp = like(rowSize(), columnSize()); cp.assign(this); return cp; } /** {@inheritDoc} */ @Override public int hashCode() { int res = 1; res = res * 37 + guid.hashCode(); res = res * 37 + sto.hashCode(); res = res * 37 + meta.hashCode(); return res; } /** * {@inheritDoc} * * We ignore guid's for comparisons. */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractMatrix that = (AbstractMatrix)o; MatrixStorage sto = getStorage(); return (sto != null ? sto.equals(that.getStorage()) : that.getStorage() == null); } /** {@inheritDoc} */ @Override public void compute(int row, int col, IgniteTriFunction<Integer, Integer, Double, Double> f) { setX(row, col, f.apply(row, col, getX(row, col))); } /** * Return max amount of columns in 2d array. * * TODO: why this in this class, mb some util class? * * @param data Data. */ protected int getMaxAmountOfColumns(double[][] data) { int maxAmountOfCols = 0; for (int i = 0; i < data.length; i++) maxAmountOfCols = Math.max(maxAmountOfCols, data[i].length); return maxAmountOfCols; } }
WilliamDo/ignite
modules/ml/src/main/java/org/apache/ignite/ml/math/impls/matrix/AbstractMatrix.java
Java
apache-2.0
26,094
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace DotVVM.Framework.Parser.Dothtml.Parser { [DebuggerDisplay("{debuggerDisplay,nq}")] public class DothtmlBindingNode : DothtmlLiteralNode { #region debbuger display [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string debuggerDisplay { get { return "{" + Name + ": " + Value + "}"; } } #endregion public string Name { get; set; } public DothtmlBindingNode() { Escape = true; } } }
holajan/dotvvm
src/DotVVM.Framework/Parser/Dothtml/Parser/DothtmlBindingNode.cs
C#
apache-2.0
666
package com.lucidastar.hodgepodge.view; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.ProgressBar; import androidx.annotation.IntDef; import com.lucidastar.hodgepodge.R; import com.mine.lucidastarutils.utils.ScreenUtils; import com.mine.lucidastarutils.utils.Utils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by qiuyouzone on 2018/10/9. */ public class CircleProgressView extends ProgressBar { private int mReachBarSize = ScreenUtils.dp2px(getContext(), 2); // ๆœชๅฎŒๆˆ่ฟ›ๅบฆๆกๅคงๅฐ private int mNormalBarSize = ScreenUtils.dp2px(getContext(), 2); // ๆœชๅฎŒๆˆ่ฟ›ๅบฆๆกๅคงๅฐ private int mReachBarColor = Color.parseColor("#108ee9"); // ๅทฒๅฎŒๆˆ่ฟ›ๅบฆ้ขœ่‰ฒ private int mNormalBarColor = Color.parseColor("#FFD3D6DA"); // ๆœชๅฎŒๆˆ่ฟ›ๅบฆ้ขœ่‰ฒ private int mTextSize = ScreenUtils.sp2px(getContext(), 14); // ่ฟ›ๅบฆๅ€ผๅญ—ไฝ“ๅคงๅฐ private int mTextColor = Color.parseColor("#108ee9"); // ่ฟ›ๅบฆ็š„ๅ€ผๅญ—ไฝ“้ขœ่‰ฒ private float mTextSkewX; // ่ฟ›ๅบฆๅ€ผๅญ—ไฝ“ๅ€พๆ–œ่ง’ๅบฆ private String mTextSuffix = "%"; // ่ฟ›ๅบฆๅ€ผๅ‰็ผ€ private String mTextPrefix = ""; // ่ฟ›ๅบฆๅ€ผๅŽ็ผ€ private boolean mTextVisible = true; // ๆ˜ฏๅฆๆ˜พ็คบ่ฟ›ๅบฆๅ€ผ private boolean mReachCapRound; // ็”ป็ฌ”ๆ˜ฏๅฆไฝฟ็”จๅœ†่ง’่พน็•Œ๏ผŒnormalStyleไธ‹็”Ÿๆ•ˆ private int mRadius = ScreenUtils.dp2px(getContext(), 20); // ๅŠๅพ„ private int mStartArc; // ่ตทๅง‹่ง’ๅบฆ private int mInnerBackgroundColor; // ๅ†…้ƒจ่ƒŒๆ™ฏๅกซๅ……้ขœ่‰ฒ private int mProgressStyle = ProgressStyle.NORMAL; // ่ฟ›ๅบฆ้ฃŽๆ ผ private int mInnerPadding = ScreenUtils.dp2px(getContext(), 1); // ๅ†…้ƒจๅœ†ไธŽๅค–้ƒจๅœ†้—ด่ท private int mOuterColor; // ๅค–้ƒจๅœ†็Žฏ้ขœ่‰ฒ private boolean needDrawInnerBackground; // ๆ˜ฏๅฆ้œ€่ฆ็ป˜ๅˆถๅ†…้ƒจ่ƒŒๆ™ฏ private RectF rectF; // ๅค–้ƒจๅœ†็Žฏ็ป˜ๅˆถๅŒบๅŸŸ private RectF rectInner; // ๅ†…้ƒจๅœ†็Žฏ็ป˜ๅˆถๅŒบๅŸŸ private int mOuterSize = ScreenUtils.dp2px(getContext(), 1); // ๅค–ๅฑ‚ๅœ†็Žฏๅฎฝๅบฆ private Paint mTextPaint; // ็ป˜ๅˆถ่ฟ›ๅบฆๅ€ผๅญ—ไฝ“็”ป็ฌ” private Paint mNormalPaint; // ็ป˜ๅˆถๆœชๅฎŒๆˆ่ฟ›ๅบฆ็”ป็ฌ” private Paint mReachPaint; // ็ป˜ๅˆถๅทฒๅฎŒๆˆ่ฟ›ๅบฆ็”ป็ฌ” private Paint mInnerBackgroundPaint; // ๅ†…้ƒจ่ƒŒๆ™ฏ็”ป็ฌ” private Paint mOutPaint; // ๅค–้ƒจๅœ†็Žฏ็”ป็ฌ” private int mRealWidth; private int mRealHeight; @IntDef({ProgressStyle.NORMAL, ProgressStyle.FILL_IN, ProgressStyle.FILL_IN_ARC}) @Retention(RetentionPolicy.SOURCE) public @interface ProgressStyle { int NORMAL = 0; int FILL_IN = 1; int FILL_IN_ARC = 2; } public CircleProgressView(Context context) { this(context, null); } public CircleProgressView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CircleProgressView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); obtainAttributes(attrs); initPaint(); } private void initPaint() { mTextPaint = new Paint(); mTextPaint.setColor(mTextColor); mTextPaint.setStyle(Paint.Style.FILL); mTextPaint.setTextSize(mTextSize); mTextPaint.setTextSkewX(mTextSkewX); mTextPaint.setAntiAlias(true); mNormalPaint = new Paint(); mNormalPaint.setColor(mNormalBarColor); mNormalPaint.setStyle(mProgressStyle == ProgressStyle.FILL_IN_ARC ? Paint.Style.FILL : Paint.Style.STROKE); mNormalPaint.setAntiAlias(true); mNormalPaint.setStrokeWidth(mNormalBarSize); mReachPaint = new Paint(); mReachPaint.setColor(mReachBarColor); mReachPaint.setStyle(mProgressStyle == ProgressStyle.FILL_IN_ARC ? Paint.Style.FILL : Paint.Style.STROKE); mReachPaint.setAntiAlias(true); mReachPaint.setStrokeCap(mReachCapRound ? Paint.Cap.ROUND : Paint.Cap.BUTT); mReachPaint.setStrokeWidth(mReachBarSize); if (needDrawInnerBackground) { mInnerBackgroundPaint = new Paint(); mInnerBackgroundPaint.setStyle(Paint.Style.FILL); mInnerBackgroundPaint.setAntiAlias(true); mInnerBackgroundPaint.setColor(mInnerBackgroundColor); } if (mProgressStyle == ProgressStyle.FILL_IN_ARC) { mOutPaint = new Paint(); mOutPaint.setStyle(Paint.Style.STROKE); mOutPaint.setColor(mOuterColor); mOutPaint.setStrokeWidth(mOuterSize); mOutPaint.setAntiAlias(true); } } private void obtainAttributes(AttributeSet attrs) { TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.CircleProgressView); mProgressStyle = ta.getInt(R.styleable.CircleProgressView_cpv_progressStyle, ProgressStyle.NORMAL); // ่Žทๅ–ไธ‰็ง้ฃŽๆ ผ้€š็”จ็š„ๅฑžๆ€ง mNormalBarSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_progressNormalSize, mNormalBarSize); mNormalBarColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressNormalColor, mNormalBarColor); mReachBarSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_progressReachSize, mReachBarSize); mReachBarColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressReachColor, mReachBarColor); mTextSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_progressTextSize, mTextSize); mTextColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressTextColor, mTextColor); mTextSkewX = ta.getDimension(R.styleable.CircleProgressView_cpv_progressTextSkewX, 0); if (ta.hasValue(R.styleable.CircleProgressView_cpv_progressTextSuffix)) { mTextSuffix = ta.getString(R.styleable.CircleProgressView_cpv_progressTextSuffix); } if (ta.hasValue(R.styleable.CircleProgressView_cpv_progressTextPrefix)) { mTextPrefix = ta.getString(R.styleable.CircleProgressView_cpv_progressTextPrefix); } mTextVisible = ta.getBoolean(R.styleable.CircleProgressView_cpv_progressTextVisible, mTextVisible); mRadius = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_radius, mRadius); rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius); switch (mProgressStyle) { case ProgressStyle.FILL_IN: mReachBarSize = 0; mNormalBarSize = 0; mOuterSize = 0; break; case ProgressStyle.FILL_IN_ARC: mStartArc = ta.getInt(R.styleable.CircleProgressView_cpv_progressStartArc, 0) + 270; mInnerPadding = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_innerPadding, mInnerPadding); mOuterColor = ta.getColor(R.styleable.CircleProgressView_cpv_outerColor, mReachBarColor); mOuterSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_outerSize, mOuterSize); mReachBarSize = 0;// ๅฐ†็”ป็ฌ”ๅคงๅฐ้‡็ฝฎไธบ0 mNormalBarSize = 0; if (!ta.hasValue(R.styleable.CircleProgressView_cpv_progressNormalColor)) { mNormalBarColor = Color.TRANSPARENT; } int mInnerRadius = mRadius - mOuterSize / 2 - mInnerPadding; rectInner = new RectF(-mInnerRadius, -mInnerRadius, mInnerRadius, mInnerRadius); break; case ProgressStyle.NORMAL: mReachCapRound = ta.getBoolean(R.styleable.CircleProgressView_cpv_reachCapRound, true); mStartArc = ta.getInt(R.styleable.CircleProgressView_cpv_progressStartArc, 0) + 270; if (ta.hasValue(R.styleable.CircleProgressView_cpv_innerBackgroundColor)) { mInnerBackgroundColor = ta.getColor(R.styleable.CircleProgressView_cpv_innerBackgroundColor, Color.argb(0, 0, 0, 0)); needDrawInnerBackground = true; } break; } ta.recycle(); } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int maxBarPaintWidth = Math.max(mReachBarSize, mNormalBarSize); int maxPaintWidth = Math.max(maxBarPaintWidth, mOuterSize); int height = 0; int width = 0; switch (mProgressStyle) { case ProgressStyle.FILL_IN: height = getPaddingTop() + getPaddingBottom() // ่พน่ท + Math.abs(mRadius * 2); // ็›ดๅพ„ width = getPaddingLeft() + getPaddingRight() // ่พน่ท + Math.abs(mRadius * 2); // ็›ดๅพ„ break; case ProgressStyle.FILL_IN_ARC: height = getPaddingTop() + getPaddingBottom() // ่พน่ท + Math.abs(mRadius * 2) // ็›ดๅพ„ + maxPaintWidth;// ่พนๆก† width = getPaddingLeft() + getPaddingRight() // ่พน่ท + Math.abs(mRadius * 2) // ็›ดๅพ„ + maxPaintWidth;// ่พนๆก† break; case ProgressStyle.NORMAL: height = getPaddingTop() + getPaddingBottom() // ่พน่ท + Math.abs(mRadius * 2) // ็›ดๅพ„ + maxBarPaintWidth;// ่พนๆก† width = getPaddingLeft() + getPaddingRight() // ่พน่ท + Math.abs(mRadius * 2) // ็›ดๅพ„ + maxBarPaintWidth;// ่พนๆก† break; } mRealWidth = resolveSize(width, widthMeasureSpec); mRealHeight = resolveSize(height, heightMeasureSpec); setMeasuredDimension(mRealWidth, mRealHeight); } @Override protected synchronized void onDraw(Canvas canvas) { switch (mProgressStyle) { case ProgressStyle.NORMAL: drawNormalCircle(canvas); break; case ProgressStyle.FILL_IN: drawFillInCircle(canvas); break; case ProgressStyle.FILL_IN_ARC: drawFillInArcCircle(canvas); break; } } /** * ็ป˜ๅˆถPROGRESS_STYLE_FILL_IN_ARCๅœ†ๅฝข */ private void drawFillInArcCircle(Canvas canvas) { canvas.save(); canvas.translate(mRealWidth / 2, mRealHeight / 2); // ็ป˜ๅˆถๅค–ๅฑ‚ๅœ†็Žฏ canvas.drawArc(rectF, 0, 360, false, mOutPaint); // ็ป˜ๅˆถๅ†…ๅฑ‚่ฟ›ๅบฆๅฎžๅฟƒๅœ†ๅผง // ๅ†…ๅฑ‚ๅœ†ๅผงๅŠๅพ„ float reachArc = getProgress() * 1.0f / getMax() * 360; canvas.drawArc(rectInner, mStartArc, reachArc, true, mReachPaint); // ็ป˜ๅˆถๆœชๅˆฐ่พพ่ฟ›ๅบฆ if (reachArc != 360) { canvas.drawArc(rectInner, reachArc + mStartArc, 360 - reachArc, true, mNormalPaint); } canvas.restore(); } /** * ็ป˜ๅˆถPROGRESS_STYLE_FILL_INๅœ†ๅฝข */ private void drawFillInCircle(Canvas canvas) { canvas.save(); canvas.translate(mRealWidth / 2, mRealHeight / 2); float progressY = getProgress() * 1.0f / getMax() * (mRadius * 2); float angle = (float) (Math.acos((mRadius - progressY) / mRadius) * 180 / Math.PI); float startAngle = 90 + angle; float sweepAngle = 360 - angle * 2; // ็ป˜ๅˆถๆœชๅˆฐ่พพๅŒบๅŸŸ rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius); mNormalPaint.setStyle(Paint.Style.FILL); canvas.drawArc(rectF, startAngle, sweepAngle, false, mNormalPaint); // ็ฟป่ฝฌ180ๅบฆ็ป˜ๅˆถๅทฒๅˆฐ่พพๅŒบๅŸŸ canvas.rotate(180); mReachPaint.setStyle(Paint.Style.FILL); canvas.drawArc(rectF, 270 - angle, angle * 2, false, mReachPaint); // ๆ–‡ๅญ—ๆ˜พ็คบๅœจๆœ€ไธŠๅฑ‚ๆœ€ๅŽ็ป˜ๅˆถ canvas.rotate(180); // ็ป˜ๅˆถๆ–‡ๅญ— if (mTextVisible) { String text = mTextPrefix + getProgress() + mTextSuffix; float textWidth = mTextPaint.measureText(text); float textHeight = (mTextPaint.descent() + mTextPaint.ascent()); canvas.drawText(text, -textWidth / 2, -textHeight / 2, mTextPaint); } } /** * ็ป˜ๅˆถPROGRESS_STYLE_NORMALๅœ†ๅฝข */ private void drawNormalCircle(Canvas canvas) { canvas.save(); canvas.translate(mRealWidth / 2, mRealHeight / 2); // ็ป˜ๅˆถๅ†…้ƒจๅœ†ๅฝข่ƒŒๆ™ฏ่‰ฒ if (needDrawInnerBackground) { canvas.drawCircle(0, 0, mRadius - Math.min(mReachBarSize, mNormalBarSize) / 2, mInnerBackgroundPaint); } // ็ป˜ๅˆถๆ–‡ๅญ— if (mTextVisible) { String text = mTextPrefix + getProgress() + mTextSuffix; float textWidth = mTextPaint.measureText(text); float textHeight = (mTextPaint.descent() + mTextPaint.ascent()); canvas.drawText(text, -textWidth / 2, -textHeight / 2, mTextPaint); } // ่ฎก็ฎ—่ฟ›ๅบฆๅ€ผ float reachArc = getProgress() * 1.0f / getMax() * 360; // ็ป˜ๅˆถๆœชๅˆฐ่พพ่ฟ›ๅบฆ if (reachArc != 360) { canvas.drawArc(rectF, reachArc + mStartArc, 360 - reachArc, false, mNormalPaint); } // ็ป˜ๅˆถๅทฒๅˆฐ่พพ่ฟ›ๅบฆ canvas.drawArc(rectF, mStartArc, reachArc, false, mReachPaint); canvas.restore(); } /** * ๅŠจ็”ป่ฟ›ๅบฆ(0-ๅฝ“ๅ‰่ฟ›ๅบฆ) * * @param duration ๅŠจ็”ปๆ—ถ้•ฟ */ public void runProgressAnim(long duration) { setProgressInTime(0, duration); } /** * @param progress ่ฟ›ๅบฆๅ€ผ * @param duration ๅŠจ็”ปๆ’ญๆ”พๆ—ถ้—ด */ public void setProgressInTime(final int progress, final long duration) { setProgressInTime(progress, getProgress(), duration); } /** * @param startProgress ่ตทๅง‹่ฟ›ๅบฆ * @param progress ่ฟ›ๅบฆๅ€ผ * @param duration ๅŠจ็”ปๆ’ญๆ”พๆ—ถ้—ด */ public void setProgressInTime(int startProgress, final int progress, final long duration) { ValueAnimator valueAnimator = ValueAnimator.ofInt(startProgress, progress); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animator) { //่Žทๅพ—ๅฝ“ๅ‰ๅŠจ็”ป็š„่ฟ›ๅบฆๅ€ผ๏ผŒๆ•ดๅž‹๏ผŒ1-100ไน‹้—ด int currentValue = (Integer) animator.getAnimatedValue(); setProgress(currentValue); } }); AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator(); valueAnimator.setInterpolator(interpolator); valueAnimator.setDuration(duration); valueAnimator.start(); } public int getReachBarSize() { return mReachBarSize; } public void setReachBarSize(int reachBarSize) { mReachBarSize = ScreenUtils.dp2px(getContext(), reachBarSize); invalidate(); } public int getNormalBarSize() { return mNormalBarSize; } public void setNormalBarSize(int normalBarSize) { mNormalBarSize = ScreenUtils.dp2px(getContext(), normalBarSize); invalidate(); } public int getReachBarColor() { return mReachBarColor; } public void setReachBarColor(int reachBarColor) { mReachBarColor = reachBarColor; invalidate(); } public int getNormalBarColor() { return mNormalBarColor; } public void setNormalBarColor(int normalBarColor) { mNormalBarColor = normalBarColor; invalidate(); } public int getTextSize() { return mTextSize; } public void setTextSize(int textSize) { mTextSize = ScreenUtils.sp2px(getContext(), textSize); invalidate(); } public int getTextColor() { return mTextColor; } public void setTextColor(int textColor) { mTextColor = textColor; invalidate(); } public float getTextSkewX() { return mTextSkewX; } public void setTextSkewX(float textSkewX) { mTextSkewX = textSkewX; invalidate(); } public String getTextSuffix() { return mTextSuffix; } public void setTextSuffix(String textSuffix) { mTextSuffix = textSuffix; invalidate(); } public String getTextPrefix() { return mTextPrefix; } public void setTextPrefix(String textPrefix) { mTextPrefix = textPrefix; invalidate(); } public boolean isTextVisible() { return mTextVisible; } public void setTextVisible(boolean textVisible) { mTextVisible = textVisible; invalidate(); } public boolean isReachCapRound() { return mReachCapRound; } public void setReachCapRound(boolean reachCapRound) { mReachCapRound = reachCapRound; invalidate(); } public int getRadius() { return mRadius; } public void setRadius(int radius) { mRadius = ScreenUtils.dp2px(getContext(), radius); invalidate(); } public int getStartArc() { return mStartArc; } public void setStartArc(int startArc) { mStartArc = startArc; invalidate(); } public int getInnerBackgroundColor() { return mInnerBackgroundColor; } public void setInnerBackgroundColor(int innerBackgroundColor) { mInnerBackgroundColor = innerBackgroundColor; invalidate(); } public int getProgressStyle() { return mProgressStyle; } public void setProgressStyle(int progressStyle) { mProgressStyle = progressStyle; invalidate(); } public int getInnerPadding() { return mInnerPadding; } public void setInnerPadding(int innerPadding) { mInnerPadding = ScreenUtils.dp2px(getContext(), innerPadding); int mInnerRadius = mRadius - mOuterSize / 2 - mInnerPadding; rectInner = new RectF(-mInnerRadius, -mInnerRadius, mInnerRadius, mInnerRadius); invalidate(); } public int getOuterColor() { return mOuterColor; } public void setOuterColor(int outerColor) { mOuterColor = outerColor; invalidate(); } public int getOuterSize() { return mOuterSize; } public void setOuterSize(int outerSize) { mOuterSize = ScreenUtils.dp2px(getContext(), outerSize); invalidate(); } private static final String STATE = "state"; private static final String PROGRESS_STYLE = "progressStyle"; private static final String TEXT_COLOR = "textColor"; private static final String TEXT_SIZE = "textSize"; private static final String TEXT_SKEW_X = "textSkewX"; private static final String TEXT_VISIBLE = "textVisible"; private static final String TEXT_SUFFIX = "textSuffix"; private static final String TEXT_PREFIX = "textPrefix"; private static final String REACH_BAR_COLOR = "reachBarColor"; private static final String REACH_BAR_SIZE = "reachBarSize"; private static final String NORMAL_BAR_COLOR = "normalBarColor"; private static final String NORMAL_BAR_SIZE = "normalBarSize"; private static final String IS_REACH_CAP_ROUND = "isReachCapRound"; private static final String RADIUS = "radius"; private static final String START_ARC = "startArc"; private static final String INNER_BG_COLOR = "innerBgColor"; private static final String INNER_PADDING = "innerPadding"; private static final String OUTER_COLOR = "outerColor"; private static final String OUTER_SIZE = "outerSize"; @Override public Parcelable onSaveInstanceState() { final Bundle bundle = new Bundle(); bundle.putParcelable(STATE, super.onSaveInstanceState()); // ไฟๅญ˜ๅฝ“ๅ‰ๆ ทๅผ bundle.putInt(PROGRESS_STYLE, getProgressStyle()); bundle.putInt(RADIUS, getRadius()); bundle.putBoolean(IS_REACH_CAP_ROUND, isReachCapRound()); bundle.putInt(START_ARC, getStartArc()); bundle.putInt(INNER_BG_COLOR, getInnerBackgroundColor()); bundle.putInt(INNER_PADDING, getInnerPadding()); bundle.putInt(OUTER_COLOR, getOuterColor()); bundle.putInt(OUTER_SIZE, getOuterSize()); // ไฟๅญ˜textไฟกๆฏ bundle.putInt(TEXT_COLOR, getTextColor()); bundle.putInt(TEXT_SIZE, getTextSize()); bundle.putFloat(TEXT_SKEW_X, getTextSkewX()); bundle.putBoolean(TEXT_VISIBLE, isTextVisible()); bundle.putString(TEXT_SUFFIX, getTextSuffix()); bundle.putString(TEXT_PREFIX, getTextPrefix()); // ไฟๅญ˜ๅทฒๅˆฐ่พพ่ฟ›ๅบฆไฟกๆฏ bundle.putInt(REACH_BAR_COLOR, getReachBarColor()); bundle.putInt(REACH_BAR_SIZE, getReachBarSize()); // ไฟๅญ˜ๆœชๅˆฐ่พพ่ฟ›ๅบฆไฟกๆฏ bundle.putInt(NORMAL_BAR_COLOR, getNormalBarColor()); bundle.putInt(NORMAL_BAR_SIZE, getNormalBarSize()); return bundle; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { final Bundle bundle = (Bundle) state; mProgressStyle = bundle.getInt(PROGRESS_STYLE); mRadius = bundle.getInt(RADIUS); mReachCapRound = bundle.getBoolean(IS_REACH_CAP_ROUND); mStartArc = bundle.getInt(START_ARC); mInnerBackgroundColor = bundle.getInt(INNER_BG_COLOR); mInnerPadding = bundle.getInt(INNER_PADDING); mOuterColor = bundle.getInt(OUTER_COLOR); mOuterSize = bundle.getInt(OUTER_SIZE); mTextColor = bundle.getInt(TEXT_COLOR); mTextSize = bundle.getInt(TEXT_SIZE); mTextSkewX = bundle.getFloat(TEXT_SKEW_X); mTextVisible = bundle.getBoolean(TEXT_VISIBLE); mTextSuffix = bundle.getString(TEXT_SUFFIX); mTextPrefix = bundle.getString(TEXT_PREFIX); mReachBarColor = bundle.getInt(REACH_BAR_COLOR); mReachBarSize = bundle.getInt(REACH_BAR_SIZE); mNormalBarColor = bundle.getInt(NORMAL_BAR_COLOR); mNormalBarSize = bundle.getInt(NORMAL_BAR_SIZE); initPaint(); super.onRestoreInstanceState(bundle.getParcelable(STATE)); return; } super.onRestoreInstanceState(state); } @Override public void invalidate() { initPaint(); super.invalidate(); } }
Lucidastar/hodgepodgeForAndroid
app/src/main/java/com/lucidastar/hodgepodge/view/CircleProgressView.java
Java
apache-2.0
22,758
package com.dxbook.ui; public class SearchResultActivity { }
treper/SlidingMenuUsage
DxStore/src/com/dxbook/ui/SearchResultActivity.java
Java
apache-2.0
63
/* * Copyright 2017-2022 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.managedblockchain.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * A summary of network configuration properties. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/managedblockchain-2018-09-24/NetworkSummary" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class NetworkSummary implements Serializable, Cloneable, StructuredPojo { /** * <p> * The unique identifier of the network. * </p> */ private String id; /** * <p> * The name of the network. * </p> */ private String name; /** * <p> * An optional description of the network. * </p> */ private String description; /** * <p> * The blockchain framework that the network uses. * </p> */ private String framework; /** * <p> * The version of the blockchain framework that the network uses. * </p> */ private String frameworkVersion; /** * <p> * The current status of the network. * </p> */ private String status; /** * <p> * The date and time that the network was created. * </p> */ private java.util.Date creationDate; /** * <p> * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * </p> */ private String arn; /** * <p> * The unique identifier of the network. * </p> * * @param id * The unique identifier of the network. */ public void setId(String id) { this.id = id; } /** * <p> * The unique identifier of the network. * </p> * * @return The unique identifier of the network. */ public String getId() { return this.id; } /** * <p> * The unique identifier of the network. * </p> * * @param id * The unique identifier of the network. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withId(String id) { setId(id); return this; } /** * <p> * The name of the network. * </p> * * @param name * The name of the network. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the network. * </p> * * @return The name of the network. */ public String getName() { return this.name; } /** * <p> * The name of the network. * </p> * * @param name * The name of the network. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withName(String name) { setName(name); return this; } /** * <p> * An optional description of the network. * </p> * * @param description * An optional description of the network. */ public void setDescription(String description) { this.description = description; } /** * <p> * An optional description of the network. * </p> * * @return An optional description of the network. */ public String getDescription() { return this.description; } /** * <p> * An optional description of the network. * </p> * * @param description * An optional description of the network. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withDescription(String description) { setDescription(description); return this; } /** * <p> * The blockchain framework that the network uses. * </p> * * @param framework * The blockchain framework that the network uses. * @see Framework */ public void setFramework(String framework) { this.framework = framework; } /** * <p> * The blockchain framework that the network uses. * </p> * * @return The blockchain framework that the network uses. * @see Framework */ public String getFramework() { return this.framework; } /** * <p> * The blockchain framework that the network uses. * </p> * * @param framework * The blockchain framework that the network uses. * @return Returns a reference to this object so that method calls can be chained together. * @see Framework */ public NetworkSummary withFramework(String framework) { setFramework(framework); return this; } /** * <p> * The blockchain framework that the network uses. * </p> * * @param framework * The blockchain framework that the network uses. * @return Returns a reference to this object so that method calls can be chained together. * @see Framework */ public NetworkSummary withFramework(Framework framework) { this.framework = framework.toString(); return this; } /** * <p> * The version of the blockchain framework that the network uses. * </p> * * @param frameworkVersion * The version of the blockchain framework that the network uses. */ public void setFrameworkVersion(String frameworkVersion) { this.frameworkVersion = frameworkVersion; } /** * <p> * The version of the blockchain framework that the network uses. * </p> * * @return The version of the blockchain framework that the network uses. */ public String getFrameworkVersion() { return this.frameworkVersion; } /** * <p> * The version of the blockchain framework that the network uses. * </p> * * @param frameworkVersion * The version of the blockchain framework that the network uses. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withFrameworkVersion(String frameworkVersion) { setFrameworkVersion(frameworkVersion); return this; } /** * <p> * The current status of the network. * </p> * * @param status * The current status of the network. * @see NetworkStatus */ public void setStatus(String status) { this.status = status; } /** * <p> * The current status of the network. * </p> * * @return The current status of the network. * @see NetworkStatus */ public String getStatus() { return this.status; } /** * <p> * The current status of the network. * </p> * * @param status * The current status of the network. * @return Returns a reference to this object so that method calls can be chained together. * @see NetworkStatus */ public NetworkSummary withStatus(String status) { setStatus(status); return this; } /** * <p> * The current status of the network. * </p> * * @param status * The current status of the network. * @return Returns a reference to this object so that method calls can be chained together. * @see NetworkStatus */ public NetworkSummary withStatus(NetworkStatus status) { this.status = status.toString(); return this; } /** * <p> * The date and time that the network was created. * </p> * * @param creationDate * The date and time that the network was created. */ public void setCreationDate(java.util.Date creationDate) { this.creationDate = creationDate; } /** * <p> * The date and time that the network was created. * </p> * * @return The date and time that the network was created. */ public java.util.Date getCreationDate() { return this.creationDate; } /** * <p> * The date and time that the network was created. * </p> * * @param creationDate * The date and time that the network was created. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withCreationDate(java.util.Date creationDate) { setCreationDate(creationDate); return this; } /** * <p> * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * </p> * * @param arn * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * </p> * * @return The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. */ public String getArn() { return this.arn; } /** * <p> * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * </p> * * @param arn * The Amazon Resource Name (ARN) of the network. For more information about ARNs and their format, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names * (ARNs)</a> in the <i>AWS General Reference</i>. * @return Returns a reference to this object so that method calls can be chained together. */ public NetworkSummary withArn(String arn) { setArn(arn); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getId() != null) sb.append("Id: ").append(getId()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getFramework() != null) sb.append("Framework: ").append(getFramework()).append(","); if (getFrameworkVersion() != null) sb.append("FrameworkVersion: ").append(getFrameworkVersion()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()).append(","); if (getCreationDate() != null) sb.append("CreationDate: ").append(getCreationDate()).append(","); if (getArn() != null) sb.append("Arn: ").append(getArn()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof NetworkSummary == false) return false; NetworkSummary other = (NetworkSummary) obj; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getFramework() == null ^ this.getFramework() == null) return false; if (other.getFramework() != null && other.getFramework().equals(this.getFramework()) == false) return false; if (other.getFrameworkVersion() == null ^ this.getFrameworkVersion() == null) return false; if (other.getFrameworkVersion() != null && other.getFrameworkVersion().equals(this.getFrameworkVersion()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getCreationDate() == null ^ this.getCreationDate() == null) return false; if (other.getCreationDate() != null && other.getCreationDate().equals(this.getCreationDate()) == false) return false; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getFramework() == null) ? 0 : getFramework().hashCode()); hashCode = prime * hashCode + ((getFrameworkVersion() == null) ? 0 : getFrameworkVersion().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getCreationDate() == null) ? 0 : getCreationDate().hashCode()); hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); return hashCode; } @Override public NetworkSummary clone() { try { return (NetworkSummary) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.managedblockchain.model.transform.NetworkSummaryMarshaller.getInstance().marshall(this, protocolMarshaller); } }
aws/aws-sdk-java
aws-java-sdk-managedblockchain/src/main/java/com/amazonaws/services/managedblockchain/model/NetworkSummary.java
Java
apache-2.0
16,696
/* * Copyright 2017-2022 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.servicecatalog.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeTagOption" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeTagOptionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * Information about the TagOption. * </p> */ private TagOptionDetail tagOptionDetail; /** * <p> * Information about the TagOption. * </p> * * @param tagOptionDetail * Information about the TagOption. */ public void setTagOptionDetail(TagOptionDetail tagOptionDetail) { this.tagOptionDetail = tagOptionDetail; } /** * <p> * Information about the TagOption. * </p> * * @return Information about the TagOption. */ public TagOptionDetail getTagOptionDetail() { return this.tagOptionDetail; } /** * <p> * Information about the TagOption. * </p> * * @param tagOptionDetail * Information about the TagOption. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeTagOptionResult withTagOptionDetail(TagOptionDetail tagOptionDetail) { setTagOptionDetail(tagOptionDetail); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getTagOptionDetail() != null) sb.append("TagOptionDetail: ").append(getTagOptionDetail()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeTagOptionResult == false) return false; DescribeTagOptionResult other = (DescribeTagOptionResult) obj; if (other.getTagOptionDetail() == null ^ this.getTagOptionDetail() == null) return false; if (other.getTagOptionDetail() != null && other.getTagOptionDetail().equals(this.getTagOptionDetail()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getTagOptionDetail() == null) ? 0 : getTagOptionDetail().hashCode()); return hashCode; } @Override public DescribeTagOptionResult clone() { try { return (DescribeTagOptionResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
aws/aws-sdk-java
aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/DescribeTagOptionResult.java
Java
apache-2.0
3,915
/* * 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.scavi.brainsqueeze.codefight.challenge; import java.util.GregorianCalendar; public class CreditCycle { int creditCycle(int m, int d, int y, int c) { if (c < d) return d - c; if (--m == 0) { m = 12; --y; } return new GregorianCalendar(y, m-1, 1).getActualMaximum(5) - c + d; } }
Scavi/BrainSqueeze
src/main/java/com/scavi/brainsqueeze/codefight/challenge/CreditCycle.java
Java
apache-2.0
923
/* * Copyright 2015-2018 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 example.springdata.jpa.multipleds.order; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import example.springdata.jpa.multipleds.customer.CustomerRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; /** * Integration test for {@link CustomerRepository}. * * @author Oliver Gierke */ @RunWith(SpringRunner.class) @SpringBootTest @Transactional(transactionManager = "orderTransactionManager") public class OrderRepositoryTests { @Autowired OrderRepository orders; @Autowired CustomerRepository customers; @Test public void persistsAndFindsCustomer() { customers.findAll().forEach(customer -> { assertThat(orders.findByCustomer(customer.getId()), hasSize(1)); }); } }
thomasdarimont/spring-data-examples
jpa/multiple-datasources/src/test/java/example/springdata/jpa/multipleds/order/OrderRepositoryTests.java
Java
apache-2.0
1,608
package com.commercetools.sunrise.common.template.cms.filebased; import com.commercetools.sunrise.cms.CmsPage; import com.commercetools.sunrise.cms.CmsService; import com.commercetools.sunrise.common.template.i18n.I18nResolver; import javax.inject.Inject; import javax.inject.Named; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.concurrent.CompletionStage; import static java.util.concurrent.CompletableFuture.completedFuture; /** * Service that provides content data from i18n files that can be found in a local file. * Internally it uses a I18nResolver to resolve the requested messages. * * The mapping of the {@link CmsService} parameters to {@link I18nResolver} parameters goes as follows: * * - {@code bundle} = {@code entryType} (e.g. banner) * - {@code messageKey} = {@code entryKey.fieldName} (e.g. homeTopLeft.subtitle.text) */ public final class FileBasedCmsService implements CmsService { @Inject @Named("cms") private I18nResolver i18nResolver; @Override public CompletionStage<Optional<CmsPage>> page(final String pageKey, final List<Locale> locales) { final CmsPage cmsPage = new FileBasedCmsPage(i18nResolver, pageKey, locales); return completedFuture(Optional.of(cmsPage)); } }
rfuertesp/pruebas2
common/app/com/commercetools/sunrise/common/template/cms/filebased/FileBasedCmsService.java
Java
apache-2.0
1,294
import torch from torch import nn, Tensor from typing import Iterable, Dict from sentence_transformers import SentenceTransformer from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, PreTrainedModel import logging logger = logging.getLogger(__name__) class DenoisingAutoEncoderLoss(nn.Module): """ This loss expects as input a batch consisting of damaged sentences and the corresponding original ones. The data generation process has already been implemented in readers/DenoisingAutoEncoderReader.py During training, the decoder reconstructs the original sentences from the encoded sentence embeddings. Here the argument 'decoder_name_or_path' indicates the pretrained model (supported by Huggingface) to be used as the decoder. Since decoding process is included, here the decoder should have a class called XXXLMHead (in the context of Huggingface's Transformers). Flag 'tie_encoder_decoder' indicates whether to tie the trainable parameters of encoder and decoder, which is shown beneficial to model performance while limiting the amount of required memory. Only when the encoder and decoder are from the same architecture, can the flag 'tie_encoder_decoder' works. For more information, please refer to the TSDAE paper. """ def __init__( self, model: SentenceTransformer, decoder_name_or_path: str = None, tie_encoder_decoder: bool = True ): """ :param model: SentenceTransformer model :param decoder_name_or_path: Model name or path for initializing a decoder (compatible with Huggingface's Transformers) :param tie_encoder_decoder: whether to tie the trainable parameters of encoder and decoder """ super(DenoisingAutoEncoderLoss, self).__init__() self.encoder = model # This will be the final model used during the inference time. self.tokenizer_encoder = model.tokenizer encoder_name_or_path = model[0].auto_model.config._name_or_path if decoder_name_or_path is None: assert tie_encoder_decoder, "Must indicate the decoder_name_or_path argument when tie_encoder_decoder=False!" if tie_encoder_decoder: if decoder_name_or_path: logger.warning('When tie_encoder_decoder=True, the decoder_name_or_path will be invalid.') decoder_name_or_path = encoder_name_or_path self.tokenizer_decoder = AutoTokenizer.from_pretrained(decoder_name_or_path) self.need_retokenization = not (type(self.tokenizer_encoder) == type(self.tokenizer_decoder)) decoder_config = AutoConfig.from_pretrained(decoder_name_or_path) decoder_config.is_decoder = True decoder_config.add_cross_attention = True kwargs_decoder = {'config': decoder_config} try: self.decoder = AutoModelForCausalLM.from_pretrained(decoder_name_or_path, **kwargs_decoder) except ValueError as e: logger.error(f'Model name or path "{decoder_name_or_path}" does not support being as a decoder. Please make sure the decoder model has an "XXXLMHead" class.') raise e assert model[0].auto_model.config.hidden_size == decoder_config.hidden_size, 'Hidden sizes do not match!' if self.tokenizer_decoder.pad_token is None: # Needed by GPT-2, etc. self.tokenizer_decoder.pad_token = self.tokenizer_decoder.eos_token self.decoder.config.pad_token_id = self.decoder.config.eos_token_id if len(AutoTokenizer.from_pretrained(encoder_name_or_path)) != len(self.tokenizer_encoder): logger.warning('WARNING: The vocabulary of the encoder has been changed. One might need to change the decoder vocabulary, too.') if tie_encoder_decoder: assert not self.need_retokenization, "The tokenizers should be the same when tie_encoder_decoder=True." if len(self.tokenizer_encoder) != len(self.tokenizer_decoder): # The vocabulary has been changed. self.tokenizer_decoder = self.tokenizer_encoder self.decoder.resize_token_embeddings(len(self.tokenizer_decoder)) logger.warning('Since the encoder vocabulary has been changed and --tie_encoder_decoder=True, now the new vocabulary has also been used for the decoder.') decoder_base_model_prefix = self.decoder.base_model_prefix PreTrainedModel._tie_encoder_decoder_weights( model[0].auto_model, self.decoder._modules[decoder_base_model_prefix], self.decoder.base_model_prefix ) def retokenize(self, sentence_features): input_ids = sentence_features['input_ids'] device = input_ids.device sentences_decoded = self.tokenizer_decoder.batch_decode( input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True ) retokenized = self.tokenizer_decoder( sentences_decoded, padding=True, truncation='longest_first', return_tensors="pt", max_length=None ).to(device) return retokenized def forward(self, sentence_features: Iterable[Dict[str, Tensor]], labels: Tensor): source_features, target_features = tuple(sentence_features) if self.need_retokenization: # since the sentence_features here are all tokenized by encoder's tokenizer, # retokenization by the decoder's one is needed if different tokenizers used target_features = self.retokenize(target_features) reps = self.encoder(source_features)['sentence_embedding'] # (bsz, hdim) # Prepare input and output target_length = target_features['input_ids'].shape[1] decoder_input_ids = target_features['input_ids'].clone()[:, :target_length - 1] label_ids = target_features['input_ids'][:, 1:] # Decode decoder_outputs = self.decoder( input_ids=decoder_input_ids, inputs_embeds=None, attention_mask=None, encoder_hidden_states=reps[:, None], # (bsz, hdim) -> (bsz, 1, hdim) encoder_attention_mask=source_features['attention_mask'][:, 0:1], labels=None, return_dict=None, use_cache=False ) # Calculate loss lm_logits = decoder_outputs[0] ce_loss_fct = nn.CrossEntropyLoss(ignore_index=self.tokenizer_decoder.pad_token_id) loss = ce_loss_fct(lm_logits.view(-1, lm_logits.shape[-1]), label_ids.reshape(-1)) return loss
UKPLab/sentence-transformers
sentence_transformers/losses/DenoisingAutoEncoderLoss.py
Python
apache-2.0
6,700
import sys from typing import Optional from bowler import Query, LN, Capture, Filename, TOKEN, SYMBOL from fissix.pytree import Node, Leaf from lib2to3.fixer_util import Name, KeywordArg, Dot, Comma, Newline, ArgList def filter_print_string(node, capture, filename) -> bool: function_name = capture.get("function_name") from pprint import pprint pprint(node) pprint(capture) return True def filter_has_no_on_delete(node: LN, capture: Capture, filename: Filename) -> bool: arguments = capture.get("function_arguments")[0].children for arg in arguments: if arg.type == SYMBOL.argument and arg.children[0].type == TOKEN.NAME: arg_name = arg.children[0].value if arg_name == "on_delete": return False # this call already has an on_delete argument. return True def add_on_delete_cascade( node: LN, capture: Capture, filename: Filename ) -> Optional[LN]: arguments = capture.get("function_arguments")[0] new_on_delete_node = KeywordArg(Name(" on_delete"), Name("models.CASCADE")) if isinstance(arguments, Leaf): # Node is a leaf and so we need to replace it with a list of things we want instead. arguments.replace([arguments.clone(),Comma(),new_on_delete_node]) else: arguments.append_child(Comma()) arguments.append_child(new_on_delete_node) return node ( Query(sys.argv[1]) .select_method("ForeignKey") .is_call() .filter(filter_has_no_on_delete) .modify(add_on_delete_cascade) .idiff() ), ( Query(sys.argv[1]) .select_method("OneToOneField") .is_call() .filter(filter_has_no_on_delete) .modify(add_on_delete_cascade) .idiff() )
edx/repo-tools
edx_repo_tools/codemods/django2/foreignkey_on_delete_mod.py
Python
apache-2.0
1,718
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphalgo.impl.centrality; import java.util.ArrayList; import java.util.Map; import java.util.Random; import java.util.Set; import org.neo4j.graphalgo.CostEvaluator; import org.neo4j.graphalgo.impl.util.MatrixUtil; import org.neo4j.graphalgo.impl.util.MatrixUtil.DoubleMatrix; import org.neo4j.graphalgo.impl.util.MatrixUtil.DoubleVector; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; /** * Computing eigenvector centrality with the "Arnoldi iteration". Convergence is * dependent of the eigenvalues of the input adjacency matrix (the network). If * the two largest eigenvalues are u1 and u2, a small factor u2/u1 will give a * faster convergence (i.e. faster computation). NOTE: Currently only works on * Doubles. * @complexity The {@link CostEvaluator} is called once for every relationship * in each iteration. Assuming this is done in constant time, the * total time complexity is O(j(n + m + i)) when j internal restarts * are required and i iterations are done in the internal * eigenvector solving of the H matrix. Typically j = the number of * iterations / k, where normally k = 3. * @author Patrik Larsson * @author Anton Persson */ public class EigenvectorCentralityArnoldi extends EigenvectorCentralityBase { /** * See {@link EigenvectorCentralityBase#EigenvectorCentralityBase(Direction, CostEvaluator, Set, Set, double)} */ public EigenvectorCentralityArnoldi( Direction relationDirection, CostEvaluator<Double> costEvaluator, Set<Node> nodeSet, Set<Relationship> relationshipSet, double precision ) { super( relationDirection, costEvaluator, nodeSet, relationshipSet, precision ); } /** * This runs the Arnoldi decomposition in a specified number of steps. */ @Override protected int runInternalIteration() { int iterations = 3; // Create a list of the nodes, in order to quickly translate an index // into a node. ArrayList<Node> nodes = new ArrayList<>( nodeSet.size() ); for ( Node node : nodeSet ) { nodes.add( node ); } DoubleMatrix hMatrix = new DoubleMatrix(); DoubleMatrix qMatrix = new DoubleMatrix(); for ( int i = 0; i < nodes.size(); ++i ) { qMatrix.set( 0, i, values.get( nodes.get( i ) ) ); } int localIterations = 1; // The main arnoldi iteration loop while ( true ) { incrementTotalIterations(); Map<Node, Double> newValues = processRelationships(); // Orthogonalize for ( int j = 0; j < localIterations; ++j ) { DoubleVector qj = qMatrix.getRow( j ); // vector product double product = 0; for ( int i = 0; i < nodes.size(); ++i ) { Double d1 = newValues.get( nodes.get( i ) ); Double d2 = qj.get( i ); if ( d1 != null && d2 != null ) { product += d1 * d2; } } hMatrix.set( j, localIterations - 1, product ); if ( product != 0.0 ) { // vector subtraction for ( int i = 0; i < nodes.size(); ++i ) { Node node = nodes.get( i ); Double value = newValues.get( node ); if ( value == null ) { value = 0.0; } Double qValue = qj.get( i ); if ( qValue != null ) { newValues.put( node, value - product * qValue ); } } } } double normalizeFactor = normalize( newValues ); values = newValues; DoubleVector qVector = new DoubleVector(); for ( int i = 0; i < nodes.size(); ++i ) { Node key = nodes.get( i ); Double value = newValues.get( key ); if ( value != null ) { qVector.set( i, value ); } } qMatrix.setRow( localIterations, qVector ); if ( normalizeFactor == 0.0 || localIterations >= nodeSet.size() || localIterations >= iterations ) { break; } hMatrix.set( localIterations, localIterations - 1, normalizeFactor ); ++localIterations; } // employ the power method to find eigenvector to h Random random = new Random( System.currentTimeMillis() ); DoubleVector vector = new DoubleVector(); for ( int i = 0; i < nodeSet.size(); ++i ) { vector.set( i, random.nextDouble() ); } MatrixUtil.normalize( vector ); boolean powerDone = false; int its = 0; double powerPrecision = 0.1; while ( !powerDone ) { DoubleVector newVector = MatrixUtil.multiply( hMatrix, vector ); MatrixUtil.normalize( newVector ); powerDone = true; for ( Integer index : vector.getIndices() ) { if ( newVector.get( index ) == null ) { continue; } double factor = Math.abs( newVector.get( index ) / vector.get( index ) ); if ( factor - powerPrecision > 1.0 || factor + powerPrecision < 1.0 ) { powerDone = false; break; } } vector = newVector; ++its; if ( its > 100 ) { break; } } // multiply q and vector to get a ritz vector DoubleVector ritzVector = new DoubleVector(); for ( int r = 0; r < nodeSet.size(); ++r ) { for ( int c = 0; c < localIterations; ++c ) { ritzVector.incrementValue( r, vector.get( c ) * qMatrix.get( c, r ) ); } } for ( int i = 0; i < nodeSet.size(); ++i ) { values.put( nodes.get( i ), ritzVector.get( i ) ); } normalize( values ); return localIterations; } }
HuangLS/neo4j
community/graph-algo/src/main/java/org/neo4j/graphalgo/impl/centrality/EigenvectorCentralityArnoldi.java
Java
apache-2.0
7,492
/* * Copyright ยฉ 2016, 2017 IBM Corp. 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.cloudant.sync.internal.documentstore.callables; import com.cloudant.sync.documentstore.Attachment; import com.cloudant.sync.documentstore.AttachmentException; import com.cloudant.sync.internal.documentstore.AttachmentStreamFactory; import com.cloudant.sync.internal.documentstore.DatabaseImpl; import com.cloudant.sync.documentstore.DocumentStoreException; import com.cloudant.sync.internal.documentstore.InternalDocumentRevision; import com.cloudant.sync.internal.documentstore.DocumentRevisionTree; import com.cloudant.sync.internal.documentstore.helpers.GetFullRevisionFromCurrentCursor; import com.cloudant.sync.internal.sqlite.Cursor; import com.cloudant.sync.internal.sqlite.SQLCallable; import com.cloudant.sync.internal.sqlite.SQLDatabase; import com.cloudant.sync.internal.util.DatabaseUtils; import java.sql.SQLException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * Get all Revisions for a given Document ID, in the form of a {@code DocumentRevisionTree} * * @see DocumentRevisionTree */ public class GetAllRevisionsOfDocumentCallable implements SQLCallable<DocumentRevisionTree> { private String docId; private String attachmentsDir; private AttachmentStreamFactory attachmentStreamFactory; private static final Logger logger = Logger.getLogger(DatabaseImpl.class.getCanonicalName()); /** * @param docId The Document ID to get the Document for * @param attachmentsDir Location of attachments * @param attachmentStreamFactory Factory to manage access to attachment streams */ public GetAllRevisionsOfDocumentCallable(String docId, String attachmentsDir, AttachmentStreamFactory attachmentStreamFactory) { this.docId = docId; this.attachmentsDir = attachmentsDir; this.attachmentStreamFactory = attachmentStreamFactory; } public DocumentRevisionTree call(SQLDatabase db) throws DocumentStoreException, AttachmentException { String sql = "SELECT " + CallableSQLConstants.FULL_DOCUMENT_COLS + " FROM revs, docs " + "WHERE docs.docid=? AND revs.doc_id = docs.doc_id ORDER BY sequence ASC"; String[] args = {docId}; Cursor cursor = null; try { DocumentRevisionTree tree = new DocumentRevisionTree(); cursor = db.rawQuery(sql, args); while (cursor.moveToNext()) { long sequence = cursor.getLong(3); Map<String, ? extends Attachment> atts = new AttachmentsForRevisionCallable( this.attachmentsDir, this.attachmentStreamFactory, sequence).call(db); InternalDocumentRevision rev = GetFullRevisionFromCurrentCursor.get(cursor, atts); logger.finer("Rev: " + rev); tree.add(rev); } return tree; } catch (SQLException e) { logger.log(Level.SEVERE, "Error getting all revisions of document", e); throw new DocumentStoreException("DocumentRevisionTree not found with id: " + docId, e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } } }
cloudant/sync-android
cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/callables/GetAllRevisionsOfDocumentCallable.java
Java
apache-2.0
3,855
package com.cognizant.cognizantits.qcconnection.qcupdation; import com4j.DISPID; import com4j.DefaultValue; import com4j.IID; import com4j.NativeType; import com4j.Optional; import com4j.ReturnValue; import com4j.VTID; @IID("{2AF970F7-6CCC-4DFB-AA78-08F689481F94}") public abstract interface IBug extends IBaseFieldExMail { @DISPID(15) @VTID(24) public abstract String status(); @DISPID(15) @VTID(25) public abstract void status(String paramString); @DISPID(16) @VTID(26) public abstract String project(); @DISPID(16) @VTID(27) public abstract void project(String paramString); @DISPID(17) @VTID(28) public abstract String summary(); @DISPID(17) @VTID(29) public abstract void summary(String paramString); @DISPID(18) @VTID(30) public abstract String priority(); @DISPID(18) @VTID(31) public abstract void priority(String paramString); @DISPID(19) @VTID(32) public abstract String detectedBy(); @DISPID(19) @VTID(33) public abstract void detectedBy(String paramString); @DISPID(20) @VTID(34) public abstract String assignedTo(); @DISPID(20) @VTID(35) public abstract void assignedTo(String paramString); @DISPID(21) @VTID(36) public abstract IList findSimilarBugs(@Optional @DefaultValue("10") int paramInt); @DISPID(22) @VTID(37) public abstract boolean hasChange(); @DISPID(23) @VTID(38) public abstract IList changeLinks(); @VTID(38) @ReturnValue(type=NativeType.VARIANT, defaultPropertyThrough={IList.class}) public abstract Object changeLinks(int paramInt); } /* Location: D:\Prabu\jars\QC.jar * Qualified Name: qcupdation.IBug * JD-Core Version: 0.7.0.1 */
CognizantQAHub/Cognizant-Intelligent-Test-Scripter
QcConnection/src/main/java/com/cognizant/cognizantits/qcconnection/qcupdation/IBug.java
Java
apache-2.0
1,729
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.common.lucene; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.*; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.MockDirectoryWrapper; import org.apache.lucene.util.Version; import org.elasticsearch.test.ElasticsearchLuceneTestCase; import org.junit.Test; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * */ public class LuceneTest extends ElasticsearchLuceneTestCase { /* * simple test that ensures that we bump the version on Upgrade */ @Test public void testVersion() { // note this is just a silly sanity check, we test it in lucene, and we point to it this way assertEquals(Lucene.VERSION, Version.LATEST); } public void testPruneUnreferencedFiles() throws IOException { MockDirectoryWrapper dir = newMockDirectory(); dir.setEnableVirusScanner(false); IndexWriterConfig iwc = newIndexWriterConfig(); iwc.setIndexDeletionPolicy(NoDeletionPolicy.INSTANCE); iwc.setMergePolicy(NoMergePolicy.INSTANCE); iwc.setMaxBufferedDocs(2); IndexWriter writer = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new TextField("id", "1", random().nextBoolean() ? Field.Store.YES : Field.Store.NO)); writer.addDocument(doc); writer.commit(); doc = new Document(); doc.add(new TextField("id", "2", random().nextBoolean() ? Field.Store.YES : Field.Store.NO)); writer.addDocument(doc); doc = new Document(); doc.add(new TextField("id", "3", random().nextBoolean() ? Field.Store.YES : Field.Store.NO)); writer.addDocument(doc); writer.commit(); SegmentInfos segmentCommitInfos = Lucene.readSegmentInfos(dir); doc = new Document(); doc.add(new TextField("id", "4", random().nextBoolean() ? Field.Store.YES : Field.Store.NO)); writer.addDocument(doc); writer.deleteDocuments(new Term("id", "2")); writer.commit(); DirectoryReader open = DirectoryReader.open(writer, true); assertEquals(3, open.numDocs()); assertEquals(1, open.numDeletedDocs()); assertEquals(4, open.maxDoc()); open.close(); writer.close(); SegmentInfos si = Lucene.pruneUnreferencedFiles(segmentCommitInfos.getSegmentsFileName(), dir); assertEquals(si.getSegmentsFileName(), segmentCommitInfos.getSegmentsFileName()); open = DirectoryReader.open(dir); assertEquals(3, open.numDocs()); assertEquals(0, open.numDeletedDocs()); assertEquals(3, open.maxDoc()); IndexSearcher s = new IndexSearcher(open); assertEquals(s.search(new TermQuery(new Term("id", "1")), 1).totalHits, 1); assertEquals(s.search(new TermQuery(new Term("id", "2")), 1).totalHits, 1); assertEquals(s.search(new TermQuery(new Term("id", "3")), 1).totalHits, 1); assertEquals(s.search(new TermQuery(new Term("id", "4")), 1).totalHits, 0); for (String file : dir.listAll()) { assertFalse("unexpected file: " + file, file.equals("segments_3") || file.startsWith("_2")); } open.close(); dir.close(); } public void testFiles() throws IOException { MockDirectoryWrapper dir = newMockDirectory(); dir.setEnableVirusScanner(false); IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random())); iwc.setMergePolicy(NoMergePolicy.INSTANCE); iwc.setMaxBufferedDocs(2); iwc.setUseCompoundFile(true); IndexWriter writer = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(new TextField("id", "1", random().nextBoolean() ? Field.Store.YES : Field.Store.NO)); writer.addDocument(doc); writer.commit(); Set<String> files = new HashSet<>(); for (String f : Lucene.files(Lucene.readSegmentInfos(dir))) { files.add(f); } assertTrue(files.toString(), files.contains("segments_1")); assertTrue(files.toString(), files.contains("_0.cfs")); assertTrue(files.toString(), files.contains("_0.cfe")); assertTrue(files.toString(), files.contains("_0.si")); doc = new Document(); doc.add(new TextField("id", "2", random().nextBoolean() ? Field.Store.YES : Field.Store.NO)); writer.addDocument(doc); doc = new Document(); doc.add(new TextField("id", "3", random().nextBoolean() ? Field.Store.YES : Field.Store.NO)); writer.addDocument(doc); writer.commit(); files.clear(); for (String f : Lucene.files(Lucene.readSegmentInfos(dir))) { files.add(f); } assertFalse(files.toString(), files.contains("segments_1")); assertTrue(files.toString(), files.contains("segments_2")); assertTrue(files.toString(), files.contains("_0.cfs")); assertTrue(files.toString(), files.contains("_0.cfe")); assertTrue(files.toString(), files.contains("_0.si")); assertTrue(files.toString(), files.contains("_1.cfs")); assertTrue(files.toString(), files.contains("_1.cfe")); assertTrue(files.toString(), files.contains("_1.si")); writer.close(); dir.close(); } }
Asimov4/elasticsearch
src/test/java/org/elasticsearch/common/lucene/LuceneTest.java
Java
apache-2.0
6,332
/* * Copyright 2015-2017 Red Hat, Inc. and/or its affiliates * and other 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.hawkular.agent.monitor.storage; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import org.hawkular.agent.monitor.api.MetricTagPayloadBuilder; import org.hawkular.agent.monitor.util.Util; import org.hawkular.metrics.client.common.MetricType; /** * Allows one to build up payload requests to send to metric storage to add tags. * After all tags are added to this builder, you can get the payloads in * JSON format via {@link #toPayload()}. */ public class MetricTagPayloadBuilderImpl implements MetricTagPayloadBuilder { // key is metric ID, value is map of name/value pairs (the actual tags) private Map<String, Map<String, String>> allGauges = new HashMap<>(); private Map<String, Map<String, String>> allCounters = new HashMap<>(); private Map<String, Map<String, String>> allAvails = new HashMap<>(); // a running count of the number of tags that have been added private int count = 0; // if not null, this is the tenant ID to associate all the metrics with (null means used the agent tenant ID) private String tenantId = null; @Override public void addTag(String key, String name, String value, MetricType metricType) { Map<String, Map<String, String>> map; switch (metricType) { case GAUGE: { map = allGauges; break; } case COUNTER: { map = allCounters; break; } case AVAILABILITY: { map = allAvails; break; } default: { throw new IllegalArgumentException("Unsupported metric type: " + metricType); } } Map<String, String> allTagsForMetric = map.get(key); if (allTagsForMetric == null) { // we haven't seen this metric ID before, create a new map of tags allTagsForMetric = new TreeMap<String, String>(); // use tree map to sort the tags map.put(key, allTagsForMetric); } allTagsForMetric.put(name, value); count++; } @Override public Map<String, String> toPayload() { Map<String, Map<String, String>> withMapObject = new HashMap<>(); for (Map.Entry<String, Map<String, String>> gaugeEntry : allGauges.entrySet()) { withMapObject.put("gauges/" + Util.urlEncode(gaugeEntry.getKey()), gaugeEntry.getValue()); } for (Map.Entry<String, Map<String, String>> counterEntry : allCounters.entrySet()) { withMapObject.put("counters/" + Util.urlEncode(counterEntry.getKey()), counterEntry.getValue()); } for (Map.Entry<String, Map<String, String>> availEntry : allAvails.entrySet()) { withMapObject.put("availability/" + Util.urlEncode(availEntry.getKey()), availEntry.getValue()); } // now convert all the maps of tags to json Map<String, String> withJson = new HashMap<>(withMapObject.size()); for (Map.Entry<String, Map<String, String>> entry : withMapObject.entrySet()) { withJson.put(entry.getKey(), Util.toJson(entry.getValue())); } return withJson; } @Override public int getNumberTags() { return count; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getTenantId() { return this.tenantId; } }
Jiri-Kremser/hawkular-agent
hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/storage/MetricTagPayloadBuilderImpl.java
Java
apache-2.0
4,162
#!/usr/bin/env python ''' Script to ingest GCP billing data into a DB ''' import logging import os import re import sys from datetime import datetime from dateutil.relativedelta import relativedelta from dateutil.parser import parse as parse_date from httplib2 import Http import transaction from apiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials from sqlalchemy import engine_from_config from sqlalchemy.sql import functions from pyramid.paster import get_appsettings, setup_logging from pyramid.scripts.common import parse_vars from ..models import (DBSession, GcpLineItem) from ..util.fileloader import load_json, save_json COMMIT_THRESHOLD = 10000 LOG = None def usage(argv): ''' cli usage ''' cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [rundate=YYYY-MM-DD]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def run(settings, options): ''' do things ''' os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = settings['creds.dir'] + \ "/" + \ settings['creds.gcp.json'] scopes = ['https://www.googleapis.com/auth/cloud-platform'] credentials = ServiceAccountCredentials.from_json_keyfile_name(settings['creds.dir'] + \ "/" + \ settings['creds.gcp.json'], scopes) http_auth = credentials.authorize(Http()) # The apiclient.discovery.build() function returns an instance of an API service # object that can be used to make API calls. The object is constructed with # methods specific to the books API. The arguments provided are: # name of the API ('cloudbilling') # version of the API you are using ('v1') # API key service = build('cloudbilling', 'v1', http=http_auth, cache_discovery=False) request = service.billingAccounts().projects().list(name='billingAccounts/0085BB-6B96B9-89FD9F') response = request.execute() LOG.debug(response) def main(argv): ''' main script entry point ''' if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) global LOG LOG = logging.getLogger(__name__) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) run(settings, options) if '__main__' in __name__: try: main(sys.argv) except KeyboardInterrupt: print "Ctrl+C detected. Exiting..."
blentz/cloud-costs
budget/scripts/gcp_test.py
Python
apache-2.0
2,730
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; ?> <h3 class="page-title"> Authority management <small> Role detail </small> </h3> <div class="page-bar"> <ul class="page-breadcrumb"> <li> <i class="fa fa-home"></i> <a href="index.html">Home</a> <i class="fa fa-angle-right"></i> </li> <li> <a href="<?php echo Yii::$app->urlManager->createUrl('role/index') ?>">Authority management</a> <i class="fa fa-angle-right"></i> </li> <li> <a href="<?php echo Yii::$app->urlManager->createUrl(['role/update', 'name' => $model->name]) ?>">Role detail</a> </li> </ul> <div class="page-toolbar"> <div class="btn-group pull-right"> <button type="button" class="btn btn-fit-height grey-salt dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="true"> Actions <i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu pull-right" role="menu"> <li> <a href="<?php echo Yii::$app->urlManager->createUrl('role/create') ?>">Role add</a> </li> </ul> </div> </div> </div> <div class="row"> <div class="col-md-12 "> <!-- BEGIN SAMPLE FORM PORTLET--> <div class="portlet box green"> <div class="portlet-title"> <div class="caption"> <i class="fa fa-gift"></i> Role detail </div> </div> <div class="portlet-body form"> <!-- BEGIN FORM--> <?php $form = ActiveForm::begin([ 'id' => 'form_sample_1', 'options' => [ 'class' => 'form-horizontal', 'novalidate' => 'novalidate', ], ]); ?> <div class="form-body"> <div class="alert alert-danger display-hide"> <button class="close" data-close="alert"></button> You have some form errors. Please check below. </div> <div class="alert alert-success display-hide"> <button class="close" data-close="alert"></button> Your form validation is successful! </div> <div class="form-group"> <label class="control-label col-md-3">Role name <span class="required" aria-required="true"> * </span> </label> <div class="col-md-4"> <?= $form->field($model, 'name')->textInput([ 'class' => 'form-control', 'placeholder' => 'Please enter the role name', 'disabled' => 'disabled'])->label(false) ?> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Role type <span class="required" aria-required="true"> * </span> </label> <div class="col-md-4"> <?= $form->field($model, 'type')->textInput([ 'value' => isset($model->type) ? $model->type : NULL, 'disabled' => 'disabled', 'class' => 'form-control'])->label(false) ?> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Rule name <span class="required" aria-required="true"> </span> </label> <div class="col-md-4"> <?= $form->field($model, 'rule_name')->textInput([ 'class' => 'form-control', 'placeholder' => '', 'disabled' => 'disabled'])->label(false) ?> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Description <span class="required" aria-required="true"> </span> </label> <div class="col-md-4"> <?= $form->field($model, 'description')->textarea(['rows' => 6, 'cols' => 5, 'disabled' => 'disabled'])->label(false) ?> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Data <span class="required" aria-required="true"> </span> </label> <div class="col-md-4"> <?= $form->field($model, 'data')->textarea(['rows' => 6, 'cols' => 5, 'disabled' => 'disabled'])->label(false) ?> </div> </div> <?php if (!empty($childArray)) { ?> <div class="form-group"> <label class="control-label col-md-3">Permission list <span class="required" aria-required="true"> </span> </label> <div class="col-md-4"> <?= $form->field($model, 'child')->checkboxList($childArray, $model->child)->label(false) ?> </div> </div> <?php } ?> </div> <div class="form-actions"> <div class="row"> <div class="col-md-offset-3 col-md-9"> <a href="<?php echo Yii::$app->urlManager->createUrl(['role/update', "name" => $model->name]) ?>" class="btn default">Modify </a> <a href="<?php echo Yii::$app->urlManager->createUrl('role/index') ?>" class="btn default">Return list </a> </div> </div> </div> <!-- </form> --> <?php ActiveForm::end(); ?> <!-- END FORM--> </div> </div> <!-- END SAMPLE FORM PORTLET--> </div> </div> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/jquery-migrate.min.js" type="text/javascript"></script> <!-- IMPORTANT! Load jquery-ui-1.10.3.custom.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip --> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/jquery-ui/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/jquery.cokie.min.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <!-- BEGIN PAGE LEVEL PLUGINS --> <!-- END PAGE LEVEL PLUGINS --> <!-- BEGIN PAGE LEVEL SCRIPTS --> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/global/scripts/metronic.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/admin/layout/scripts/layout.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/admin/layout/scripts/quick-sidebar.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/admin/layout/scripts/demo.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/admin/pages/scripts/index.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/admin/pages/scripts/tasks.js" type="text/javascript"></script> <script src="<?php echo Yii::$app->request->baseUrl ?>/metronic/admin/pages/scripts/components-pickers.js"></script> <!-- END PAGE LEVEL SCRIPTS --> <script> jQuery(document).ready(function () { // initiate layout and plugins Metronic.init(); // init metronic core components Layout.init(); // init current layout QuickSidebar.init(); // init quick sidebar Demo.init(); // init demo features Tasks.initDashboardWidget(); ComponentsPickers.init(); }); </script>
diandianxiyu/Yii2-CMS-Template
views/role/view.php
PHP
apache-2.0
9,248
package org.gradle.test.performance.mediummonolithicjavaproject.p211; public class Production4230 { private String property0; public String getProperty0() { return property0; } public void setProperty0(String value) { property0 = value; } private String property1; public String getProperty1() { return property1; } public void setProperty1(String value) { property1 = value; } private String property2; public String getProperty2() { return property2; } public void setProperty2(String value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
oehme/analysing-gradle-performance
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p211/Production4230.java
Java
apache-2.0
1,891
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Binary read_entries scans the entries from a specified GraphStore and emits // them to stdout as a delimited stream. package main import ( "context" "flag" "fmt" "log" "os" "sync" "kythe.io/kythe/go/platform/delimited" "kythe.io/kythe/go/platform/vfs" "kythe.io/kythe/go/services/graphstore" "kythe.io/kythe/go/storage/gsutil" "kythe.io/kythe/go/util/flagutil" "kythe.io/kythe/go/util/kytheuri" spb "kythe.io/kythe/proto/storage_go_proto" _ "kythe.io/kythe/go/services/graphstore/proxy" _ "kythe.io/kythe/go/storage/leveldb" ) var ( gs graphstore.Service count = flag.Bool("count", false, "Only print the number of entries scanned") shardsToFiles = flag.String("sharded_file", "", "If given, scan the entire GraphStore, storing each shard in a separate file instead of stdout (requires --shards)") shardIndex = flag.Int64("shard_index", 0, "Index of a single shard to emit (requires --shards)") shards = flag.Int64("shards", 0, "Number of shards to split the GraphStore") edgeKind = flag.String("edge_kind", "", "Edge kind by which to filter a read/scan") targetTicket = flag.String("target", "", "Ticket of target by which to filter a scan") factPrefix = flag.String("fact_prefix", "", "Fact prefix by which to filter a scan") ) func init() { gsutil.Flag(&gs, "graphstore", "GraphStore to read") flag.Usage = flagutil.SimpleUsage("Scans/reads the entries from a GraphStore, emitting a delimited entry stream to stdout", "--graphstore spec [--count] [--shards N [--shard_index I] --sharded_file path] [--edge_kind] ([--fact_prefix str] [--target ticket] | [ticket...])") } func main() { flag.Parse() if gs == nil { flagutil.UsageError("missing --graphstore") } else if *shardsToFiles != "" && *shards <= 0 { flagutil.UsageError("--sharded_file and --shards must be given together") } else if *shards > 0 && len(flag.Args()) > 0 { flagutil.UsageError("--shards and giving tickets for reads are mutually exclusive") } ctx := context.Background() wr := delimited.NewWriter(os.Stdout) var total int64 if *shards <= 0 { entryFunc := func(entry *spb.Entry) error { if *count { total++ return nil } return wr.PutProto(entry) } if len(flag.Args()) > 0 { if *targetTicket != "" || *factPrefix != "" { log.Fatal("--target and --fact_prefix are unsupported when given tickets") } if err := readEntries(ctx, gs, entryFunc, *edgeKind, flag.Args()); err != nil { log.Fatal(err) } } else { if err := scanEntries(ctx, gs, entryFunc, *edgeKind, *targetTicket, *factPrefix); err != nil { log.Fatal(err) } } if *count { fmt.Println(total) } return } sgs, ok := gs.(graphstore.Sharded) if !ok { log.Fatalf("Sharding unsupported for given GraphStore type: %T", gs) } else if *shardIndex >= *shards { log.Fatalf("Invalid shard index for %d shards: %d", *shards, *shardIndex) } if *count { cnt, err := sgs.Count(ctx, &spb.CountRequest{Index: *shardIndex, Shards: *shards}) if err != nil { log.Fatalf("ERROR: %v", err) } fmt.Println(cnt) return } else if *shardsToFiles != "" { var wg sync.WaitGroup wg.Add(int(*shards)) for i := int64(0); i < *shards; i++ { go func(i int64) { defer wg.Done() path := fmt.Sprintf("%s-%.5d-of-%.5d", *shardsToFiles, i, *shards) f, err := vfs.Create(ctx, path) if err != nil { log.Fatalf("Failed to create file %q: %v", path, err) } defer f.Close() wr := delimited.NewWriter(f) if err := sgs.Shard(ctx, &spb.ShardRequest{ Index: i, Shards: *shards, }, func(entry *spb.Entry) error { return wr.PutProto(entry) }); err != nil { log.Fatalf("GraphStore shard scan error: %v", err) } }(i) } wg.Wait() return } if err := sgs.Shard(ctx, &spb.ShardRequest{ Index: *shardIndex, Shards: *shards, }, func(entry *spb.Entry) error { return wr.PutProto(entry) }); err != nil { log.Fatalf("GraphStore shard scan error: %v", err) } } func readEntries(ctx context.Context, gs graphstore.Service, entryFunc graphstore.EntryFunc, edgeKind string, tickets []string) error { for _, ticket := range tickets { src, err := kytheuri.ToVName(ticket) if err != nil { return fmt.Errorf("error parsing ticket %q: %v", ticket, err) } if err := gs.Read(ctx, &spb.ReadRequest{ Source: src, EdgeKind: edgeKind, }, entryFunc); err != nil { return fmt.Errorf("GraphStore Read error for ticket %q: %v", ticket, err) } } return nil } func scanEntries(ctx context.Context, gs graphstore.Service, entryFunc graphstore.EntryFunc, edgeKind, targetTicket, factPrefix string) error { var target *spb.VName var err error if targetTicket != "" { target, err = kytheuri.ToVName(targetTicket) if err != nil { return fmt.Errorf("error parsing --target %q: %v", targetTicket, err) } } if err := gs.Scan(ctx, &spb.ScanRequest{ EdgeKind: edgeKind, FactPrefix: factPrefix, Target: target, }, entryFunc); err != nil { return fmt.Errorf("GraphStore Scan error: %v", err) } return nil }
benjyw/kythe
kythe/go/storage/tools/read_entries/read_entries.go
GO
apache-2.0
5,685
# # Author:: Seth Chisamore (<schisamo@opscode.com>) # Cookbook Name:: chef_handlers # Recipe:: default # # Copyright 2011, Opscode, 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. # Chef::Log.info("Chef Handlers will be at: #{node['chef_handler']['handler_path']}") remote_directory node['chef_handler']['handler_path'] do source 'handlers' recursive true action :nothing if node.os == 'linux' owner 'root' group 'root' mode "0755" end end.run_action(:create)
hh/chef_handler
recipes/default.rb
Ruby
apache-2.0
989
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.marketing.campaign.activity.offline.create response. * * @author auto create * @since 1.0, 2017-04-07 18:22:19 */ public class AlipayMarketingCampaignActivityOfflineCreateResponse extends AlipayResponse { private static final long serialVersionUID = 3571851859414371374L; /** * ๅˆ›ๅปบๆˆๅŠŸ็š„ๆดปๅŠจid */ @ApiField("camp_id") private String campId; /** * ๅˆ›ๅปบๆˆๅŠŸ็š„ๅˆธๆจก็‰ˆid */ @ApiField("prize_id") private String prizeId; public void setCampId(String campId) { this.campId = campId; } public String getCampId( ) { return this.campId; } public void setPrizeId(String prizeId) { this.prizeId = prizeId; } public String getPrizeId( ) { return this.prizeId; } }
wendal/alipay-sdk
src/main/java/com/alipay/api/response/AlipayMarketingCampaignActivityOfflineCreateResponse.java
Java
apache-2.0
860
/* * Copyright 2014 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 io.github.carlomicieli.footballdb.starter.domain.games; /** * @author Carlo Micieli */ @SuppressWarnings("serial") public class PassingStatsFormatException extends IllegalArgumentException { /** * Constructs a <em>PassingStatsFormatException</em> with no detail message. */ public PassingStatsFormatException() { this("Invalid format for passing stats. Correct format is [Comp-Att-Yd-TD-INT]"); } /** * Constructs a <em>PassingStatsFormatException</em> with the specified detail message. * @param s the detail message. */ public PassingStatsFormatException(String s) { super(s); } }
CarloMicieli/footballdb-starter
src/main/java/io/github/carlomicieli/footballdb/starter/domain/games/PassingStatsFormatException.java
Java
apache-2.0
1,290
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: BceForgetPassword.proto package com.xinqihd.sns.gameserver.proto; public final class XinqiBceForgetPassword { private XinqiBceForgetPassword() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface BceForgetPasswordOrBuilder extends com.google.protobuf.MessageOrBuilder { // required string roleName = 1; boolean hasRoleName(); String getRoleName(); } public static final class BceForgetPassword extends com.google.protobuf.GeneratedMessage implements BceForgetPasswordOrBuilder { // Use BceForgetPassword.newBuilder() to construct. private BceForgetPassword(Builder builder) { super(builder); } private BceForgetPassword(boolean noInit) {} private static final BceForgetPassword defaultInstance; public static BceForgetPassword getDefaultInstance() { return defaultInstance; } public BceForgetPassword getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.internal_static_com_xinqihd_sns_gameserver_proto_BceForgetPassword_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.internal_static_com_xinqihd_sns_gameserver_proto_BceForgetPassword_fieldAccessorTable; } private int bitField0_; // required string roleName = 1; public static final int ROLENAME_FIELD_NUMBER = 1; private java.lang.Object roleName_; public boolean hasRoleName() { return ((bitField0_ & 0x00000001) == 0x00000001); } public String getRoleName() { java.lang.Object ref = roleName_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { roleName_ = s; } return s; } } private com.google.protobuf.ByteString getRoleNameBytes() { java.lang.Object ref = roleName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); roleName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { roleName_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasRoleName()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getRoleNameBytes()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getRoleNameBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPasswordOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.internal_static_com_xinqihd_sns_gameserver_proto_BceForgetPassword_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.internal_static_com_xinqihd_sns_gameserver_proto_BceForgetPassword_fieldAccessorTable; } // Construct using com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); roleName_ = ""; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword.getDescriptor(); } public com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword getDefaultInstanceForType() { return com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword.getDefaultInstance(); } public com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword build() { com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword buildPartial() { com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword result = new com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.roleName_ = roleName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword) { return mergeFrom((com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword other) { if (other == com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword.getDefaultInstance()) return this; if (other.hasRoleName()) { setRoleName(other.getRoleName()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasRoleName()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { bitField0_ |= 0x00000001; roleName_ = input.readBytes(); break; } } } } private int bitField0_; // required string roleName = 1; private java.lang.Object roleName_ = ""; public boolean hasRoleName() { return ((bitField0_ & 0x00000001) == 0x00000001); } public String getRoleName() { java.lang.Object ref = roleName_; if (!(ref instanceof String)) { String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); roleName_ = s; return s; } else { return (String) ref; } } public Builder setRoleName(String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; roleName_ = value; onChanged(); return this; } public Builder clearRoleName() { bitField0_ = (bitField0_ & ~0x00000001); roleName_ = getDefaultInstance().getRoleName(); onChanged(); return this; } void setRoleName(com.google.protobuf.ByteString value) { bitField0_ |= 0x00000001; roleName_ = value; onChanged(); } // @@protoc_insertion_point(builder_scope:com.xinqihd.sns.gameserver.proto.BceForgetPassword) } static { defaultInstance = new BceForgetPassword(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:com.xinqihd.sns.gameserver.proto.BceForgetPassword) } private static com.google.protobuf.Descriptors.Descriptor internal_static_com_xinqihd_sns_gameserver_proto_BceForgetPassword_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_com_xinqihd_sns_gameserver_proto_BceForgetPassword_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\027BceForgetPassword.proto\022 com.xinqihd.s" + "ns.gameserver.proto\"%\n\021BceForgetPassword" + "\022\020\n\010roleName\030\001 \002(\tB\030B\026XinqiBceForgetPass" + "word" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_com_xinqihd_sns_gameserver_proto_BceForgetPassword_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_com_xinqihd_sns_gameserver_proto_BceForgetPassword_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_com_xinqihd_sns_gameserver_proto_BceForgetPassword_descriptor, new java.lang.String[] { "RoleName", }, com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword.class, com.xinqihd.sns.gameserver.proto.XinqiBceForgetPassword.BceForgetPassword.Builder.class); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
wangqi/gameserver
server/src/gensrc/java/com/xinqihd/sns/gameserver/proto/XinqiBceForgetPassword.java
Java
apache-2.0
16,953
package com.lys.ping; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.pingplusplus.Pingpp; import com.pingplusplus.exception.APIConnectionException; import com.pingplusplus.exception.APIException; import com.pingplusplus.exception.AuthenticationException; import com.pingplusplus.exception.ChannelException; import com.pingplusplus.exception.InvalidRequestException; import com.pingplusplus.exception.PingppException; import com.pingplusplus.model.App; import com.pingplusplus.model.Charge; import com.pingplusplus.model.ChargeCollection; import com.sun.istack.internal.logging.Logger; /** * Charge ๅฏน่ฑก็›ธๅ…ณ็คบไพ‹ * @author sunkai * * ่ฏฅๅฎžไพ‹็จ‹ๅบๆผ”็คบไบ†ๅฆ‚ไฝ•ไปŽ ping++ ๆœๅŠกๅ™จ่Žทๅพ— charge ๏ผŒๆŸฅ่ฏข chargeใ€‚ * * ๅผ€ๅ‘่€…้œ€่ฆๅกซๅ†™ apiKey ๅ’Œ appId , apiKey ๅฏไปฅๅœจ ping++ ็ฎก็†ๅนณๅฐใ€ๅบ”็”จไฟกๆฏ้‡Œ้ขๆŸฅ็œ‹ใ€‘ * * apiKey ๆœ‰ TestKey ๅ’Œ LiveKey ไธค็งใ€‚ * * TestKey ๆจกๅผไธ‹ไธไผšไบง็”Ÿ็œŸๅฎž็š„ไบคๆ˜“ใ€‚ */ public class PingCharge { Logger logger = Logger.getLogger(getClass()); public PingCharge(){ Pingpp.apiKey = apiKey; } /** * pingpp ็ฎก็†ๅนณๅฐๅฏนๅบ”็š„ API key */ public static String apiKey = "sk_live_zGMmfNLh87sghw4qjeWs4DnP"; /** * pingpp ็ฎก็†ๅนณๅฐๅฏนๅบ”็š„ๅบ”็”จ ID */ public static String appId = "app_j9S4O4G00GC0jHWj"; public static void main(String[] args) { Pingpp.apiKey = apiKey; PingCharge ce = new PingCharge(); System.out.println("---------ๅˆ›ๅปบ charge"); //Charge charge = ce.charge(); System.out.println("---------ๆŸฅ่ฏข charge"); //ce.retrieve(charge.getId()); System.out.println("---------ๆŸฅ่ฏข chargeๅˆ—่กจ"); //ce.all(); } /** * ๅˆ›ๅปบ Charge * * ๅˆ›ๅปบ Charge ็”จๆˆท้œ€่ฆ็ป„่ฃ…ไธ€ไธช map ๅฏน่ฑกไฝœไธบๅ‚ๆ•ฐไผ ้€’็ป™ Charge.create(); * map ้‡Œ้ขๅ‚ๆ•ฐ็š„ๅ…ทไฝ“่ฏดๆ˜Ž่ฏทๅ‚่€ƒ๏ผšhttps://pingxx.com/document/api#api-c-new * @return */ public Charge charge(String channel,int amount,String Subject,String Body,String OrderId) { logger.info("channel:"+channel+" amount:"+amount+" Subject:"+Subject+" Body:"+Body+" OrderId:"+OrderId); Charge charge = null; Map<String, Object> chargeMap = new HashMap<String, Object>(); chargeMap.put("amount", amount*100); chargeMap.put("currency", "cny"); chargeMap.put("subject", Subject); chargeMap.put("body", Body); chargeMap.put("order_no", OrderId); chargeMap.put("channel", channel); chargeMap.put("client_ip", "127.0.0.1"); Map<String,Object> extra =new HashMap<String, Object>(); if(channel.equals("alipay_wap")){ extra.put("success_url", "http://www.wangzhong.com/index/PayMoneyEnd"); }else if(channel.equals("alipay_wap")){ }else if(channel.equals("upacp_wap")||channel.equals("upmp_wap")){ extra.put("result_url", "http://www.wangzhong.com/index/PayMoneyEnd"); } //extra.put("cancel_url", "http://www.wangzhong.com/"); chargeMap.put("extra", extra); Map<String, String> app = new HashMap<String, String>(); app.put("id",appId); chargeMap.put("app", app); try { //ๅ‘่ตทไบคๆ˜“่ฏทๆฑ‚ charge = Charge.create(chargeMap); System.out.println(charge); } catch (PingppException e) { e.printStackTrace(); } return charge; } /** * ๆŸฅ่ฏข Charge * * ่ฏฅๆŽฅๅฃๆ นๆฎ charge Id ๆŸฅ่ฏขๅฏนๅบ”็š„ charge ใ€‚ * ๅ‚่€ƒๆ–‡ๆกฃ๏ผšhttps://pingxx.com/document/api#api-c-inquiry * * ่ฏฅๆŽฅๅฃๅฏไปฅไผ ้€’ไธ€ไธช expand ๏ผŒ ่ฟ”ๅ›ž็š„ charge ไธญ็š„ app ไผšๅ˜ๆˆ app ๅฏน่ฑกใ€‚ * ๅ‚่€ƒๆ–‡ๆกฃ๏ผš https://pingxx.com/document/api#api-expanding * @param id */ public void retrieve(String id) { try { Map<String, Object> param = new HashMap<String, Object>(); List<String> expande = new ArrayList<String>(); expande.add("app"); param.put("expand", expande); //Charge charge = Charge.retrieve(id); //Expand app Charge charge = Charge.retrieve(id, param); if (charge.getApp() instanceof App) { //App app = (App) charge.getApp(); // System.out.println("App Object ,appId = " + app.getId()); } else { // System.out.println("String ,appId = " + charge.getApp()); } System.out.println(charge); } catch (PingppException e) { e.printStackTrace(); } } /** * ๅˆ†้กตๆŸฅ่ฏขCharge * * ่ฏฅๆŽฅๅฃไธบๆ‰น้‡ๆŸฅ่ฏขๆŽฅๅฃ๏ผŒ้ป˜่ฎคไธ€ๆฌกๆŸฅ่ฏข10ๆกใ€‚ * ็”จๆˆทๅฏไปฅ้€š่ฟ‡ๆทปๅŠ  limit ๅ‚ๆ•ฐ่‡ช่กŒ่ฎพ็ฝฎๆŸฅ่ฏขๆ•ฐ็›ฎ๏ผŒๆœ€ๅคšไธ€ๆฌกไธ่ƒฝ่ถ…่ฟ‡ 100 ๆกใ€‚ * * ่ฏฅๆŽฅๅฃๅŒๆ ทๅฏไปฅไฝฟ็”จ expand ๅ‚ๆ•ฐใ€‚ * @return */ public ChargeCollection all() { ChargeCollection chargeCollection = null; Map<String, Object> chargeParams = new HashMap<String, Object>(); chargeParams.put("limit", 3); //ๅขžๅŠ ๆญคๅค„่ฎพๆ–ฝ๏ผŒๅˆปๆ„่Žทๅ–app expande // List<String> expande = new ArrayList<String>(); // expande.add("app"); // chargeParams.put("expand", expande); try { chargeCollection = Charge.all(chargeParams); System.out.println(chargeCollection); } catch (AuthenticationException e) { e.printStackTrace(); } catch (InvalidRequestException e) { e.printStackTrace(); } catch (APIConnectionException e) { e.printStackTrace(); } catch (APIException e) { e.printStackTrace(); } catch (ChannelException e) { e.printStackTrace(); } return chargeCollection; } }
zzsoszz/wyyf
src/com/lys/ping/PingCharge.java
Java
apache-2.0
5,897
# -*- coding: utf-8 -*- # # Copyright 2014-2020 BigML # # 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. """BigMLer - Resources processing: creation, update and retrieval of ensembles """ import bigmler.utils as u import bigmler.resourcesapi.ensembles as r import bigmler.checkpoint as c MONTECARLO_FACTOR = 200 def ensemble_processing(datasets, api, args, resume, fields=None, session_file=None, path=None, log=None): """Creates an ensemble of models from the input data """ ensembles = [] ensemble_ids = [] models = [] model_ids = [] number_of_ensembles = len(datasets) if resume: resume, ensemble_ids = c.checkpoint( c.are_ensembles_created, path, number_of_ensembles, debug=args.debug) if args.number_of_models > 1: _, model_ids = c.checkpoint(c.are_models_created, path, \ number_of_ensembles * args.number_of_models) models = model_ids if not resume: message = u.dated("Found %s ensembles out of %s. Resuming.\n" % (len(ensemble_ids), number_of_ensembles)) u.log_message(message, log_file=session_file, console=args.verbosity) ensembles = ensemble_ids number_of_ensembles -= len(ensemble_ids) if number_of_ensembles > 0: ensemble_args = r.set_ensemble_args(args, fields=fields) ensembles, ensemble_ids, models, model_ids = r.create_ensembles( datasets, ensembles, ensemble_args, args, api=api, path=path, number_of_ensembles=number_of_ensembles, session_file=session_file, log=log) return ensembles, ensemble_ids, models, model_ids, resume def ensemble_per_label(labels, dataset, api, args, resume, fields=None, multi_label_data=None, session_file=None, path=None, log=None): """Creates an ensemble per label for multi-label datasets """ ensemble_ids = [] ensembles = [] model_ids = [] models = [] number_of_ensembles = len(labels) if resume: resume, ensemble_ids = c.checkpoint( c.are_ensembles_created, path, number_of_ensembles, debug=args.debug) ensembles = ensemble_ids if not resume: message = u.dated("Found %s ensembles out of %s." " Resuming.\n" % (len(ensemble_ids), number_of_ensembles)) u.log_message(message, log_file=session_file, console=args.verbosity) # erase models' info that will be rebuilt u.log_created_resources("models", path, None, mode='w') number_of_ensembles = len(labels) - len(ensemble_ids) ensemble_args_list = r.set_label_ensemble_args( args, labels, multi_label_data, number_of_ensembles, fields) # create ensembles changing the input_field to select # only one label at a time (ensembles, ensemble_ids, models, model_ids) = r.create_ensembles( dataset, ensemble_ids, ensemble_args_list, args, number_of_ensembles, api, path, session_file, log) return ensembles, ensemble_ids, models, model_ids, resume
jaor/bigmler
bigmler/processing/ensembles.py
Python
apache-2.0
3,944
/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cli; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.android.ddmlib.IDevice; import com.android.ddmlib.IShellOutputReceiver; import com.android.ddmlib.InstallException; import com.facebook.buck.rules.ArtifactCache; import com.facebook.buck.rules.NoopArtifactCache; import com.facebook.buck.util.Ansi; import com.facebook.buck.util.ProjectFilesystem; import com.google.common.io.ByteStreams; import org.junit.Before; import org.junit.Test; import org.kohsuke.args4j.CmdLineException; import java.io.File; import java.io.OutputStream; import java.io.PrintStream; import java.util.List; import java.util.concurrent.atomic.AtomicReference; public class InstallCommandTest { private BuckConfig buckConfig; private InstallCommand installCommand; @Before public void setUp() { buckConfig = BuckConfig.emptyConfig(); installCommand = createInstallCommand(); } private InstallCommandOptions getOptions(String...args) throws CmdLineException { InstallCommandOptions options = new InstallCommandOptions(buckConfig); new CmdLineParserAdditionalOptions(options).parseArgument(args); return options; } private TestDevice createRealDevice(String serial, IDevice.DeviceState state) { TestDevice device = TestDevice.createRealDevice(serial); device.setState(state); return device; } private TestDevice createEmulator(String serial, IDevice.DeviceState state) { TestDevice device = TestDevice.createEmulator(serial); device.setState(state); return device; } private TestDevice createDeviceForShellCommandTest(final String output) { return new TestDevice() { @Override public void executeShellCommand(String cmd, IShellOutputReceiver receiver, int timeout) { byte[] outputBytes = output.getBytes(); receiver.addOutput(outputBytes, 0, outputBytes.length); receiver.flush(); } }; } private InstallCommand createInstallCommand() { OutputStream nullOut = ByteStreams.nullOutputStream(); PrintStream out = new PrintStream(nullOut); Console console = new Console(out, out, new Ansi()); ProjectFilesystem filesystem = new ProjectFilesystem(new File(".")); ArtifactCache artifactCache = new NoopArtifactCache(); return new InstallCommand(console.getStdOut(), console.getStdErr(), console, filesystem, artifactCache); } /** * Verify that null is returned when no devices are present. */ @Test public void testDeviceFilterNoDevices() throws CmdLineException { InstallCommandOptions options = getOptions(); IDevice[] devices = new IDevice[] { }; assertNull(installCommand.filterDevices(devices, options.adbOptions())); } /** * Verify that non-online devices will not appear in result list. */ @Test public void testDeviceFilterOnlineOnly() throws CmdLineException { InstallCommandOptions options = getOptions(); IDevice[] devices = new IDevice[] { createEmulator("1", IDevice.DeviceState.OFFLINE), createEmulator("2", IDevice.DeviceState.BOOTLOADER), createEmulator("3", IDevice.DeviceState.RECOVERY), createRealDevice("4", IDevice.DeviceState.OFFLINE), createRealDevice("5", IDevice.DeviceState.BOOTLOADER), createRealDevice("6", IDevice.DeviceState.RECOVERY), }; assertNull(installCommand.filterDevices(devices, options.adbOptions())); } /** * Verify that multi-install is not enabled and multiple devices * pass the filter null is returned. Also verify that if multiple * devices are passing the filter and multi-install mode is enabled * they all appear in resulting list. */ @Test public void testDeviceFilterMultipleDevices() throws CmdLineException { IDevice[] devices = new IDevice[] { createEmulator("1", IDevice.DeviceState.ONLINE), createEmulator("2", IDevice.DeviceState.ONLINE), createRealDevice("4", IDevice.DeviceState.ONLINE), createRealDevice("5", IDevice.DeviceState.ONLINE) }; InstallCommandOptions options = getOptions(); assertNull(installCommand.filterDevices(devices, options.adbOptions())); options = getOptions(AdbOptions.MULTI_INSTALL_MODE_SHORT_ARG); List<IDevice> filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNotNull(filteredDevices); assertEquals(devices.length, filteredDevices.size()); } /** * Verify that when emulator-only mode is enabled only emulators appear in result. */ @Test public void testDeviceFilterEmulator() throws CmdLineException { InstallCommandOptions options = getOptions(AdbOptions.EMULATOR_MODE_SHORT_ARG); IDevice[] devices = new IDevice[] { createEmulator("1", IDevice.DeviceState.ONLINE), createRealDevice("2", IDevice.DeviceState.ONLINE), }; List<IDevice> filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNotNull(filteredDevices); assertEquals(1, filteredDevices.size()); assertSame(devices[0], filteredDevices.get(0)); } /** * Verify that when real-device-only mode is enabled only real devices appear in result. */ @Test public void testDeviceFilterRealDevices() throws CmdLineException { InstallCommandOptions options = getOptions(AdbOptions.DEVICE_MODE_LONG_ARG); IDevice[] devices = new IDevice[] { createRealDevice("1", IDevice.DeviceState.ONLINE), createEmulator("2", IDevice.DeviceState.ONLINE) }; List<IDevice> filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNotNull(filteredDevices); assertEquals(1, filteredDevices.size()); assertSame(devices[0], filteredDevices.get(0)); } /** * Verify that filtering by serial number works. */ @Test public void testDeviceFilterBySerial() throws CmdLineException { IDevice[] devices = new IDevice[] { createRealDevice("1", IDevice.DeviceState.ONLINE), createEmulator("2", IDevice.DeviceState.ONLINE), createRealDevice("3", IDevice.DeviceState.ONLINE), createEmulator("4", IDevice.DeviceState.ONLINE) }; for (int i = 0; i < devices.length; i++) { InstallCommandOptions options = getOptions( AdbOptions.SERIAL_NUMBER_SHORT_ARG,devices[i].getSerialNumber()); List<IDevice> filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNotNull(filteredDevices); assertEquals(1, filteredDevices.size()); assertSame(devices[i], filteredDevices.get(0)); } } /** * Verify that if no devices match filters null is returned. */ @Test public void testDeviceFilterNoMatchingDevices() throws CmdLineException { IDevice[] devices = new IDevice[] { createRealDevice("1", IDevice.DeviceState.ONLINE), createEmulator("2", IDevice.DeviceState.ONLINE), createRealDevice("3", IDevice.DeviceState.ONLINE), createEmulator("4", IDevice.DeviceState.ONLINE) }; InstallCommandOptions options = getOptions( AdbOptions.SERIAL_NUMBER_SHORT_ARG, "invalid-serial"); List<IDevice> filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNull(filteredDevices); } /** * Verify that different combinations of arguments work correctly. */ @Test public void testDeviceFilterCombos() throws CmdLineException { TestDevice realDevice1 = createRealDevice("1", IDevice.DeviceState.ONLINE); TestDevice realDevice2 = createRealDevice("2", IDevice.DeviceState.ONLINE); TestDevice emulator1 = createEmulator("3", IDevice.DeviceState.ONLINE); TestDevice emulator2 = createEmulator("4", IDevice.DeviceState.ONLINE); IDevice[] devices = new IDevice[] { realDevice1, emulator1, realDevice2, emulator2 }; // Filter by serial in "real device" mode with serial number for real device. InstallCommandOptions options = getOptions( AdbOptions.SERIAL_NUMBER_SHORT_ARG, realDevice1.getSerialNumber(), AdbOptions.DEVICE_MODE_LONG_ARG); List<IDevice> filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNotNull(filteredDevices); assertEquals(1, filteredDevices.size()); assertSame(realDevice1, filteredDevices.get(0)); // Filter by serial in "real device" mode with serial number for emulator. options = getOptions( AdbOptions.SERIAL_NUMBER_SHORT_ARG, emulator1.getSerialNumber(), AdbOptions.DEVICE_MODE_LONG_ARG); filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNull(filteredDevices); // Filter by serial in "emulator" mode with serial number for real device. options = getOptions( AdbOptions.SERIAL_NUMBER_SHORT_ARG, realDevice1.getSerialNumber(), AdbOptions.EMULATOR_MODE_SHORT_ARG); filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNull(filteredDevices); // Filter by serial in "real device" mode with serial number for emulator. options = getOptions( AdbOptions.SERIAL_NUMBER_SHORT_ARG, emulator1.getSerialNumber(), AdbOptions.EMULATOR_MODE_SHORT_ARG); filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNotNull(filteredDevices); assertEquals(1, filteredDevices.size()); assertSame(emulator1, filteredDevices.get(0)); // Filter in both "real device" mode and "emulator mode". options = getOptions( AdbOptions.DEVICE_MODE_LONG_ARG, AdbOptions.EMULATOR_MODE_SHORT_ARG, AdbOptions.MULTI_INSTALL_MODE_SHORT_ARG); filteredDevices = installCommand.filterDevices(devices, options.adbOptions()); assertNotNull(filteredDevices); assertEquals(devices.length, filteredDevices.size()); for (IDevice device : devices) { assertTrue(filteredDevices.contains(device)); } } /** * Verify that successful installation on device results in true. */ @Test public void testSuccessfulDeviceInstall() { File apk = new File("/some/file.apk"); final AtomicReference<String> apkPath = new AtomicReference<String>(); TestDevice device = new TestDevice() { @Override public String installPackage(String s, boolean b, String... strings) throws InstallException { apkPath.set(s); return null; } }; device.setSerialNumber("serial#1"); device.setName("testDevice"); assertTrue(installCommand.installApkOnDevice(device, apk)); assertEquals(apk.getAbsolutePath(), apkPath.get()); } /** * Also make sure we're not erroneously parsing "Exception" and "Error". */ @Test public void testDeviceStartActivitySuccess() { TestDevice device = createDeviceForShellCommandTest( "Starting: Intent { cmp=com.example.ExceptionErrorActivity }\r\n"); assertNull(installCommand.deviceStartActivity(device, "com.foo/.Activity")); } @Test public void testDeviceStartActivityAmDoesntExist() { TestDevice device = createDeviceForShellCommandTest("sh: am: not found\r\n"); assertNotNull(installCommand.deviceStartActivity(device, "com.foo/.Activity")); } @Test public void testDeviceStartActivityActivityDoesntExist() { String errorLine = "Error: Activity class {com.foo/.Activiqy} does not exist.\r\n"; TestDevice device = createDeviceForShellCommandTest( "Starting: Intent { cmp=com.foo/.Activiqy }\r\n" + "Error type 3\r\n" + errorLine); assertEquals( errorLine.trim(), installCommand.deviceStartActivity(device, "com.foo/.Activiy").trim()); } @Test public void testDeviceStartActivityException() { String errorLine = "java.lang.SecurityException: Permission Denial: " + "starting Intent { flg=0x10000000 cmp=com.foo/.Activity } from null " + "(pid=27581, uid=2000) not exported from uid 10002\r\n"; TestDevice device = createDeviceForShellCommandTest( "Starting: Intent { cmp=com.foo/.Activity }\r\n" + errorLine + " at android.os.Parcel.readException(Parcel.java:1425)\r\n" + " at android.os.Parcel.readException(Parcel.java:1379)\r\n" + // (...) " at dalvik.system.NativeStart.main(Native Method)\r\n"); assertEquals( errorLine.trim(), installCommand.deviceStartActivity(device, "com.foo/.Activity").trim()); } /** * Verify that if failure reason is returned, installation is marked as failed. */ @Test public void testFailedDeviceInstallWithReason() { File apk = new File("/some/file.apk"); TestDevice device = new TestDevice() { @Override public String installPackage(String s, boolean b, String... strings) throws InstallException { return "[SOME_REASON]"; } }; device.setSerialNumber("serial#1"); device.setName("testDevice"); assertFalse(installCommand.installApkOnDevice(device, apk)); } /** * Verify that if exception is thrown during installation, installation is marked as failed. */ @Test public void testFailedDeviceInstallWithException() { File apk = new File("/some/file.apk"); TestDevice device = new TestDevice() { @Override public String installPackage(String s, boolean b, String... strings) throws InstallException { throw new InstallException("Failed to install on test device.", null); } }; device.setSerialNumber("serial#1"); device.setName("testDevice"); assertFalse(installCommand.installApkOnDevice(device, apk)); } }
azatoth/buck
test/com/facebook/buck/cli/InstallCommandTest.java
Java
apache-2.0
14,471
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "isourceselector.h" namespace search::queryeval { ISourceSelector::ISourceSelector(Source defaultSource) : _baseId(0), _defaultSource(defaultSource) { assert(defaultSource < SOURCE_LIMIT); } void ISourceSelector::setDefaultSource(Source source) { assert(source < SOURCE_LIMIT); assert(source >= _defaultSource); _defaultSource = source; } }
vespa-engine/vespa
searchlib/src/vespa/searchlib/queryeval/isourceselector.cpp
C++
apache-2.0
483
# == Schema Information # # Table name: course_users # # id :integer not null, primary key # course_id :integer # user_id :integer # created_at :datetime # updated_at :datetime # # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :course_user do end end
patrickspencer/compass-webapp
spec/factories/course_users.rb
Ruby
apache-2.0
334
/* * Copyright 2017-2022 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.iotdeviceadvisor; import javax.annotation.Generated; import com.amazonaws.services.iotdeviceadvisor.model.*; import com.amazonaws.client.AwsAsyncClientParams; import com.amazonaws.annotation.ThreadSafe; import java.util.concurrent.ExecutorService; /** * Client for accessing AWSIoTDeviceAdvisor asynchronously. Each asynchronous method will return a Java Future object * representing the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive * notification when an asynchronous operation completes. * <p> * <p> * Amazon Web Services IoT Core Device Advisor is a cloud-based, fully managed test capability for validating IoT * devices during device software development. Device Advisor provides pre-built tests that you can use to validate IoT * devices for reliable and secure connectivity with Amazon Web Services IoT Core before deploying devices to * production. By using Device Advisor, you can confirm that your devices can connect to Amazon Web Services IoT Core, * follow security best practices and, if applicable, receive software updates from IoT Device Management. You can also * download signed qualification reports to submit to the Amazon Web Services Partner Network to get your device * qualified for the Amazon Web Services Partner Device Catalog without the need to send your device in and wait for it * to be tested. * </p> */ @ThreadSafe @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AWSIoTDeviceAdvisorAsyncClient extends AWSIoTDeviceAdvisorClient implements AWSIoTDeviceAdvisorAsync { private static final int DEFAULT_THREAD_POOL_SIZE = 50; private final java.util.concurrent.ExecutorService executorService; public static AWSIoTDeviceAdvisorAsyncClientBuilder asyncBuilder() { return AWSIoTDeviceAdvisorAsyncClientBuilder.standard(); } /** * Constructs a new asynchronous client to invoke service methods on AWSIoTDeviceAdvisor using the specified * parameters. * * @param asyncClientParams * Object providing client parameters. */ AWSIoTDeviceAdvisorAsyncClient(AwsAsyncClientParams asyncClientParams) { this(asyncClientParams, false); } /** * Constructs a new asynchronous client to invoke service methods on AWSIoTDeviceAdvisor using the specified * parameters. * * @param asyncClientParams * Object providing client parameters. * @param endpointDiscoveryEnabled * true will enable endpoint discovery if the service supports it. */ AWSIoTDeviceAdvisorAsyncClient(AwsAsyncClientParams asyncClientParams, boolean endpointDiscoveryEnabled) { super(asyncClientParams, endpointDiscoveryEnabled); this.executorService = asyncClientParams.getExecutor(); } /** * Returns the executor service used by this client to execute async requests. * * @return The executor service used by this client to execute async requests. */ public ExecutorService getExecutorService() { return executorService; } @Override public java.util.concurrent.Future<CreateSuiteDefinitionResult> createSuiteDefinitionAsync(CreateSuiteDefinitionRequest request) { return createSuiteDefinitionAsync(request, null); } @Override public java.util.concurrent.Future<CreateSuiteDefinitionResult> createSuiteDefinitionAsync(final CreateSuiteDefinitionRequest request, final com.amazonaws.handlers.AsyncHandler<CreateSuiteDefinitionRequest, CreateSuiteDefinitionResult> asyncHandler) { final CreateSuiteDefinitionRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<CreateSuiteDefinitionResult>() { @Override public CreateSuiteDefinitionResult call() throws Exception { CreateSuiteDefinitionResult result = null; try { result = executeCreateSuiteDefinition(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<DeleteSuiteDefinitionResult> deleteSuiteDefinitionAsync(DeleteSuiteDefinitionRequest request) { return deleteSuiteDefinitionAsync(request, null); } @Override public java.util.concurrent.Future<DeleteSuiteDefinitionResult> deleteSuiteDefinitionAsync(final DeleteSuiteDefinitionRequest request, final com.amazonaws.handlers.AsyncHandler<DeleteSuiteDefinitionRequest, DeleteSuiteDefinitionResult> asyncHandler) { final DeleteSuiteDefinitionRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<DeleteSuiteDefinitionResult>() { @Override public DeleteSuiteDefinitionResult call() throws Exception { DeleteSuiteDefinitionResult result = null; try { result = executeDeleteSuiteDefinition(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<GetEndpointResult> getEndpointAsync(GetEndpointRequest request) { return getEndpointAsync(request, null); } @Override public java.util.concurrent.Future<GetEndpointResult> getEndpointAsync(final GetEndpointRequest request, final com.amazonaws.handlers.AsyncHandler<GetEndpointRequest, GetEndpointResult> asyncHandler) { final GetEndpointRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<GetEndpointResult>() { @Override public GetEndpointResult call() throws Exception { GetEndpointResult result = null; try { result = executeGetEndpoint(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<GetSuiteDefinitionResult> getSuiteDefinitionAsync(GetSuiteDefinitionRequest request) { return getSuiteDefinitionAsync(request, null); } @Override public java.util.concurrent.Future<GetSuiteDefinitionResult> getSuiteDefinitionAsync(final GetSuiteDefinitionRequest request, final com.amazonaws.handlers.AsyncHandler<GetSuiteDefinitionRequest, GetSuiteDefinitionResult> asyncHandler) { final GetSuiteDefinitionRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<GetSuiteDefinitionResult>() { @Override public GetSuiteDefinitionResult call() throws Exception { GetSuiteDefinitionResult result = null; try { result = executeGetSuiteDefinition(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<GetSuiteRunResult> getSuiteRunAsync(GetSuiteRunRequest request) { return getSuiteRunAsync(request, null); } @Override public java.util.concurrent.Future<GetSuiteRunResult> getSuiteRunAsync(final GetSuiteRunRequest request, final com.amazonaws.handlers.AsyncHandler<GetSuiteRunRequest, GetSuiteRunResult> asyncHandler) { final GetSuiteRunRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<GetSuiteRunResult>() { @Override public GetSuiteRunResult call() throws Exception { GetSuiteRunResult result = null; try { result = executeGetSuiteRun(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<GetSuiteRunReportResult> getSuiteRunReportAsync(GetSuiteRunReportRequest request) { return getSuiteRunReportAsync(request, null); } @Override public java.util.concurrent.Future<GetSuiteRunReportResult> getSuiteRunReportAsync(final GetSuiteRunReportRequest request, final com.amazonaws.handlers.AsyncHandler<GetSuiteRunReportRequest, GetSuiteRunReportResult> asyncHandler) { final GetSuiteRunReportRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<GetSuiteRunReportResult>() { @Override public GetSuiteRunReportResult call() throws Exception { GetSuiteRunReportResult result = null; try { result = executeGetSuiteRunReport(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<ListSuiteDefinitionsResult> listSuiteDefinitionsAsync(ListSuiteDefinitionsRequest request) { return listSuiteDefinitionsAsync(request, null); } @Override public java.util.concurrent.Future<ListSuiteDefinitionsResult> listSuiteDefinitionsAsync(final ListSuiteDefinitionsRequest request, final com.amazonaws.handlers.AsyncHandler<ListSuiteDefinitionsRequest, ListSuiteDefinitionsResult> asyncHandler) { final ListSuiteDefinitionsRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<ListSuiteDefinitionsResult>() { @Override public ListSuiteDefinitionsResult call() throws Exception { ListSuiteDefinitionsResult result = null; try { result = executeListSuiteDefinitions(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<ListSuiteRunsResult> listSuiteRunsAsync(ListSuiteRunsRequest request) { return listSuiteRunsAsync(request, null); } @Override public java.util.concurrent.Future<ListSuiteRunsResult> listSuiteRunsAsync(final ListSuiteRunsRequest request, final com.amazonaws.handlers.AsyncHandler<ListSuiteRunsRequest, ListSuiteRunsResult> asyncHandler) { final ListSuiteRunsRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<ListSuiteRunsResult>() { @Override public ListSuiteRunsResult call() throws Exception { ListSuiteRunsResult result = null; try { result = executeListSuiteRuns(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request) { return listTagsForResourceAsync(request, null); } @Override public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(final ListTagsForResourceRequest request, final com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler) { final ListTagsForResourceRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<ListTagsForResourceResult>() { @Override public ListTagsForResourceResult call() throws Exception { ListTagsForResourceResult result = null; try { result = executeListTagsForResource(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<StartSuiteRunResult> startSuiteRunAsync(StartSuiteRunRequest request) { return startSuiteRunAsync(request, null); } @Override public java.util.concurrent.Future<StartSuiteRunResult> startSuiteRunAsync(final StartSuiteRunRequest request, final com.amazonaws.handlers.AsyncHandler<StartSuiteRunRequest, StartSuiteRunResult> asyncHandler) { final StartSuiteRunRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<StartSuiteRunResult>() { @Override public StartSuiteRunResult call() throws Exception { StartSuiteRunResult result = null; try { result = executeStartSuiteRun(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<StopSuiteRunResult> stopSuiteRunAsync(StopSuiteRunRequest request) { return stopSuiteRunAsync(request, null); } @Override public java.util.concurrent.Future<StopSuiteRunResult> stopSuiteRunAsync(final StopSuiteRunRequest request, final com.amazonaws.handlers.AsyncHandler<StopSuiteRunRequest, StopSuiteRunResult> asyncHandler) { final StopSuiteRunRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<StopSuiteRunResult>() { @Override public StopSuiteRunResult call() throws Exception { StopSuiteRunResult result = null; try { result = executeStopSuiteRun(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request) { return tagResourceAsync(request, null); } @Override public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(final TagResourceRequest request, final com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler) { final TagResourceRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<TagResourceResult>() { @Override public TagResourceResult call() throws Exception { TagResourceResult result = null; try { result = executeTagResource(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request) { return untagResourceAsync(request, null); } @Override public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(final UntagResourceRequest request, final com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler) { final UntagResourceRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<UntagResourceResult>() { @Override public UntagResourceResult call() throws Exception { UntagResourceResult result = null; try { result = executeUntagResource(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } @Override public java.util.concurrent.Future<UpdateSuiteDefinitionResult> updateSuiteDefinitionAsync(UpdateSuiteDefinitionRequest request) { return updateSuiteDefinitionAsync(request, null); } @Override public java.util.concurrent.Future<UpdateSuiteDefinitionResult> updateSuiteDefinitionAsync(final UpdateSuiteDefinitionRequest request, final com.amazonaws.handlers.AsyncHandler<UpdateSuiteDefinitionRequest, UpdateSuiteDefinitionResult> asyncHandler) { final UpdateSuiteDefinitionRequest finalRequest = beforeClientExecution(request); return executorService.submit(new java.util.concurrent.Callable<UpdateSuiteDefinitionResult>() { @Override public UpdateSuiteDefinitionResult call() throws Exception { UpdateSuiteDefinitionResult result = null; try { result = executeUpdateSuiteDefinition(finalRequest); } catch (Exception ex) { if (asyncHandler != null) { asyncHandler.onError(ex); } throw ex; } if (asyncHandler != null) { asyncHandler.onSuccess(finalRequest, result); } return result; } }); } /** * Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending * asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should * call {@code getExecutorService().shutdown()} followed by {@code getExecutorService().awaitTermination()} prior to * calling this method. */ @Override public void shutdown() { super.shutdown(); executorService.shutdownNow(); } }
aws/aws-sdk-java
aws-java-sdk-iotdeviceadvisor/src/main/java/com/amazonaws/services/iotdeviceadvisor/AWSIoTDeviceAdvisorAsyncClient.java
Java
apache-2.0
22,034
/* * Copyright 2019 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. */ package com.google.devtools.intellij.protoeditor.ide.documentation; import com.google.devtools.intellij.protoeditor.lang.psi.PbCommentOwner; import com.google.devtools.intellij.protoeditor.lang.psi.util.PbCommentUtil; import com.intellij.lang.documentation.AbstractDocumentationProvider; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; import java.util.List; import org.jetbrains.annotations.Nullable; /** A {@link com.intellij.lang.documentation.DocumentationProvider} for proto elements. */ public class PbDocumentationProvider extends AbstractDocumentationProvider { @Nullable @Override public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { return null; } @Nullable @Override public List<String> getUrlFor(PsiElement element, PsiElement originalElement) { return null; } @Nullable @Override public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) { if (!(element instanceof PbCommentOwner)) { return null; } PbCommentOwner owner = (PbCommentOwner) element; List<PsiComment> comments = owner.getComments(); if (comments.isEmpty()) { return null; } StringBuilder commentBuilder = new StringBuilder("<pre>"); for (String line : PbCommentUtil.extractText(comments)) { commentBuilder.append(StringUtil.escapeXml(line)); commentBuilder.append("\n"); } commentBuilder.append("</pre>"); return commentBuilder.toString(); } @Nullable @Override public PsiElement getDocumentationElementForLink( PsiManager psiManager, String link, PsiElement context) { return null; } }
google/intellij-protocol-buffer-editor
core/src/main/java/com/google/devtools/intellij/protoeditor/ide/documentation/PbDocumentationProvider.java
Java
apache-2.0
2,354
package com.mnknowledge.dp.behavioral.observer.newsfeed; public class User implements Observer { private String name; private String article; private Subject newsFeed; public User(String name) { super(); this.name = name; } public void subscribe(Subject newsFeed) { newsFeed.registerObserver(this); this.newsFeed = newsFeed; article = "No New Article!"; } @Override public void update() { System.out.println("State change reported by Subject."); article = (String) newsFeed.getUpdate(); } public String getArticle() { return article; } public String getName() { return name; } }
stapetro/mnk_designpatterns
dpsamples/src/main/java/com/mnknowledge/dp/behavioral/observer/newsfeed/User.java
Java
apache-2.0
714
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ads.googleads.migration.campaignmanagement; import com.beust.jcommander.Parameter; import com.google.ads.googleads.lib.GoogleAdsClient; import com.google.ads.googleads.migration.utils.ArgumentNames; import com.google.ads.googleads.migration.utils.CodeSampleParams; import com.google.ads.googleads.v10.common.ExpandedTextAdInfo; import com.google.ads.googleads.v10.common.KeywordInfo; import com.google.ads.googleads.v10.common.ManualCpc; import com.google.ads.googleads.v10.enums.AdGroupAdStatusEnum.AdGroupAdStatus; import com.google.ads.googleads.v10.enums.AdGroupCriterionStatusEnum.AdGroupCriterionStatus; import com.google.ads.googleads.v10.enums.AdGroupStatusEnum.AdGroupStatus; import com.google.ads.googleads.v10.enums.AdGroupTypeEnum.AdGroupType; import com.google.ads.googleads.v10.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType; import com.google.ads.googleads.v10.enums.BudgetDeliveryMethodEnum.BudgetDeliveryMethod; import com.google.ads.googleads.v10.enums.CampaignStatusEnum.CampaignStatus; import com.google.ads.googleads.v10.enums.KeywordMatchTypeEnum.KeywordMatchType; import com.google.ads.googleads.v10.errors.GoogleAdsError; import com.google.ads.googleads.v10.errors.GoogleAdsException; import com.google.ads.googleads.v10.resources.Ad; import com.google.ads.googleads.v10.resources.AdGroup; import com.google.ads.googleads.v10.resources.AdGroupAd; import com.google.ads.googleads.v10.resources.AdGroupCriterion; import com.google.ads.googleads.v10.resources.Campaign; import com.google.ads.googleads.v10.resources.Campaign.NetworkSettings; import com.google.ads.googleads.v10.resources.CampaignBudget; import com.google.ads.googleads.v10.services.AdGroupAdOperation; import com.google.ads.googleads.v10.services.AdGroupAdServiceClient; import com.google.ads.googleads.v10.services.AdGroupCriterionOperation; import com.google.ads.googleads.v10.services.AdGroupCriterionServiceClient; import com.google.ads.googleads.v10.services.AdGroupOperation; import com.google.ads.googleads.v10.services.AdGroupServiceClient; import com.google.ads.googleads.v10.services.CampaignBudgetOperation; import com.google.ads.googleads.v10.services.CampaignBudgetServiceClient; import com.google.ads.googleads.v10.services.CampaignOperation; import com.google.ads.googleads.v10.services.CampaignServiceClient; import com.google.ads.googleads.v10.services.GoogleAdsRow; import com.google.ads.googleads.v10.services.GoogleAdsServiceClient; import com.google.ads.googleads.v10.services.GoogleAdsServiceClient.SearchPagedResponse; import com.google.ads.googleads.v10.services.MutateAdGroupAdResult; import com.google.ads.googleads.v10.services.MutateAdGroupAdsResponse; import com.google.ads.googleads.v10.services.MutateAdGroupCriteriaResponse; import com.google.ads.googleads.v10.services.MutateAdGroupCriterionResult; import com.google.ads.googleads.v10.services.MutateAdGroupsResponse; import com.google.ads.googleads.v10.services.MutateCampaignBudgetsResponse; import com.google.ads.googleads.v10.services.MutateCampaignsResponse; import com.google.ads.googleads.v10.services.SearchGoogleAdsRequest; import com.google.ads.googleads.v10.utils.ResourceNames; import com.google.common.collect.ImmutableList; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.joda.time.DateTime; /** * This code example is the last in a series of code examples that shows how to create a Search * campaign using the AdWords API, and then migrate it to the Google Ads API one functionality at a * time. See Step0 through Step5 for code examples in various stages of migration. * * <p>This code example represents the final state, where all the functionality - create a campaign * budget, a search campaign, an ad group, keywords, and expanded text ads have all been migrated to * using the Google Ads API. The AdWords API is not used. */ public class CreateCompleteCampaignGoogleAdsApiOnly { private static final int PAGE_SIZE = 1_000; private static final int NUMBER_OF_ADS = 5; private static final List<String> KEYWORDS_TO_ADD = Arrays.asList("mars cruise", "space hotel"); private static class CreateCompleteCampaignGoogleAdsApiOnlyParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true) private Long customerId; } public static void main(String[] args) { CreateCompleteCampaignGoogleAdsApiOnlyParams params = new CreateCompleteCampaignGoogleAdsApiOnlyParams(); if (!params.parseArguments(args)) { // Either pass the required parameters for this example on the command line, or insert them // into the code here. See the parameter class definition above for descriptions. params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE"); } // Initializes the Google Ads client. GoogleAdsClient googleAdsClient; try { googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build(); } catch (FileNotFoundException fnfe) { System.err.printf( "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe); return; } catch (IOException ioe) { System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe); return; } try { new CreateCompleteCampaignGoogleAdsApiOnly().runExample(googleAdsClient, params.customerId); } catch (GoogleAdsException gae) { // GoogleAdsException is the base class for most exceptions thrown by an API request. // Instances of this exception have a message and a GoogleAdsFailure that contains a // collection of GoogleAdsErrors that indicate the underlying causes of the // GoogleAdsException. System.err.printf( "Request ID %s failed due to GoogleAdsException. Underlying errors:%n", gae.getRequestId()); int i = 0; for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) { System.err.printf(" Error %d: %s%n", i++, googleAdsError); } } } /** * Runs the example. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private void runExample(GoogleAdsClient googleAdsClient, long customerId) { CampaignBudget budget = createBudget(googleAdsClient, customerId); Campaign campaign = createCampaign(googleAdsClient, customerId, budget); AdGroup adGroup = createAdGroup(googleAdsClient, customerId, campaign); createTextAds(googleAdsClient, customerId, adGroup, NUMBER_OF_ADS); createKeywords(googleAdsClient, customerId, adGroup, KEYWORDS_TO_ADD); } /** * Creates a budget. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private CampaignBudget createBudget(GoogleAdsClient googleAdsClient, long customerId) { // Creates the budget. CampaignBudget budget = CampaignBudget.newBuilder() .setName("Interplanetary Cruise Budget #" + System.currentTimeMillis()) .setDeliveryMethod(BudgetDeliveryMethod.STANDARD) .setAmountMicros(10_000_000) .build(); // Creates the operation. CampaignBudgetOperation op = CampaignBudgetOperation.newBuilder().setCreate(budget).build(); // Gets the CampaignBudget service. try (CampaignBudgetServiceClient campaignBudgetServiceClient = googleAdsClient.getLatestVersion().createCampaignBudgetServiceClient()) { // Adds the budget. MutateCampaignBudgetsResponse response = campaignBudgetServiceClient.mutateCampaignBudgets( Long.toString(customerId), ImmutableList.of(op)); String budgetResourceName = response.getResults(0).getResourceName(); // Retrieves the budget. CampaignBudget newBudget = getBudget(googleAdsClient, customerId, budgetResourceName); // Displays the results. System.out.printf( "Budget with ID %s and name '%s' was created.%n", newBudget.getId(), newBudget.getName()); return newBudget; } } /** * Retrieves the campaign budget. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param budgetResourceName resource name of the new campaign budget. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private CampaignBudget getBudget( GoogleAdsClient googleAdsClient, long customerId, String budgetResourceName) { // Gets the GoogleAdsService. try (GoogleAdsServiceClient googleAdsServiceClient = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { // Creates the request. SearchGoogleAdsRequest request = SearchGoogleAdsRequest.newBuilder() .setCustomerId(Long.toString(customerId)) .setPageSize(PAGE_SIZE) .setQuery( String.format( "SELECT campaign_budget.id, campaign_budget.name, " + "campaign_budget.resource_name FROM campaign_budget " + "WHERE campaign_budget.resource_name = '%s'", budgetResourceName)) .build(); // Retrieves the budget. SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request); return searchPagedResponse.getPage().getResponse().getResults(0).getCampaignBudget(); } } /** * Creates a campaign. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param budget the budget for the campaign. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private Campaign createCampaign( GoogleAdsClient googleAdsClient, long customerId, CampaignBudget budget) { String budgetResourceName = ResourceNames.campaignBudget(customerId, budget.getId()); // Configures the campaign network options NetworkSettings networkSettings = NetworkSettings.newBuilder() .setTargetGoogleSearch(true) .setTargetSearchNetwork(true) .setTargetContentNetwork(false) .setTargetPartnerSearchNetwork(false) .build(); // Creates the campaign. Campaign campaign = Campaign.newBuilder() .setName("Interplanetary Cruise #" + System.currentTimeMillis()) .setAdvertisingChannelType(AdvertisingChannelType.SEARCH) // Recommendation: Set the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve .setStatus(CampaignStatus.PAUSED) // Sets the bidding strategy and budget. .setManualCpc(ManualCpc.newBuilder().build()) .setCampaignBudget(budgetResourceName) // Adds the networkSettings configured above. .setNetworkSettings(networkSettings) // Optional: sets the start & end dates. .setStartDate(new DateTime().plusDays(1).toString("yyyyMMdd")) .setEndDate(new DateTime().plusDays(30).toString("yyyyMMdd")) .build(); // Creates the operation. CampaignOperation op = CampaignOperation.newBuilder().setCreate(campaign).build(); // Gets the Campaign service. try (CampaignServiceClient campaignServiceClient = googleAdsClient.getLatestVersion().createCampaignServiceClient()) { // Adds the campaign. MutateCampaignsResponse response = campaignServiceClient.mutateCampaigns(Long.toString(customerId), ImmutableList.of(op)); String campaignResourceName = response.getResults(0).getResourceName(); // Retrieves the campaign. Campaign newCampaign = getCampaign(googleAdsClient, customerId, campaignResourceName); // Displays the results. System.out.printf( "Campaign with ID %s and name '%s' was created.%n", newCampaign.getId(), newCampaign.getName()); return newCampaign; } } /** * Retrieves the campaign. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param campaignResourceName resource name of the new campaign. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private Campaign getCampaign( GoogleAdsClient googleAdsClient, long customerId, String campaignResourceName) { // Gets the GoogleAdsService. try (GoogleAdsServiceClient googleAdsServiceClient = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { // Creates the request. SearchGoogleAdsRequest request = SearchGoogleAdsRequest.newBuilder() .setCustomerId(Long.toString(customerId)) .setPageSize(PAGE_SIZE) .setQuery( String.format( "SELECT campaign.id, campaign.name, campaign.resource_name " + "FROM campaign " + "WHERE campaign.resource_name = '%s'", campaignResourceName)) .build(); // Retrieves the campaign. SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request); return searchPagedResponse.getPage().getResponse().getResults(0).getCampaign(); } } /** * Creates an ad group. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param campaign the campaign for the ad group. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private AdGroup createAdGroup( GoogleAdsClient googleAdsClient, long customerId, Campaign campaign) { String campaignResourceName = ResourceNames.campaign(customerId, campaign.getId()); // Creates the ad group, setting an optional CPC value. AdGroup adGroup = AdGroup.newBuilder() .setName("Earth to Mars Cruises #" + System.currentTimeMillis()) .setStatus(AdGroupStatus.ENABLED) .setCampaign(campaignResourceName) .setType(AdGroupType.SEARCH_STANDARD) .setCpcBidMicros(500_000L) .build(); // Creates the operation. AdGroupOperation op = AdGroupOperation.newBuilder().setCreate(adGroup).build(); // Gets the AdGroup Service. try (AdGroupServiceClient adGroupServiceClient = googleAdsClient.getLatestVersion().createAdGroupServiceClient()) { // Adds the AdGroup. MutateAdGroupsResponse response = adGroupServiceClient.mutateAdGroups(Long.toString(customerId), ImmutableList.of(op)); String adGroupResourceName = response.getResults(0).getResourceName(); // Retrieves the AdGroup. AdGroup newAdGroup = getAdGroup(googleAdsClient, customerId, adGroupResourceName); // Displays the results. System.out.printf( "Ad group with ID %s and name '%s' was created.%n", newAdGroup.getId(), newAdGroup.getName()); return newAdGroup; } } /** * Retrieves the ad group. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param adGroupResourceName resource name of the new ad group. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private AdGroup getAdGroup( GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName) { // Gets the GoogleAdsService. try (GoogleAdsServiceClient googleAdsServiceClient = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { // Creates the request. SearchGoogleAdsRequest request = SearchGoogleAdsRequest.newBuilder() .setCustomerId(Long.toString(customerId)) .setPageSize(PAGE_SIZE) .setQuery( String.format( "SELECT ad_group.id, ad_group.name, ad_group.resource_name " + "FROM ad_group WHERE ad_group.resource_name = '%s'", adGroupResourceName)) .build(); // Retrieves the AdGroup. SearchPagedResponse response = googleAdsServiceClient.search(request); return response.getPage().getResponse().getResults(0).getAdGroup(); } } /** * Creates text ads. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param adGroup the ad group for the text ad. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private List<AdGroupAd> createTextAds( GoogleAdsClient googleAdsClient, long customerId, AdGroup adGroup, int numberOfAds) { String adGroupResourceName = ResourceNames.adGroup(customerId, adGroup.getId()); List<AdGroupAdOperation> operations = new ArrayList<>(); for (int i = 0; i < numberOfAds; i++) { // Creates the text ad AdGroupAd adgroupAd = AdGroupAd.newBuilder() .setAdGroup(adGroupResourceName) .setStatus(AdGroupAdStatus.PAUSED) .setAd( Ad.newBuilder() .addFinalUrls("http://www.example.com/" + String.valueOf(i)) .setExpandedTextAd( ExpandedTextAdInfo.newBuilder() .setDescription("Buy your tickets now!") .setHeadlinePart1("Cruise #" + i + " to Mars") .setHeadlinePart2("Best Space Cruise Line") .setPath1("path1") .setPath2("path2") .build())) .build(); // Creates the operation. AdGroupAdOperation op = AdGroupAdOperation.newBuilder().setCreate(adgroupAd).build(); operations.add(op); } // Gets the AdGroupAd service. try (AdGroupAdServiceClient adGroupAdServiceClient = googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) { // Adds the text ads. MutateAdGroupAdsResponse response = adGroupAdServiceClient.mutateAdGroupAds(Long.toString(customerId), operations); System.out.printf("Added %d text ads:%n", response.getResultsCount()); // Creates a list of the text ad resource names. List<String> newAdGroupAdResourceNames = new ArrayList<>(); for (MutateAdGroupAdResult result : response.getResultsList()) { newAdGroupAdResourceNames.add(result.getResourceName()); } // Retrieves the expanded text ads. List<AdGroupAd> newAdGroupAds = getAdGroupAds(googleAdsClient, customerId, newAdGroupAdResourceNames); for (AdGroupAd newAdGroupAd : newAdGroupAds) { Ad ad = newAdGroupAd.getAd(); ExpandedTextAdInfo expandedTextAdInfo = ad.getExpandedTextAd(); // Displays the results. System.out.printf( "Expanded text ad with ID %s, status '%s', " + "and headline '%s - %s' was created in ad group with ID %s.%n", ad.getId(), newAdGroupAd.getStatus(), expandedTextAdInfo.getHeadlinePart1(), expandedTextAdInfo.getHeadlinePart2(), adGroup.getId()); } return newAdGroupAds; } } /** * Retrieves the ad group ads. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param newResourceNames resource names of the new ad group ad. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private List<AdGroupAd> getAdGroupAds( GoogleAdsClient googleAdsClient, long customerId, List<String> newResourceNames) { // Gets the GoogleAdsService. try (GoogleAdsServiceClient googleAdsServiceClient = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { // Creates the request. SearchGoogleAdsRequest request = SearchGoogleAdsRequest.newBuilder() .setCustomerId(Long.toString(customerId)) .setPageSize(PAGE_SIZE) .setQuery( String.format( "SELECT " + "ad_group.id, " + "ad_group_ad.ad.id, " + "ad_group_ad.ad.expanded_text_ad.headline_part1, " + "ad_group_ad.ad.expanded_text_ad.headline_part2, " + "ad_group_ad.status, " + "ad_group_ad.ad.final_urls, " + "ad_group_ad.resource_name " + "FROM ad_group_ad " + "WHERE ad_group_ad.resource_name IN (%s)", String.join( ", ", newResourceNames.stream() .map(resourceName -> String.format("'%s'", resourceName)) .collect(Collectors.toList())))) .build(); // Retrieves the ad group ads SearchPagedResponse response = googleAdsServiceClient.search(request); // Creates and returns a list of the ad group ads. List<AdGroupAd> adGroupAds = new ArrayList<>(); for (GoogleAdsRow googleAdsRow : response.iterateAll()) { adGroupAds.add(googleAdsRow.getAdGroupAd()); } return adGroupAds; } } /** * Creates keywords ad group criteria. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param adGroup the ad group for the new criteria. * @param keywordsToAdd the keywords to add to the text ads. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private List<AdGroupCriterion> createKeywords( GoogleAdsClient googleAdsClient, long customerId, AdGroup adGroup, List<String> keywordsToAdd) { String adGroupResourceName = ResourceNames.adGroup(customerId, adGroup.getId()); List<AdGroupCriterionOperation> operations = new ArrayList<>(); for (String keywordText : keywordsToAdd) { // Creates the keyword criterion AdGroupCriterion adGroupCriterion = AdGroupCriterion.newBuilder() .setAdGroup(adGroupResourceName) .setStatus(AdGroupCriterionStatus.ENABLED) .setKeyword( KeywordInfo.newBuilder() .setText(keywordText) .setMatchType(KeywordMatchType.EXACT) .build()) .build(); // Creates the operation. AdGroupCriterionOperation op = AdGroupCriterionOperation.newBuilder().setCreate(adGroupCriterion).build(); operations.add(op); } // Gets the AdGroupCriterionService. try (AdGroupCriterionServiceClient adGroupCriterionServiceClient = googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) { // Adds the keywords MutateAdGroupCriteriaResponse response = adGroupCriterionServiceClient.mutateAdGroupCriteria( Long.toString(customerId), operations); System.out.printf("Added %d keywords:%n", response.getResultsCount()); // Creates a list of new keyword resource names List<String> newCriteriaResourceNames = new ArrayList<>(); for (MutateAdGroupCriterionResult result : response.getResultsList()) { newCriteriaResourceNames.add(result.getResourceName()); } // Retrieves the newly created keywords. List<AdGroupCriterion> newCriteria = getKeywords(googleAdsClient, customerId, newCriteriaResourceNames); // Displays the results. for (AdGroupCriterion newCriterion : newCriteria) { System.out.printf( "Keyword with text '%s', ID %s, and match type '%s' was retrieved for ad group '%s'.%n", newCriterion.getKeyword().getText(), newCriterion.getCriterionId(), newCriterion.getKeyword().getMatchType(), adGroup.getName()); } return newCriteria; } } /** * Retrieves the keyword ad group criteria. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param newResourceNames resource names of the new ad group criteria. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private List<AdGroupCriterion> getKeywords( GoogleAdsClient googleAdsClient, long customerId, List<String> newResourceNames) { // Gets the GoogleAdsService. try (GoogleAdsServiceClient googleAdsServiceClient = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { // Creates the request. SearchGoogleAdsRequest request = SearchGoogleAdsRequest.newBuilder() .setCustomerId(Long.toString(customerId)) .setPageSize(PAGE_SIZE) // Creates the search query. .setQuery( String.format( "SELECT " + "ad_group.id, " + "ad_group.status, " + "ad_group_criterion.criterion_id, " + "ad_group_criterion.keyword.text, " + "ad_group_criterion.keyword.match_type " + "FROM ad_group_criterion " + "WHERE ad_group_criterion.type = 'KEYWORD' " + "AND ad_group.status = 'ENABLED' " + "AND ad_group_criterion.status IN ('ENABLED', 'PAUSED') " + "AND ad_group_criterion.resource_name IN (%s) ", String.join( ", ", newResourceNames.stream() .map(resourceName -> String.format("'%s'", resourceName)) .collect(Collectors.toList())))) .build(); // Retrieves the adGroupCriteria. SearchPagedResponse response = googleAdsServiceClient.search(request); // Creates and returns a list of adGroupCriteria List<AdGroupCriterion> adGroupCriteria = new ArrayList<>(); for (GoogleAdsRow googleAdsRow : response.iterateAll()) { adGroupCriteria.add(googleAdsRow.getAdGroupCriterion()); } return adGroupCriteria; } } }
googleads/google-ads-java
google-ads-migration-examples/src/main/java/com/google/ads/googleads/migration/campaignmanagement/CreateCompleteCampaignGoogleAdsApiOnly.java
Java
apache-2.0
27,574