hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
8865fb476867b6e3edc39cb6480caf078a47b76d | 5,715 | package org.apereo.cas.web.flow;
import org.apereo.cas.AbstractCentralAuthenticationServiceTests;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.apereo.cas.web.support.CookieRetrievingCookieGenerator;
import org.apereo.cas.CasProtocolConstants;
import org.apereo.cas.web.support.WebUtils;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.test.MockRequestContext;
import javax.servlet.http.Cookie;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* @author Marvin S. Addison
* @since 3.4.0
*/
public class SendTicketGrantingTicketActionTests extends AbstractCentralAuthenticationServiceTests {
private SendTicketGrantingTicketAction action;
private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;
private MockRequestContext context;
@Before
public void onSetUp() throws Exception {
this.ticketGrantingTicketCookieGenerator = new CookieRetrievingCookieGenerator();
ticketGrantingTicketCookieGenerator.setCookieName("TGT");
this.action = new SendTicketGrantingTicketAction();
this.action.setCentralAuthenticationService(getCentralAuthenticationService());
this.action.setTicketGrantingTicketCookieGenerator(ticketGrantingTicketCookieGenerator);
this.action.setServicesManager(getServicesManager());
this.action.setCreateSsoSessionCookieOnRenewAuthentications(true);
this.action.afterPropertiesSet();
this.context = new MockRequestContext();
}
@Test
public void verifyNoTgtToSet() throws Exception {
this.context.setExternalContext(new ServletExternalContext(new MockServletContext(),
new MockHttpServletRequest(), new MockHttpServletResponse()));
assertEquals("success", this.action.execute(this.context).getId());
}
@Test
public void verifyTgtToSet() throws Exception {
final MockHttpServletResponse response = new MockHttpServletResponse();
final MockHttpServletRequest request = new MockHttpServletRequest();
final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
when(tgt.getId()).thenReturn("test");
WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
this.context.setExternalContext(new ServletExternalContext(new MockServletContext(),
request, response));
assertEquals("success", this.action.execute(this.context).getId());
request.setCookies(response.getCookies());
assertEquals(tgt.getId(), this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
}
@Test
public void verifyTgtToSetRemovingOldTgt() throws Exception {
final MockHttpServletResponse response = new MockHttpServletResponse();
final MockHttpServletRequest request = new MockHttpServletRequest();
final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
when(tgt.getId()).thenReturn("test");
request.setCookies(new Cookie("TGT", "test5"));
WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
assertEquals("success", this.action.execute(this.context).getId());
request.setCookies(response.getCookies());
assertEquals(tgt.getId(), this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
}
@Test
public void verifySsoSessionCookieOnRenewAsParameter() throws Exception {
final MockHttpServletResponse response = new MockHttpServletResponse();
final MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(CasProtocolConstants.PARAMETER_RENEW, "true");
final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
when(tgt.getId()).thenReturn("test");
request.setCookies(new Cookie("TGT", "test5"));
WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
this.action.setCreateSsoSessionCookieOnRenewAuthentications(false);
assertEquals("success", this.action.execute(this.context).getId());
assertEquals(0, response.getCookies().length);
}
@Test
public void verifySsoSessionCookieOnServiceSsoDisallowed() throws Exception {
final MockHttpServletResponse response = new MockHttpServletResponse();
final MockHttpServletRequest request = new MockHttpServletRequest();
final WebApplicationService svc = mock(WebApplicationService.class);
when(svc.getId()).thenReturn("TestSsoFalse");
final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
when(tgt.getId()).thenReturn("test");
request.setCookies(new Cookie("TGT", "test5"));
WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
this.context.getFlowScope().put("service", svc);
this.action.setCreateSsoSessionCookieOnRenewAuthentications(false);
assertEquals("success", this.action.execute(this.context).getId());
assertEquals(0, response.getCookies().length);
}
}
| 45.72 | 113 | 0.753456 |
32f45d81a091800b19ef85afa20f0e94038ac6c7 | 652 | package controller.model;
public class Wrapper {
//*******************************Class fields******************************//
private int opnum; //Contains the number of operation for the server
private String CData; //Contains json in String format
//*******************************Class Methods******************************//
//Setters and Getters
public int getOpnum() {
return opnum;
}
public void setOpnum(int opnum) {
this.opnum = opnum;
}
public String getCData() {
return CData;
}
public void setCData(String CData) {
this.CData = CData;
}
}
| 19.757576 | 82 | 0.492331 |
ae7a99319cc3d085578e07dc3b0659e9694a958b | 8,726 | /*
* Copyright 2022 LINE Corporation
*
* LINE Corporation 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:
*
* 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.linecorp.armeria.internal.server.graphql;
import static com.linecorp.armeria.internal.server.graphql.GraphqlDocServicePlugin.DEFAULT_METHOD_NAME;
import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.hamcrest.CustomTypeSafeMatcher;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.linecorp.armeria.client.WebClient;
import com.linecorp.armeria.common.AggregatedHttpResponse;
import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.internal.testing.TestUtil;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.docs.DocService;
import com.linecorp.armeria.server.docs.DocServiceFilter;
import com.linecorp.armeria.server.docs.FieldRequirement;
import com.linecorp.armeria.server.docs.ServiceSpecification;
import com.linecorp.armeria.server.docs.TypeSignature;
import com.linecorp.armeria.server.graphql.GraphqlService;
import com.linecorp.armeria.testing.junit5.server.ServerExtension;
import graphql.schema.DataFetcher;
class GraphqlDocServiceTest {
private static final ObjectMapper mapper = new ObjectMapper();
@RegisterExtension
static ServerExtension server = new ServerExtension() {
@Override
protected void configure(ServerBuilder sb) throws Exception {
if (TestUtil.isDocServiceDemoMode()) {
sb.http(8080);
}
final File graphqlSchemaFile =
new File(getClass().getResource("/test.graphqls").toURI());
final GraphqlService service =
GraphqlService.builder()
.schemaFile(graphqlSchemaFile)
.runtimeWiring(c -> {
final DataFetcher<String> bar = dataFetcher("bar");
c.type("Query",
typeWiring -> typeWiring.dataFetcher("foo", bar));
})
.build();
sb.service("/graphql", service);
sb.serviceUnder("/docs",
DocService.builder().build());
sb.serviceUnder("/excludeAll",
DocService.builder()
.exclude(DocServiceFilter.ofGraphql())
.build());
sb.serviceUnder("/excludeAll2",
DocService.builder()
.exclude(DocServiceFilter.ofMethodName(DEFAULT_METHOD_NAME))
.build());
}
};
private static DataFetcher<String> dataFetcher(String value) {
return environment -> value;
}
@Test
void jsonSpecification() throws InterruptedException {
if (TestUtil.isDocServiceDemoMode()) {
Thread.sleep(Long.MAX_VALUE);
}
final WebClient client = WebClient.of(server.httpUri());
final AggregatedHttpResponse res = client.get("/docs/specification.json").aggregate().join();
assertThat(res.status()).isEqualTo(HttpStatus.OK);
assertThat(res.headers().get(HttpHeaderNames.CACHE_CONTROL)).isEqualTo("no-cache, must-revalidate");
assertThatJson(res.contentUtf8())
.when(IGNORING_ARRAY_ORDER)
.node("services[0].name").isEqualTo("com.linecorp.armeria.server.graphql.DefaultGraphqlService")
.node("services[0].methods[0].name").isEqualTo(DEFAULT_METHOD_NAME)
.node("services[0].methods[0].returnTypeSignature").isEqualTo("json")
.node("services[0].methods[0].parameters[0]").matches(
new CustomTypeSafeMatcher<Map<String, Object>>("query") {
@Override
protected boolean matchesSafely(Map<String, Object> fieldInfo) {
assertThatFieldInfo(fieldInfo, "query", FieldRequirement.REQUIRED,
TypeSignature.ofBase("string"));
return true;
}
})
.node("services[0].methods[0].parameters[1]").matches(
new CustomTypeSafeMatcher<Map<String, Object>>("operationName") {
@Override
protected boolean matchesSafely(Map<String, Object> fieldInfo) {
assertThatFieldInfo(fieldInfo, "operationName", FieldRequirement.OPTIONAL,
TypeSignature.ofBase("string"));
return true;
}
})
.node("services[0].methods[0].parameters[2]").matches(
new CustomTypeSafeMatcher<Map<String, Object>>("variables") {
@Override
protected boolean matchesSafely(Map<String, Object> fieldInfo) {
assertThatFieldInfo(fieldInfo, "variables", FieldRequirement.OPTIONAL,
TypeSignature.ofBase("map"));
return true;
}
})
.node("services[0].methods[0].parameters[3]").matches(
new CustomTypeSafeMatcher<Map<String, Object>>("extensions") {
@Override
protected boolean matchesSafely(Map<String, Object> fieldInfo) {
assertThatFieldInfo(fieldInfo, "extensions", FieldRequirement.OPTIONAL,
TypeSignature.ofBase("map"));
return true;
}
})
.node("services[0].methods[0].endpoints[0].pathMapping").isEqualTo("exact:/graphql");
}
private static void assertThatFieldInfo(Map<String, Object> fieldInfo, String name,
FieldRequirement fieldRequirement, TypeSignature typeSignature) {
assertThat(fieldInfo.get("name")).isEqualTo(name);
assertThat(fieldInfo.get("requirement")).isEqualTo(fieldRequirement.name());
assertThat(fieldInfo.get("typeSignature")).isEqualTo(typeSignature.signature());
}
@ParameterizedTest
@ValueSource(strings = { "/excludeAll", "/excludeAll2" })
void excludeAllServices(String path) throws IOException {
final WebClient client = WebClient.of(server.httpUri());
final AggregatedHttpResponse res = client.get(path + "/specification.json").aggregate().join();
assertThat(res.status()).isEqualTo(HttpStatus.OK);
final JsonNode actualJson = mapper.readTree(res.contentUtf8());
final JsonNode expectedJson = mapper.valueToTree(new ServiceSpecification(ImmutableList.of(),
ImmutableList.of(),
ImmutableList.of(),
ImmutableList.of(),
ImmutableList.of()));
assertThatJson(actualJson).isEqualTo(expectedJson);
}
}
| 51.329412 | 112 | 0.577813 |
000b120cf2c515085461d14bcd245ce4a1f5fce0 | 322 | package sch.frog.calculator.compile.lexical;
import sch.frog.calculator.compile.IWord;
import sch.frog.calculator.compile.syntax.ISyntaxNodeGenerator;
/**
* 词法分析的token
*/
public interface IToken extends IWord {
/**
* 获取词法节点生成器
* @return
*/
ISyntaxNodeGenerator getSyntaxNodeGenerator();
}
| 17.888889 | 63 | 0.71118 |
fe7ae562d11367976a1dd693514f404b0c5f6023 | 2,386 | package org.javarosa.engine.xml;
import org.javarosa.core.model.data.UncastData;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.xml.util.InvalidStructureException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Hashtable;
/**
* @author ctsims
*
*/
public class TreeElementParser extends ElementParser<TreeElement> {
final int multiplicity;
final String instanceId;
public TreeElementParser(KXmlParser parser, int multiplicity, String instanceId) {
super(parser);
this.multiplicity = multiplicity;
this.instanceId = instanceId;
}
@Override
public TreeElement parse() throws InvalidStructureException, IOException, XmlPullParserException {
int depth = parser.getDepth();
TreeElement element = new TreeElement(parser.getName(), multiplicity);
element.setInstanceName(instanceId);
for (int i = 0 ; i < parser.getAttributeCount(); ++i) {
element.setAttribute(parser.getAttributeNamespace(i), parser.getAttributeName(i), parser.getAttributeValue(i));
}
Hashtable<String, Integer> multiplicities = new Hashtable<>();
//NOTE: We never expect this to be the exit condition
while (parser.getDepth() >= depth) {
switch (this.nextNonWhitespace()) {
case KXmlParser.START_TAG:
String name = parser.getName();
int val;
if (multiplicities.containsKey(name)) {
val = multiplicities.get(name) + 1;
} else {
val = 0;
}
multiplicities.put(name, val);
TreeElement kid = new TreeElementParser(parser, val, instanceId).parse();
element.addChild(kid);
break;
case KXmlParser.END_TAG:
return element;
case KXmlParser.TEXT:
element.setValue(new UncastData(parser.getText().trim()));
break;
default:
throw new InvalidStructureException("Exception while trying to parse an XML Tree, got something other than tags and text", parser);
}
}
return element;
}
}
| 36.151515 | 151 | 0.603521 |
ba1b001851254435e2c750e4e996f2e25e5b2c85 | 3,424 | /**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.github.liyue2008.rpc.serialize;
import com.github.liyue2008.rpc.spi.ServiceSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @author LiYue
* Date: 2019/9/20
*/
@SuppressWarnings("unchecked")
public class SerializeSupport {
private static final Logger logger = LoggerFactory.getLogger(SerializeSupport.class);
/**
* 序列化对象和序列化实现的映射关系
*
* key: 序列化对象类型
* value: 序列化实现
*/
private static Map<Class<?>, Serializer<?>> serializerMap = new HashMap<>();
/**
* 序列化实现和序列化类型的映射关系
*
* key: 序列化实现类型,枚举数字表示
* value: 序列化对象类型
*/
private static Map<Byte/**/, Class<?>/**/> typeMap = new HashMap<>();
static {
for (Serializer serializer : ServiceSupport.loadAll(Serializer.class)) {
registerType(serializer.type(), serializer.getSerializeClass(), serializer);
logger.info("Found serializer, class: {}, type: {}.",
serializer.getSerializeClass().getCanonicalName(),
serializer.type());
}
}
private static byte parseEntryType(byte[] buffer) {
return buffer[0];
}
private static <E> void registerType(byte type, Class<E> eClass, Serializer<E> serializer) {
serializerMap.put(eClass, serializer);
typeMap.put(type, eClass);
}
@SuppressWarnings("unchecked")
private static <E> E parse(byte[] buffer, int offset, int length, Class<E> eClass) {
Object entry = serializerMap.get(eClass).parse(buffer, offset, length);
if (eClass.isAssignableFrom(entry.getClass())) {
return (E) entry;
} else {
throw new SerializeException("Type mismatch!");
}
}
public static <E> E parse(byte[] buffer) {
return parse(buffer, 0, buffer.length);
}
private static <E> E parse(byte[] buffer, int offset, int length) {
byte type = parseEntryType(buffer);
@SuppressWarnings("unchecked")
Class<E> eClass = (Class<E>) typeMap.get(type);
if (null == eClass) {
throw new SerializeException(String.format("Unknown entry type: %d!", type));
} else {
return parse(buffer, offset + 1, length - 1, eClass);
}
}
public static <E> byte[] serialize(E entry) {
@SuppressWarnings("unchecked")
Serializer<E> serializer = (Serializer<E>) serializerMap.get(entry.getClass());
if (serializer == null) {
throw new SerializeException(String.format("Unknown entry class type: %s", entry.getClass().toString()));
}
byte[] bytes = new byte[serializer.size(entry) + 1];
bytes[0] = serializer.type();
serializer.serialize(entry, bytes, 1, bytes.length - 1);
return bytes;
}
}
| 33.568627 | 117 | 0.631717 |
d33eaeeaddec4bc0c3ab2aca35d5f749efde91c0 | 442 | package org.ubjson.viewer;
public class ScopeStack {
private int pos;
private Scope[] levels;
public ScopeStack() {
// Support a scope depth up to 128-levels.
levels = new Scope[128];
}
public void reset() {
pos = -1;
}
public void push(Scope scope) {
levels[++pos] = scope;
}
public Scope peek() {
return (pos < 0 ? null : levels[pos]);
}
public Scope pop() {
return levels[pos--];
}
} | 16.37037 | 45 | 0.59276 |
800460acaa0579767c3872cab9f051935d45b7b3 | 769 | package com.guaner.service.admin;
/**
* 后台菜单操作service
*/
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.guaner.dao.admin.MenuDao;
import com.guaner.entity.admin.Menu;
@Service
public class MenuService {
@Autowired
private MenuDao menuDao;
/**
* 菜单添加/编辑
* @param menu
* @return
*/
public Menu save(Menu menu){
return menuDao.save(menu);
}
/**
* 获取所有的菜单列表
* @return
*/
public List<Menu> findAll(){
return menuDao.findAll();
}
/**
* 根据id查询菜单
* @param id
* @return
*/
public Menu find(Long id){
return menuDao.find(id);
}
/**
* 根据id删除一条记录
* @param id
*/
public void delete(Long id){
menuDao.deleteById(id);
}
}
| 14.509434 | 62 | 0.6658 |
3060ea725579163eef8c5024ee06bf8a7dbfe530 | 6,308 | package org.activiti.rest.api.process;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.TaskQueryProperty;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.query.QueryProperty;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.TaskQuery;
import org.activiti.rest.api.ActivitiUtil;
import org.activiti.rest.api.DataResponse;
import org.activiti.rest.api.SecuredResource;
import org.activiti.rest.api.task.TasksPaginateList;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.restlet.resource.Get;
public class ProcessInstanceHighLightsResource extends SecuredResource {
private RuntimeService runtimeService = ActivitiUtil.getRuntimeService();
private RepositoryServiceImpl repositoryService = (RepositoryServiceImpl) ActivitiUtil.getRepositoryService();
private HistoryService historyService = (HistoryService) ActivitiUtil.getHistoryService();
private ProcessInstance processInstance;
private ProcessDefinitionEntity processDefinition;
List<String> historicActivityInstanceList = new ArrayList<String>();
List<String> highLightedFlows = new ArrayList<String>();
public ProcessInstanceHighLightsResource() {
/*
properties.put("id", TaskQueryProperty.TASK_ID);
properties.put("executionId", TaskQueryProperty.EXECUTION_ID);
properties.put("processInstanceId", TaskQueryProperty.PROCESS_INSTANCE_ID);
*/
}
@Get
public ObjectNode getHighlighted() {
if (authenticate() == false)
return null;
String processInstanceId = (String) getRequest().getAttributes().get("processInstanceId");
if (processInstanceId == null) {
throw new ActivitiException("No process instance id provided");
}
ObjectNode responseJSON = new ObjectMapper().createObjectNode();
responseJSON.put("processInstanceId", processInstanceId);
ArrayNode activitiesArray = new ObjectMapper().createArrayNode();
ArrayNode flowsArray = new ObjectMapper().createArrayNode();
try {
processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
processDefinition = (ProcessDefinitionEntity) repositoryService
.getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
responseJSON.put("processDefinitionId", processInstance.getProcessDefinitionId());
List<String> highLightedActivities = runtimeService.getActiveActivityIds(processInstanceId);
List<String> highLightedFlows = getHighLightedFlows(processDefinition, processInstanceId);
for (String activityId : highLightedActivities)
activitiesArray.add(activityId);
for (String flow : highLightedFlows)
flowsArray.add(flow);
for (String activityId : highLightedActivities) {
Execution execution = runtimeService.createExecutionQuery()
.processInstanceId(processInstance.getProcessInstanceId())
.activityId(activityId).singleResult();
ExecutionEntity executionEntity = (ExecutionEntity)execution;
executionEntity.getProcessDefinitionId();
}
} catch (Exception e) {}
responseJSON.put("activities", activitiesArray);
responseJSON.put("flows", flowsArray);
return responseJSON;
}
// TODO: move this method to some 'utils'
private List<String> getHighLightedFlows(ProcessDefinitionEntity processDefinition, String processInstanceId) {
List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceStartTime().asc()/*.orderByActivityId().asc()*/.list();
//_log.info("--->procId: " + procId);
for (HistoricActivityInstance hai : historicActivityInstances) {
//_log.info("id: " + hai.getId() + ", ActivityId:" + hai.getActivityId() + ", ActivityName:" + hai.getActivityName());
historicActivityInstanceList.add(hai.getActivityId());
}
// add current activities to list
List<String> highLightedActivities = runtimeService.getActiveActivityIds(processInstanceId);
historicActivityInstanceList.addAll(highLightedActivities);
// activities and their sequence-flows
getHighLightedFlows(processDefinition.getActivities());
return highLightedFlows;
}
private void getHighLightedFlows (List<ActivityImpl> activityList) {
for (ActivityImpl activity : activityList) {
//int index = historicActivityInstanceList.indexOf(activity.getId());
if (activity.getProperty("type").equals("subProcess")) {
// get flows for the subProcess
getHighLightedFlows(activity.getActivities());
}
//if (index >=0 && index+1 < historicActivityInstanceList.size()) {
if (historicActivityInstanceList.contains(activity.getId())) {
//_log.info("* actId:" + activity.getId() + ", transitions: " + activity.getOutgoingTransitions());
List<PvmTransition> pvmTransitionList = activity.getOutgoingTransitions();
for (PvmTransition pvmTransition: pvmTransitionList) {
String destinationFlowId = pvmTransition.getDestination().getId();
//_log.info("- destinationFlowId: " + destinationFlowId + ", + " + historicActivityInstanceList.get(index+1));
if (historicActivityInstanceList.contains(destinationFlowId)) {
//_log.info("> actId:" + activity.getId() + ", flow: " + destinationFlowId);
highLightedFlows.add(pvmTransition.getId());
}
}
}
}
}
}
| 43.805556 | 238 | 0.742391 |
94dcc08a111e41101f732a334a5a03d020645c86 | 1,678 | /*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iris.voice.google;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.iris.core.messaging.MessageListener;
import com.iris.core.platform.PlatformDispatcherFactory;
import com.iris.google.Constants;
import com.iris.messages.PlatformMessage;
import com.iris.messages.address.Address;
import com.iris.voice.VoiceProvider;
import com.iris.voice.context.VoiceContextResolver;
@Singleton
public class GoogleService implements VoiceProvider {
private final MessageListener<PlatformMessage> dispatcher;
@Inject
public GoogleService(
VoiceContextResolver contextResolver,
PlatformDispatcherFactory factory,
RequestHandler requestHandler
) {
this.dispatcher = factory
.buildDispatcher()
.addArgumentResolverFactory(contextResolver)
.addAnnotatedHandler(requestHandler)
.build();
}
@Override
public Address address() {
return Constants.SERVICE_ADDRESS;
}
@Override
public void onMessage(PlatformMessage msg) {
dispatcher.onMessage(msg);
}
}
| 29.438596 | 75 | 0.749106 |
65c85c17b27a6572456ad34c4c95fb851460ff09 | 3,045 | package com.syntaxphoenix.syntaxapi.command;
import java.util.ArrayList;
import java.util.Iterator;
import com.syntaxphoenix.syntaxapi.exception.ObjectLockedException;
public class Ranges implements Iterable<BaseArgumentRange> {
private final ArrayList<BaseArgumentRange> ranges;
private boolean locked = false;
public Ranges() {
this.ranges = new ArrayList<>();
}
public Ranges(ArrayList<BaseArgumentRange> ranges) {
this.ranges = ranges;
}
public int count() {
return ranges.size();
}
public BaseArgumentRange get(int position) {
if (position < 1) {
throw negativeOrZero();
}
if (position > count()) {
throw outOfBounce(position);
}
return ranges.get(position - 1);
}
public void add(BaseArgumentRange argument, int position) {
if (locked) {
throw locked();
}
if (position < 1) {
throw negativeOrZero();
}
if (argument == null) {
return;
}
ranges.add(position - 1, argument);
}
public void add(BaseArgumentRange argument) {
if (locked) {
throw locked();
}
if (argument == null) {
return;
}
ranges.add(argument);
}
public Class<?> getInputType(int position) {
return get(position).getInputType();
}
public RangeType getType(int position) {
return get(position).getType();
}
public RangeSuperType getSuperType(int position) {
return getType(position).getSuperType();
}
protected boolean isLocked() {
return locked;
}
protected void setLocked(boolean locked) {
this.locked = locked;
}
/*
*
*/
@Override
public String toString() {
return toString(ArgumentSerializer.DEFAULT);
}
public String toString(ArgumentSerializer serializer) {
return toString(ArgumentRangeSerializer.DEFAULT, serializer);
}
public String toString(ArgumentRangeSerializer serializer) {
return toString(serializer, ArgumentSerializer.DEFAULT);
}
public String toString(ArgumentRangeSerializer range, ArgumentSerializer argument) {
return null;
}
/*
* Exception Construction
*/
private IllegalArgumentException negativeOrZero() {
return new IllegalArgumentException("Bound must be positive!");
}
private IndexOutOfBoundsException outOfBounce(int position) {
return new IndexOutOfBoundsException("Index: " + position + " - Size: " + count());
}
private ObjectLockedException locked() {
return new ObjectLockedException("Cannot edit a locked object!");
}
/*
*
*
*
*/
@Override
public Iterator<BaseArgumentRange> iterator() {
return ranges.iterator();
}
} | 24.166667 | 92 | 0.583908 |
bd652142c4ad3ac66d6e219c0172eebc8794b433 | 3,684 | /* LogContourFeatureExtractorTest.java
Copyright 2012 Andrew Rosenberg
This file is part of the AuToBI prosodic analysis package.
AuToBI 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.
AuToBI 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 AuToBI. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.cuny.qc.speech.AuToBI.featureextractor;
import edu.cuny.qc.speech.AuToBI.core.Contour;
import edu.cuny.qc.speech.AuToBI.core.Region;
import edu.cuny.qc.speech.AuToBI.core.Word;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
/**
* Test class for LogContourFeatureExtractor
*
* @see edu.cuny.qc.speech.AuToBI.featureextractor.IntonationalPhraseBoundaryFeatureExtractor
*/
public class LogContourFeatureExtractorTest {
@Test
public void testConstructorSetsExtractedFeaturesCorrectly() {
LogContourFeatureExtractor fe = new LogContourFeatureExtractor("I");
assertEquals(1, fe.getRequiredFeatures().size());
assertTrue(fe.getRequiredFeatures().contains("I"));
}
@Test
public void testConstructorSetsRequiredFeaturesCorrectly() {
LogContourFeatureExtractor fe = new LogContourFeatureExtractor("I");
assertEquals(1, fe.getExtractedFeatures().size());
assertTrue(fe.getExtractedFeatures().contains("log[I]"));
}
@Test
public void testExtractFeaturesExtractsFeatures() {
LogContourFeatureExtractor fe = new LogContourFeatureExtractor("I");
List<Region> regions = new ArrayList<Region>();
Word w = new Word(0, 1, "testing");
w.setAttribute("I", new Contour(0, 0.01, new double[]{0.1, 0.5}));
regions.add(w);
try {
fe.extractFeatures(regions);
assertTrue(w.hasAttribute("log[I]"));
} catch (FeatureExtractorException e) {
fail();
}
}
@Test
public void testExtractFeaturesExtractsFeaturesCorrectly() {
LogContourFeatureExtractor fe = new LogContourFeatureExtractor("I");
List<Region> regions = new ArrayList<Region>();
Word w = new Word(0, 1, "testing");
w.setAttribute("I", new Contour(0, 0.01, new double[]{0.1, 0.5}));
regions.add(w);
try {
fe.extractFeatures(regions);
Contour c = (Contour) w.getAttribute("log[I]");
assertEquals(2, c.size());
assertEquals(Math.log(0.1), c.get(0));
assertEquals(Math.log(0.5), c.get(1));
} catch (FeatureExtractorException e) {
e.printStackTrace();
}
}
@Test
public void testExtractFeaturesAssignsTheSameObjectToSubsequentRegions() {
LogContourFeatureExtractor fe = new LogContourFeatureExtractor("I");
Contour c = new Contour(0, 0.01, new double[]{0.1, 0.5});
List<Region> regions = new ArrayList<Region>();
Word w = new Word(0, .5, "testing");
Word w2 = new Word(0.5, 1, "testing");
w.setAttribute("I", c);
w2.setAttribute("I", c);
regions.add(w);
regions.add(w2);
try {
fe.extractFeatures(regions);
assertTrue(w.getAttribute("log[I]") == w2.getAttribute("log[I]"));
} catch (FeatureExtractorException e) {
e.printStackTrace();
}
}
}
| 31.758621 | 93 | 0.703583 |
c1d5cf9ee02936df0718b2e44e50c165fb297161 | 727 | public class Funcionario {
private String nome;
private String cpf;
private String funcao;
private Double salario;
public void setNome(String nome) {
this.nome = nome;
}
public String getNome() {
return this.nome;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getCpf() {
return this.cpf;
}
public void setFuncao(String funcao) {
this.funcao = funcao;
}
public String getFuncao() {
return this.funcao;
}
public void setSalario(Double Salario) {
this.salario= salario;
}
public Double getSalario() {
return this.salario;
}
}
| 20.771429 | 45 | 0.558459 |
4a7ae59403fc2f445d8a52adfdefd2f0f7778173 | 19,513 | package com.sokool.intimacyup;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Random;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sokool.intimacyup.model.LevelResults;
import com.sokool.intimacyup.model.Question;
public class MainActivity extends AppCompatActivity implements UserFragment.Records, MarksFragment.NewPlayer {
protected LinearLayout dropView;
ArrayList<Question> questionListOne;
ArrayList<Question> questionListTwo;
ArrayList<Question> questionListThree;
int num;
public static String LEVEL_ONE = "Level one";
public static String LEVEL_TWO = "Level two";
public static String LEVEL_THREE = "Level three";
String currentLevel = LEVEL_ONE;
ArrayList<LevelResults> levelResultsList;
int playerOneTotal = 0;
int playerTwoTotal = 0;
int playerOneTotalL1 = 0;
int playerTwoTotalL1 = 0;
int playerOneTotalL2 = 0;
int playerTwoTotalL2 = 0;
int playerOneTotalL3 = 0;
int playerTwoTotalL3 = 0;
public String PLAYER_ONE;
public String PLAYER_TWO;
SharedPreferences.OnSharedPreferenceChangeListener spListener;
String currentPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
hide();
initView();
questionListOne = new ArrayList<>();
questionListOne = questions(LEVEL_ONE);
questionListTwo = new ArrayList<>();
questionListTwo = questions(LEVEL_TWO);
questionListThree = new ArrayList<>();
questionListThree = questions(LEVEL_THREE);
FragmentManager fragmentManager = getSupportFragmentManager();
MarksFragment marksFragment = new MarksFragment();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.dropView, marksFragment, "marksFragment");
fragmentTransaction.commit();
FragmentTransaction fragmentTransaction1 = fragmentManager.beginTransaction();
NameFragment nameFragment = new NameFragment();
final SharedPreferences spp = getSharedPreferences("PLAYERS", Context.MODE_PRIVATE);
String player1Svd = spp.getString("Player1", null);
String player2Svd = spp.getString("Player2", null);
if (TextUtils.isEmpty(player1Svd) || TextUtils.isEmpty(player2Svd)) {
nameFragment.setCancelable(false);
}
nameFragment.show(fragmentTransaction1, "dialog");
spListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
PLAYER_ONE = sharedPreferences.getString("Player1", "Player1");
PLAYER_TWO = sharedPreferences.getString("Player2", "Player2");
if (key.equals("Player1") || key.equals("Player2")) {
restart();
}
}
};
final SharedPreferences sp = this.getSharedPreferences("PLAYERS", Context.MODE_PRIVATE);
sp.registerOnSharedPreferenceChangeListener(spListener);
PLAYER_ONE = sp.getString("Player1", null);
PLAYER_TWO = sp.getString("Player2", null);
if (PLAYER_ONE == null || PLAYER_TWO == null) {
PLAYER_ONE = "Player1";
PLAYER_TWO = "Player2";
sp.edit().putString("Player1", "").apply();
sp.edit().putString("Player2", "").apply();
}
Gson gson = new Gson();
Type questionType = new TypeToken<ArrayList<Question>>() {
}.getType();
String stored_questionListOne = sp.getString("questionListOne", null);
if (stored_questionListOne != null) {
questionListOne = gson.fromJson(stored_questionListOne, questionType);
} else {
questionListOne = questions(LEVEL_ONE);
}
String stored_questionListTwo = sp.getString("questionListTwo", null);
if (stored_questionListTwo != null) {
questionListTwo = gson.fromJson(stored_questionListTwo, questionType);
} else {
questionListTwo = questions(LEVEL_TWO);
}
String stored_questionListThree = sp.getString("questionListThree", null);
if (stored_questionListThree != null) {
questionListThree = gson.fromJson(stored_questionListThree, questionType);
} else {
questionListThree = questions(LEVEL_THREE);
}
currentLevel = sp.getString("currentLevel", LEVEL_ONE);
playerOneTotalL1 = sp.getInt("playerOneTotalL1", 0);
playerTwoTotalL1 = sp.getInt("playerTwoTotalL1", 0);
playerOneTotalL2 = sp.getInt("playerOneTotalL2", 0);
playerTwoTotalL2 = sp.getInt("playerTwoTotalL2", 0);
playerOneTotalL3 = sp.getInt("playerOneTotalL3", 0);
playerTwoTotalL3 = sp.getInt("playerTwoTotalL3", 0);
String lastPlayer = sp.getString("lastPlayer", null);
if (lastPlayer != null) {
currentPlayer = lastPlayer;
togglePlayers();
} else {
currentPlayer = PLAYER_TWO;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private ArrayList<Question> questions(String level) {
String[] current;
String[] set1 = new String[]{
"Given the choice of anyone in the world, whom would you want as a dinner guest?",
"Would you like to be famous? In what way?",
"Before making a telephone call, do you ever rehearse what you are going to say? Why?",
"What would constitute a “perfect” day for you?",
"When did you last sing to yourself? To someone else?",
"If you were able to live to the age of 90 and retain either the mind or body of a 30-year-old for the last 60 years of your life, which would you want?",
"Do you have a secret hunch about how you will die?",
"Name three things you and I appear to have in common.",
"For what in your life do you feel most grateful?",
"If you could change anything about the way you were raised, what would it be?",
"Take four minutes and tell me your life story in as much detail as possible.",
"If you could wake up tomorrow having gained any one quality or ability, what would it be?"
};
String[] set2 = new String[]{
"If someone could tell you the truth about yourself, your life, the future or anything else, what would you want to know?",
"Is there something that you’ve dreamed of doing for a long time? Why haven’t you done it?",
"What is the greatest accomplishment of your life?",
"What do you value most in a friendship?",
"What is your most treasured memory?",
"What is your most terrible memory?",
"If you knew that in one year you would die suddenly, would you change anything about the way you are now living? Why?",
"What does friendship mean to you?",
"What roles do love and affection play in your life?",
"Alternate sharing something you consider a positive characteristic of me. Share a total of five items.",
"How close and warm is your family? Do you feel your childhood was happier than most other people’s?",
"How do you feel about your relationship with your mother?"
};
String[] set3 = new String[]{
"Make three true “we” statements each. For instance, “We are both in this room feeling ... “",
"Complete this sentence: “I wish I had someone with whom I could share ... “",
"If you were going to become a close friend with me, please share what would be important for me to know.",
"Tell me what you like about me; be very honest this time, saying things that you might not say to someone you’ve just met.",
"Share with me an embarrassing moment in your life.",
"When did you last cry in front of another person? By yourself?",
"Tell me something that you like about me already.",
"What, if something, is too serious to be joked about? Would you joke about it?",
"If you were to die this evening with no opportunity to communicate with anyone, what would you most regret not having told someone? Why haven’t you told them yet?",
"Your house, containing everything you own, catches fire. After saving your loved ones and pets, you have time to safely make a final dash to save any one item. What would it be? Why?",
"Of all the people in your family, whose death would you find most disturbing? Why?",
"Share a personal problem and ask my advice on how I might handle it. Also, ask me to reflect back to you how I seem to be feeling about the problem you have chosen.",
};
ArrayList<Question> questionArrayList = new ArrayList<>();
if (level.equals(LEVEL_ONE)) {
current = set1;
for (int i = 0; i < current.length; i++
) {
Question question = new Question(current[i]);
questionArrayList.add(question);
}
}
if (level.equals(LEVEL_TWO)) {
current = set2;
for (int i = 0; i < current.length; i++
) {
Question question = new Question(current[i]);
questionArrayList.add(question);
}
}
if (level.equals(LEVEL_THREE)) {
current = set3;
for (int i = 0; i < current.length; i++
) {
Question question = new Question(current[i]);
questionArrayList.add(question);
}
}
return questionArrayList;
}
private void initView() {
dropView = (LinearLayout) findViewById(R.id.dropView);
}
@Override
public void results(Question question) {
String player = question.getAnsweredBy();
if (currentLevel.equals(LEVEL_ONE)) {
if (player.equals(PLAYER_ONE)) {
playerOneTotalL1 += question.getPoints();
}
if (player.equals(PLAYER_TWO)) {
playerTwoTotalL1 += question.getPoints();
}
}
if (currentLevel.equals(LEVEL_TWO)) {
if (player.equals(PLAYER_ONE)) {
playerOneTotalL2 += question.getPoints();
}
if (player.equals(PLAYER_TWO)) {
playerTwoTotalL2 += question.getPoints();
}
}
if (currentLevel.equals(LEVEL_THREE)) {
if (player.equals(PLAYER_ONE)) {
playerOneTotalL3 += question.getPoints();
}
if (player.equals(PLAYER_TWO)) {
playerTwoTotalL3 += question.getPoints();
}
}
if (currentLevel.equals(LEVEL_ONE)) {
questionListOne.remove(num);
}
if (currentLevel.equals(LEVEL_TWO)) {
questionListTwo.remove(num);
}
if (currentLevel.equals(LEVEL_THREE)) {
questionListThree.remove(num);
}
saveState(player);
togglePlayers();
}
private void saveState(String lastPlayer) {
Gson gson = new Gson();
final SharedPreferences sp = getSharedPreferences("PLAYERS", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = sp.edit();
spEditor.putString("questionListOne", gson.toJson(questionListOne));
spEditor.putString("questionListTwo", gson.toJson(questionListTwo));
spEditor.putString("questionListThree", gson.toJson(questionListThree));
spEditor.putInt("playerTwoTotalL1", playerTwoTotalL1);
spEditor.putInt("playerOneTotalL1", playerOneTotalL1);
spEditor.putInt("playerOneTotalL2", playerOneTotalL2);
spEditor.putInt("playerTwoTotalL2", playerTwoTotalL2);
spEditor.putInt("playerOneTotalL3", playerOneTotalL3);
spEditor.putInt("playerTwoTotalL3", playerTwoTotalL3);
spEditor.putString("currentLevel", currentLevel);
spEditor.putString("lastPlayer", lastPlayer);
spEditor.apply();
}
private void togglePlayers() {
if (currentPlayer.equals(PLAYER_ONE)) {
currentPlayer = PLAYER_TWO;
} else if (currentPlayer.equals(PLAYER_TWO)) {
currentPlayer = PLAYER_ONE;
} else {
currentPlayer = PLAYER_ONE;
}
}
@Override
public void restart() {
final SharedPreferences sp = getSharedPreferences("PLAYERS", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = sp.edit();
spEditor.remove("questionListOne");
spEditor.remove("questionListTwo");
spEditor.remove("questionListThree");
spEditor.remove("playerTwoTotalL1");
spEditor.remove("playerOneTotalL1");
spEditor.remove("playerOneTotalL2");
spEditor.remove("playerTwoTotalL2");
spEditor.remove("playerOneTotalL3");
spEditor.remove("playerTwoTotalL3");
spEditor.remove("currentLevel");
spEditor.putString("lastPlayer", PLAYER_TWO);
spEditor.putString("currentLevel", LEVEL_ONE);
currentLevel = LEVEL_ONE;
currentPlayer = PLAYER_ONE;
questionListOne = questions(LEVEL_ONE);
questionListTwo = questions(LEVEL_TWO);
questionListThree = questions(LEVEL_THREE);
playerOneTotalL1 = 0;
playerTwoTotalL1 = 0;
playerOneTotalL2 = 0;
playerTwoTotalL2 = 0;
playerOneTotalL3 = 0;
playerTwoTotalL3 = 0;
spEditor.commit();
}
@Override
public void play() {
if (currentLevel.equals(LEVEL_ONE)) {
if (questionListOne.size() <= 0) {
currentLevel = LEVEL_TWO;
} else {
Random random = new Random();
num = random.nextInt(questionListOne.size());
FragmentManager fragmentManager = getSupportFragmentManager();
Question qn = questionListOne.get(num);
qn.setAnsweredBy(currentPlayer);
// togglePlayers();
UserFragment userFragment = new UserFragment(qn);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.dropView, userFragment, "userFragment");
fragmentTransaction.commit();
}
}
if (currentLevel.equals(LEVEL_TWO)) {
if (questionListTwo.size() <= 0) {
currentLevel = LEVEL_THREE;
} else {
Random random = new Random();
num = random.nextInt(questionListTwo.size());
Question qn = questionListTwo.get(num);
qn.setAnsweredBy(currentPlayer);
FragmentManager fragmentManager = getSupportFragmentManager();
UserFragment userFragment = new UserFragment(qn);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.dropView, userFragment, "userFragment");
// togglePlayers();
fragmentTransaction.commit();
}
}
if (currentLevel.equals(LEVEL_THREE)) {
if (questionListThree.size() <= 0) {
currentLevel = "done";
Toast.makeText(this, "Levels Complete", Toast.LENGTH_SHORT).show();
} else {
Random random = new Random();
num = random.nextInt(questionListThree.size());
Question qn = questionListThree.get(num);
qn.setAnsweredBy(currentPlayer);
FragmentManager fragmentManager = getSupportFragmentManager();
UserFragment userFragment = new UserFragment(qn);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.dropView, userFragment, "userFragment");
// togglePlayers();
fragmentTransaction.commit();
}
}
if (currentLevel.equals("done")) {
currentLevel = "done";
Toast.makeText(this, "Levels Complete Thank you for playing", Toast.LENGTH_SHORT).show();
FragmentManager fragmentManager = getSupportFragmentManager();
MarksFragment marksFragment = new MarksFragment();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.dropView, marksFragment, "marksFragment");
fragmentTransaction.commit();
}
}
@Override
public String getLevel() {
return currentLevel;
}
@Override
public ArrayList<LevelResults> getLevelResults() {
LevelResults levelone = new LevelResults(LEVEL_ONE, playerOneTotalL1, playerTwoTotalL1);
LevelResults leveltwo = new LevelResults(LEVEL_TWO, playerOneTotalL2, playerTwoTotalL2);
LevelResults levelthree = new LevelResults(LEVEL_THREE, playerOneTotalL3, playerTwoTotalL3);
levelResultsList = new ArrayList<>();
levelResultsList.add(levelone);
levelResultsList.add(leveltwo);
levelResultsList.add(levelthree);
return levelResultsList;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
hide();
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
}
}
| 39.903885 | 202 | 0.60862 |
f8894cf4e299d3f1711ecd7a06966ee286622aff | 1,461 | /*
* Copyright 2020 vivier technologies
*
* 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.vivier_technologies.admin;
public interface Status {
interface State {
byte ACTIVE = 0;
byte PASSIVE = 1;
}
int STATE = 0;
int INSTANCE_NAME = 1;
int INSTANCE_NAME_LEN = 16;
int MACHINE_NAME = INSTANCE_NAME + INSTANCE_NAME_LEN;
int MACHINE_NAME_LEN = 50;
int STATUS_LEN = MACHINE_NAME + MACHINE_NAME_LEN;
/**
* Get state of the status sender
*
* @return byte representing the state - values above
*/
byte getState();
/**
* Physical instance name of the sending process
*
* @return string in byte array of length INSTANCE_NAME_LEN
*/
byte[] getInstanceName();
/**
* Machine name the sending process is located on
*
* @return string in byte array of length MACHINE_NAME_LEN
*/
byte[] getMachineName();
}
| 26.563636 | 75 | 0.672142 |
36f92433ec820e2608c2e0c15d00f8d9767b13b3 | 1,811 | package org.jdfs.tracker.codec;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;
import org.jdfs.commons.codec.DecoderState;
import org.jdfs.commons.codec.JdfsFileRequestMessageDecoder;
import org.jdfs.commons.request.JdfsRequestConstants;
import org.jdfs.tracker.request.UpdateFileInfoRequest;
import org.jdfs.tracker.request.UpdateFileInfoSyncRequest;
/**
* 用于对{@link UpdateFileInfoSyncRequest}进行解码的解码器
* @author James Quan
* @version 2015年1月31日 上午9:50:38
*/
public class UpdateFileSyncRequestMessageDecoder extends JdfsFileRequestMessageDecoder<UpdateFileInfoSyncRequest> {
@Override
protected int getRequestCode() {
return JdfsRequestConstants.REQUEST_SYNC_INFO_UPDATE;
}
@Override
protected UpdateFileInfoSyncRequest createRequest(int batchId, int code) {
UpdateFileInfoSyncRequest r = new UpdateFileInfoSyncRequest();
r.setBatchId(batchId);
return r;
}
@Override
protected MessageDecoderResult decodeFileRequest(
DecoderState<UpdateFileInfoSyncRequest> state, IoSession session,
IoBuffer in) throws Exception{
UpdateFileInfoSyncRequest request = state.getRequest();
if(state.getState() == 2) {
if(in.remaining() < 20) {
return MessageDecoderResult.NEED_DATA;
}
int group = in.getInt();
long size = in.getLong();
long lastModified = in.getLong();
request.setGroup(group);
request.setSize(size);
request.setLastModified(lastModified);
state.toNextState();
}
if(!in.prefixedDataAvailable(4, maxDataSize)) {
return MessageDecoderResult.NEED_DATA;
}
int l = in.getInt();
byte[] data = new byte[l];
in.get(data);
String name = new String(data, "UTF-8");
request.setName(name);
return MessageDecoderResult.OK;
}
}
| 30.694915 | 115 | 0.76974 |
12d38267a162eb1837f6d9e92ed6aabcc17ab541 | 2,037 | package oop.focus.diary.controller;
import oop.focus.common.View;
import oop.focus.db.exceptions.DaoAccessException;
import oop.focus.diary.model.DailyMood;
import oop.focus.diary.model.DailyMoodImpl;
import oop.focus.diary.model.DailyMoodManager;
import oop.focus.diary.view.DailyMoodSection;
import org.joda.time.LocalDate;
import java.util.Optional;
/**
* Implementation of {@link DailyMoodController}. DailyMoodControllerImpl has methods to manage dailyMood's section.
*/
public class DailyMoodControllerImpl implements DailyMoodController {
private final DailyMoodManager manager;
private DailyMood dailyMood;
/**
* Instantiates a new daily mood controller and creates the associated view.
*
* @param manager the daily mood manager
*/
public DailyMoodControllerImpl(final DailyMoodManager manager) {
this.manager = manager;
if (this.manager.getMoodByDate(LocalDate.now()).isPresent()) {
this.dailyMood = new DailyMoodImpl(this.manager.getMoodByDate(LocalDate.now()).get(), LocalDate.now());
}
}
/**
* {@inheritDoc}
*/
@Override
public void addDailyMood(final int value) throws DaoAccessException {
this.dailyMood = new DailyMoodImpl(value, LocalDate.now());
this.manager.addDailyMood(this.dailyMood);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getValueChosen() {
return this.manager.getMoodByDate(LocalDate.now());
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getValueByDate(final LocalDate date) {
return this.manager.getMoodByDate(date);
}
/**
* {@inheritDoc}
*/
@Override
public void removeChoice() throws DaoAccessException {
if (this.getValueChosen().isPresent()) {
this.manager.deleteDailyMood(this.dailyMood);
}
}
/**
* {@inheritDoc}
*/
@Override
public View getView() {
return new DailyMoodSection(this);
}
}
| 28.690141 | 116 | 0.670103 |
d9ba5a6aed2db896900d06e3047edcc2e080e7c7 | 1,534 | package io.stargate.graphql.schema.fetchers.dml;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import io.stargate.db.schema.Keyspace;
import io.stargate.graphql.schema.DmlTestBase;
import io.stargate.graphql.schema.SampleKeyspaces;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class QueryFetcherUdtsTest extends DmlTestBase {
@Override
public Keyspace getKeyspace() {
return SampleKeyspaces.UDTS;
}
@ParameterizedTest
@MethodSource("successfulQueries")
@DisplayName("Should execute GraphQL with UDTs and generate expected CQL query")
public void udtTest(String graphQlQuery, String expectedCqlQuery) {
assertQuery(String.format("query { %s }", graphQlQuery), expectedCqlQuery);
}
public static Arguments[] successfulQueries() {
return new Arguments[] {
arguments(
"TestTable(value: { a: { b: {i:1} } }) { values { a{b{i}} } }",
"SELECT a FROM udts.\"TestTable\" WHERE a={\"b\":{\"i\":1}}"),
arguments(
"TestTable(filter: { a: {eq: { b: {i:1} } } }) { values { a{b{i}} } }",
"SELECT a FROM udts.\"TestTable\" WHERE a={\"b\":{\"i\":1}}"),
arguments(
"TestTable(filter: { a: {in: [{ b: {i:1} }, { b: {i:2} }] } }) { values { a{b{i}} } }",
"SELECT a FROM udts.\"TestTable\" WHERE a IN ({\"b\":{\"i\":1}},{\"b\":{\"i\":2}})"),
};
}
}
| 37.414634 | 97 | 0.649283 |
a3c6f4ec6554a944d8c59ac32116cf55a5b6acdb | 679 | package com.brijesh.microservices.limitsservice.controller;
import com.brijesh.microservices.limitsservice.bean.Limits;
import com.brijesh.microservices.limitsservice.configuration.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LimitsController {
@Autowired
private Configuration configuration;
@GetMapping("/limits")
public Limits retrieveLimits(){
return new Limits(configuration.getMinimum(),configuration.getMaximum());
// return new Limits(1,1000);
}
}
| 32.333333 | 81 | 0.795287 |
0d16591ec01b069227a10e9ceb34a54882465e01 | 5,735 | /*
* Copyright 2015-2025 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 sockslib.server.msg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sockslib.common.AddressType;
import sockslib.common.NotImplementException;
import sockslib.utils.SocksUtil;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* The class <code>CommandResponseMessage</code> represents a command response message.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 6, 2015 11:10:25 AM
*/
public class CommandResponseMessage implements WritableMessage {
/**
* Logger that subclasses also can use.
*/
protected static final Logger logger = LoggerFactory.getLogger(CommandResponseMessage.class);
private int version = 5;
/**
* The reserved field.
*/
private int reserved = 0x00;
/**
* Address type.
*/
private int addressType = AddressType.IPV4;
/**
* Bind address.
*/
private InetAddress bindAddress;
/**
* Bind port.
*/
private int bindPort;
/**
* Rely from SOCKS server.
*/
private ServerReply reply;
/**
* Constructs a {@link CommandResponseMessage} by {@link ServerReply}.
*
* @param reply Reply from server.
*/
public CommandResponseMessage(ServerReply reply) {
byte[] defaultAddress = {0, 0, 0, 0};
this.reply = reply;
try {
bindAddress = InetAddress.getByAddress(defaultAddress);
addressType = 0x01;
} catch (UnknownHostException e) {
logger.error(e.getMessage(), e);
}
}
/**
* Constructs a {@link CommandResponseMessage}.
*
* @param version Version
* @param reply Sever reply.
* @param bindAddress Bind IP address.
* @param bindPort Bind port.
*/
public CommandResponseMessage(int version, ServerReply reply, InetAddress bindAddress, int
bindPort) {
this.version = version;
this.reply = reply;
this.bindAddress = bindAddress;
this.bindPort = bindPort;
if (bindAddress.getAddress().length == 4) {
addressType = 0x01;
} else {
addressType = 0x04;
}
}
@Override
public byte[] getBytes() {
byte[] bytes = null;
switch (addressType) {
case AddressType.IPV4:
bytes = new byte[10];
for (int i = 0; i < bindAddress.getAddress().length; i++) {
bytes[i + 4] = bindAddress.getAddress()[i];
}
bytes[8] = SocksUtil.getFirstByteFromInt(bindPort);
bytes[9] = SocksUtil.getSecondByteFromInt(bindPort);
break;
case AddressType.IPV6:
bytes = new byte[22];
for (int i = 0; i < bindAddress.getAddress().length; i++) {
bytes[i + 4] = bindAddress.getAddress()[i];
}
bytes[20] = SocksUtil.getFirstByteFromInt(bindPort);
bytes[21] = SocksUtil.getSecondByteFromInt(bindPort);
break;
case AddressType.DOMAIN_NAME:
throw new NotImplementException();
default:
break;
}
bytes[0] = (byte) version;
bytes[1] = reply.getValue();
bytes[2] = (byte) reserved;
bytes[3] = (byte) addressType;
return bytes;
}
@Override
public int getLength() {
return getBytes().length;
}
/**
* Returns version.
*
* @return Version.
*/
public int getVersion() {
return version;
}
/**
* Sets version.
*
* @param version Version.
*/
public void setVersion(int version) {
this.version = version;
}
/**
* Returns address type.
*
* @return Address type.
*/
public int getAddressType() {
return addressType;
}
/**
* Sets address type.
*
* @param addressType Address type.
*/
public void setAddressType(int addressType) {
this.addressType = addressType;
}
/**
* Returns bind address.
*
* @return Bind address.
*/
public InetAddress getBindAddress() {
return bindAddress;
}
/**
* Sets bind address.
*
* @param bindAddress Bind address.
*/
public void setBindAddress(InetAddress bindAddress) {
this.bindAddress = bindAddress;
}
/**
* Returns bind port.
*
* @return Bind port.
*/
public int getBindPort() {
return bindPort;
}
/**
* Sets bind port.
*
* @param bindPort Bind port.
*/
public void setBindPort(int bindPort) {
this.bindPort = bindPort;
}
/**
* Returns the reply of SOCKS server.
*
* @return SOCKS server's reply.
*/
public ServerReply getReply() {
return reply;
}
/**
* Sets SOCKS server's reply.
*
* @param reply Reply of the SOCKS server.
*/
public void setReply(ServerReply reply) {
this.reply = reply;
}
}
| 24.404255 | 100 | 0.575065 |
8bceb6d27410ac116e0dbdabb343a40b53540257 | 983 | package com.company.TextProcessing.Exercise;
import java.util.Scanner;
public class P07StringExplosion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
StringBuilder sb = new StringBuilder();
//01234567890123456
//abv>1>1>2>2asdasd
for (int i = 0; i < text.length(); i++) {
char symbol = text.charAt(i);
sb.append(symbol);
if (symbol == '>') {
i++;
int range = text.charAt(i) - '0';
int j = i;
for (; j < i + range && j < text.length(); j++) {
if (text.charAt(j) == '>') {
sb.append('>');
j++;
range += (text.charAt(j) - '0') + 1;
}
}
i = j - 1;
}
}
System.out.println(sb);
}
}
| 26.567568 | 65 | 0.416073 |
0addcac57020217f0e790bb283f6c281b2ea5323 | 664 | package com.ltts.movieapp.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ltts.movieapp.bo.MovieBo;
import com.ltts.movieapp.model.Movie;
@Service
public class MovieServiceImp implements MovieService{
@Autowired
private MovieBo mv;
@Override
public void save(Movie id) {
// TODO Auto-generated method stub
}
@Override
public Movie findMovieById(int id) {
// TODO Auto-generated method stub
return mv.findMovieById(id);
}
@Override
public List<Movie> findAll() {
// TODO Auto-generated method stub
return mv.findAll();
}
}
| 18.444444 | 62 | 0.751506 |
6c8b9b53f6cd4bcc0377d74a60f255a8063e1463 | 1,786 | package com.turbouml.dto.models;
import java.util.List;
/**
* An entity to represent all of the data in a single diagram for a project
* stores the data of the project from the project database table,
* stores all class diagrams belonging to the project,
* stores all relationships belonging to the project
* stores all packages belonging to the project
* stores the dimensions of the diagram canvas
*/
public class UMLDiagram
{
public static final int MAX_X = 2000;
public static final int MAX_Y = 2000;
private Project project;
private List<UMLClassDiagram> classDiagrams;
private List<UMLRelationship> classRelationships;
private List<UMLPackage> packages;
private int maxX = MAX_X;
private int maxY = MAX_Y;
public void setMaxX(int maxX) {
this.maxX = maxX;
}
public int getMaxX() {
return maxX;
}
public int getMaxY() {
return maxY;
}
public void setMaxY(int maxY) {
this.maxY = maxY;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public List<UMLRelationship> getClassRelationships() {
return classRelationships;
}
public void setClassRelationships(List<UMLRelationship> classRelationships) {
this.classRelationships = classRelationships;
}
public List<UMLPackage> getPackages() {
return packages;
}
public void setPackages(List<UMLPackage> packages) {
this.packages = packages;
}
public List<UMLClassDiagram> getClassDiagrams() {
return classDiagrams;
}
public void setClassDiagrams(List<UMLClassDiagram> classDiagrams) {
this.classDiagrams = classDiagrams;
}
}
| 24.465753 | 81 | 0.678611 |
0bfdc7348dbec8aacba214cada5cadd78acb825e | 1,212 | import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CalculadoraServlet extends HttpServlet
{
public void service (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
double op1, op2, result;
int operacion;
String simb_op[] = {"+", "-", "*","/"};
ServletOutputStream out = res.getOutputStream();
op1 = Double.parseDouble(req.getParameter("operando1"));
op2 = Double.parseDouble(req.getParameter("operando2"));
operacion = Integer.parseInt(req.getParameter("operacion"));
result = calcula(op1, op2, operacion);
out.println("<html>");
out.println("<head><title>Resultado de calcular con Servlet</title></head>");
out.println("<body BGCOLOR = \"#E0E0FF\" TEXT= \"blue\">");
out.println("<h1><center>La operacion efectuada es:</center></h1>");
out.println("<h2> <b><center>"+ op1+" "+ simb_op[operacion-1] + " "+ op2 + " = "+ result + "</center></b></h2>");
out.println("</body>");
out.println("</html>");
out.close();
}
public double calcula(double op1, double op2, int operacion)
{
double result = 0;
switch (operacion)
{
case 1:
return op1 + op2;
case 2:
return op1 - op2;
case 3:
return op1 * op2;
case 4:
return op1 / op2;
}
return result;
}
}
| 28.186047 | 113 | 0.695545 |
08344b0cf9a96ea168b08feceb7d2170062a71c3 | 2,255 | package org.anddev.andengine.extension.physics.box2d;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.World;
import org.anddev.andengine.engine.handler.runnable.RunnableHandler;
public class FixedStepPhysicsWorld
extends PhysicsWorld
{
public static final int STEPSPERSECOND_DEFAULT = 60;
private final int mMaximumStepsPerUpdate;
private float mSecondsElapsedAccumulator;
private final float mTimeStep;
public FixedStepPhysicsWorld(int paramInt1, int paramInt2, Vector2 paramVector2, boolean paramBoolean)
{
super(paramVector2, paramBoolean);
this.mTimeStep = (1.0F / paramInt1);
this.mMaximumStepsPerUpdate = paramInt2;
}
public FixedStepPhysicsWorld(int paramInt1, int paramInt2, Vector2 paramVector2, boolean paramBoolean, int paramInt3, int paramInt4)
{
super(paramVector2, paramBoolean, paramInt3, paramInt4);
this.mTimeStep = (1.0F / paramInt1);
this.mMaximumStepsPerUpdate = paramInt2;
}
public FixedStepPhysicsWorld(int paramInt, Vector2 paramVector2, boolean paramBoolean)
{
this(paramInt, 2147483647, paramVector2, paramBoolean);
}
public FixedStepPhysicsWorld(int paramInt1, Vector2 paramVector2, boolean paramBoolean, int paramInt2, int paramInt3)
{
this(paramInt1, 2147483647, paramVector2, paramBoolean, paramInt2, paramInt3);
}
public void onUpdate(float paramFloat)
{
this.mRunnableHandler.onUpdate(paramFloat);
this.mSecondsElapsedAccumulator = (paramFloat + this.mSecondsElapsedAccumulator);
int i = this.mVelocityIterations;
int j = this.mPositionIterations;
World localWorld = this.mWorld;
float f = this.mTimeStep;
for (int k = this.mMaximumStepsPerUpdate;; k--)
{
if ((this.mSecondsElapsedAccumulator < f) || (k <= 0))
{
this.mPhysicsConnectorManager.onUpdate(paramFloat);
return;
}
localWorld.step(f, i, j);
this.mSecondsElapsedAccumulator -= f;
}
}
}
/* Location: C:\Users\Rodelle\Desktop\Attacknid\Tools\Attacknids-dex2jar.jar
* Qualified Name: org.anddev.andengine.extension.physics.box2d.FixedStepPhysicsWorld
* JD-Core Version: 0.7.0.1
*/ | 35.234375 | 135 | 0.71663 |
efd2da8dea278d49ffc82f670168a63806e573cb | 8,045 | /*
Copyright (c) 2007-2009 Kristofer Karlsson <[email protected]>
and Jan Matejek <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package se.krka.kahlua.stdlib;
import se.krka.kahlua.vm.JavaFunction;
import se.krka.kahlua.vm.LuaCallFrame;
import se.krka.kahlua.vm.LuaState;
import se.krka.kahlua.vm.LuaTable;
import se.krka.kahlua.vm.LuaTableImpl;
public final class TableLib implements JavaFunction {
private static final int CONCAT = 0;
private static final int INSERT = 1;
private static final int REMOVE = 2;
private static final int MAXN = 3;
private static final int NUM_FUNCTIONS = 4;
private static final String[] names;
private static TableLib[] functions;
static {
names = new String[NUM_FUNCTIONS];
names[CONCAT] = "concat";
names[INSERT] = "insert";
names[REMOVE] = "remove";
names[MAXN] = "maxn";
}
private int index;
public TableLib (int index) {
this.index = index;
}
public static void register (LuaState state) {
initFunctions();
LuaTable table = new LuaTableImpl();
state.getEnvironment().rawset("table", table);
for (int i = 0; i < NUM_FUNCTIONS; i++) {
table.rawset(names[i], functions[i]);
}
}
private static synchronized void initFunctions () {
if (functions == null) {
functions = new TableLib[NUM_FUNCTIONS];
for (int i = 0; i < NUM_FUNCTIONS; i++) {
functions[i] = new TableLib(i);
}
}
}
public String toString () {
if (index < names.length) {
return "table." + names[index];
}
return super.toString();
}
public int call (LuaCallFrame callFrame, int nArguments) {
switch (index) {
case CONCAT:
return concat(callFrame, nArguments);
case INSERT:
return insert(callFrame, nArguments);
case REMOVE:
return remove(callFrame, nArguments);
case MAXN:
return maxn(callFrame, nArguments);
default:
return 0;
}
}
private static int concat (LuaCallFrame callFrame, int nArguments) {
BaseLib.luaAssert(nArguments >= 1, "expected table, got no arguments");
LuaTable table = (LuaTable)callFrame.get(0);
String separator = "";
if (nArguments >= 2) {
separator = BaseLib.rawTostring(callFrame.get(1));
}
int first = 1;
if (nArguments >= 3) {
Double firstDouble = BaseLib.rawTonumber(callFrame.get(2));
first = firstDouble.intValue();
}
int last;
if (nArguments >= 4) {
Double lastDouble = BaseLib.rawTonumber(callFrame.get(3));
last = lastDouble.intValue();
} else {
last = table.len();
}
StringBuffer buffer = new StringBuffer();
for (int i = first; i <= last; i++) {
if (i > first) {
buffer.append(separator);
}
Double key = LuaState.toDouble(i);
Object value = table.rawget(key);
buffer.append(BaseLib.rawTostring(value));
}
return callFrame.push(buffer.toString());
}
public static void insert (LuaState state, LuaTable table, Object element) {
append(state, table, element);
}
public static void append(LuaState state, LuaTable table, Object element) {
int position = 1 + table.len();
state.tableSet(table, LuaState.toDouble(position), element);
}
public static void rawappend(LuaTable table, Object element) {
int position = 1 + table.len();
table.rawset(LuaState.toDouble(position), element);
}
public static void insert(LuaState state, LuaTable table, int position, Object element) {
int len = table.len();
for (int i = len; i >= position; i--) {
state.tableSet(table, LuaState.toDouble(i+1), state.tableGet(table, LuaState.toDouble(i)));
}
state.tableSet(table, LuaState.toDouble(position), element);
}
public static void rawinsert(LuaTable table, int position, Object element) {
int len = table.len();
if (position <= len) {
Double dest = LuaState.toDouble(len + 1);
for (int i = len; i >= position; i--) {
Double src = LuaState.toDouble(i);
table.rawset(dest, table.rawget(src));
dest = src;
}
table.rawset(dest, element);
} else {
table.rawset(LuaState.toDouble(position), element);
}
}
private static int insert (LuaCallFrame callFrame, int nArguments) {
BaseLib.luaAssert(nArguments >= 2, "Not enough arguments");
LuaTable t = (LuaTable)callFrame.get(0);
int pos = t.len() + 1;
Object elem = null;
if (nArguments > 2) {
pos = BaseLib.rawTonumber(callFrame.get(1)).intValue();
elem = callFrame.get(2);
} else {
elem = callFrame.get(1);
}
insert(callFrame.thread.state, t, pos, elem);
return 0;
}
public static Object remove (LuaState state, LuaTable table) {
return remove(state, table, table.len());
}
public static Object remove (LuaState state, LuaTable table, int position) {
Object ret = state.tableGet(table, LuaState.toDouble(position));
int len = table.len();
for (int i = position; i < len; i++) {
state.tableSet(table, LuaState.toDouble(i), state.tableGet(table, LuaState.toDouble(i+1)));
}
state.tableSet(table, LuaState.toDouble(len), null);
return ret;
}
public static Object rawremove (LuaTable table, int position) {
Object ret = table.rawget(LuaState.toDouble(position));
int len = table.len();
for (int i = position; i <= len; i++) {
table.rawset(LuaState.toDouble(i), table.rawget(LuaState.toDouble(i+1)));
}
return ret;
}
public static void removeItem (LuaTable table, Object item) {
if (item == null) return;
Object key = null;
while ((key = table.next(key)) != null) {
if (item.equals(table.rawget(key))) {
if (key instanceof Double) {
double k = ((Double)key).doubleValue();
int i = (int)k;
if (k == i) rawremove(table, i);
} else {
table.rawset(key, null);
}
return;
}
}
}
public static void dumpTable (LuaTable table) {
System.out.print("table " + table + ": ");
Object key = null;
while ((key = table.next(key)) != null) {
System.out.print(key.toString() + " => " + table.rawget(key) + ", ");
}
System.out.println();
}
private static int remove (LuaCallFrame callFrame, int nArguments) {
BaseLib.luaAssert(nArguments >= 1, "expected table, got no arguments");
LuaTable t = (LuaTable)callFrame.get(0);
int pos = t.len();
if (nArguments > 1) {
pos = BaseLib.rawTonumber(callFrame.get(1)).intValue();
}
callFrame.push(remove(callFrame.thread.state, t, pos));
return 1;
}
private static int maxn (LuaCallFrame callFrame, int nArguments) {
BaseLib.luaAssert(nArguments >= 1, "expected table, got no arguments");
LuaTable t = (LuaTable)callFrame.get(0);
Object key = null;
int max = 0;
while ((key = t.next(key)) != null) {
if (key instanceof Double) {
int what = (int)LuaState.fromDouble(key);
if (what > max) max = what;
}
}
callFrame.push(LuaState.toDouble(max));
return 1;
}
public static Object find (LuaTable table, Object item) {
if (item == null) return null;
Object key = null;
while ((key = table.next(key)) != null) {
if (item.equals(table.rawget(key))) {
return key;
}
}
return null;
}
public static boolean contains (LuaTable table, Object item) {
return find(table, item) != null;
}
}
| 29.148551 | 94 | 0.684027 |
ce9afa12228af84b68b470eb1244f35135db4d7e | 1,871 | package com.browntape.productcategorizer;
/**
* Created by Srini on 11/8/16.
*/
public class Product {
public String id;
public String itemOrder;
public String title;
public String sku_code_from_channel;
public String company_id;
public String number;
public String category_id;
public Product(){}
public Product(String id, String itemOrder, String title, String sku_code_from_channel, String company_id, String number, String category_id) {
this.id = id;
this.itemOrder = itemOrder;
this.title = title;
this.sku_code_from_channel = sku_code_from_channel;
this.company_id = company_id;
this.number = number;
this.category_id = category_id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItemOrder() {
return itemOrder;
}
public void setItemOrder(String itemOrder) {
this.itemOrder = itemOrder;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSku_code_from_channel() {
return sku_code_from_channel;
}
public void setSku_code_from_channel(String sku_code_from_channel) {
this.sku_code_from_channel = sku_code_from_channel;
}
public String getCompany_id() {
return company_id;
}
public void setCompany_id(String company_id) {
this.company_id = company_id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String catgory_id) {
this.category_id = catgory_id;
}
}
| 22.011765 | 147 | 0.642437 |
318d9b08a367881af01d1c3ee550976eeacd6cd5 | 2,679 | /*
* DomainToken.java
* Copyright 2006 (C) Aaron Divinsky <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Created on March 3, 2006
*
* Current Ver: $Revision$
* Last Editor: $Author$
* Last Edited: $Date$
*/
package plugin.lsttokens.kit.deity;
import java.util.Collection;
import java.util.StringTokenizer;
import pcgen.cdom.base.Constants;
import pcgen.cdom.reference.CDOMSingleRef;
import pcgen.cdom.reference.ReferenceUtilities;
import pcgen.core.Domain;
import pcgen.core.kit.KitDeity;
import pcgen.rules.context.LoadContext;
import pcgen.rules.persistence.token.AbstractTokenWithSeparator;
import pcgen.rules.persistence.token.CDOMPrimaryToken;
import pcgen.rules.persistence.token.ParseResult;
/**
* DOMAIN Token for KitDeity
*/
public class DomainToken extends AbstractTokenWithSeparator<KitDeity> implements
CDOMPrimaryToken<KitDeity>
{
/**
* Gets the name of the tag this class will parse.
*
* @return Name of the tag this class handles
*/
@Override
public String getTokenName()
{
return "DOMAIN";
}
@Override
public Class<KitDeity> getTokenClass()
{
return KitDeity.class;
}
@Override
protected char separator()
{
return '|';
}
@Override
protected ParseResult parseTokenWithSeparator(LoadContext context,
KitDeity kitDeity, String value)
{
StringTokenizer pipeTok = new StringTokenizer(value, Constants.PIPE);
while (pipeTok.hasMoreTokens())
{
String tokString = pipeTok.nextToken();
Class<Domain> DOMAIN_CLASS = Domain.class;
CDOMSingleRef<Domain> ref =
context.ref.getCDOMReference(DOMAIN_CLASS, tokString);
kitDeity.addDomain(ref);
}
return ParseResult.SUCCESS;
}
@Override
public String[] unparse(LoadContext context, KitDeity kitDeity)
{
Collection<CDOMSingleRef<Domain>> domains = kitDeity.getDomains();
if (domains == null || domains.isEmpty())
{
return null;
}
return new String[]{ReferenceUtilities.joinLstFormat(domains,
Constants.PIPE)};
}
}
| 27.336735 | 80 | 0.748787 |
52e7c6a3ce1060417304c672b522d616df09f5a9 | 5,613 | package net.cnri.cordra.util.cmdline;
import java.io.IOException;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Pattern;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import net.cnri.cordra.CordraServiceFactory;
import net.cnri.cordra.GsonUtility;
import net.cnri.cordra.replication.kafka.ReplicationMessage;
import net.cnri.microservices.Alerter;
import net.cnri.microservices.LoggingAlerter;
import net.cnri.microservices.MultithreadedKafkaConsumer;
import net.cnri.microservices.StripedExecutorService;
import net.cnri.microservices.StripedThreadPoolExecutorService;
public class TransactionFileLogger2 {
private StripedExecutorService stripedTaskRunner;
private MultithreadedKafkaConsumer consumer;
private static Gson gson = GsonUtility.getGson();
private DailyFileLogger files;
public static void main(String[] args) throws Exception {
OptionSet options = parseOptions(args);
String dirPath = (String) options.valueOf("p");
String kafkaBootstrapServers = (String) options.valueOf("k");
String groupId;
if (options.has("g")) {
groupId = (String) options.valueOf("g");
} else {
groupId = UUID.randomUUID().toString();
}
Path path = Paths.get(dirPath);
Files.createDirectories(path);
Properties props = null;
if (options.has("properties")) {
String filename = (String) options.valueOf("properties");
try (Reader reader = Files.newBufferedReader(Paths.get(filename)) ) {
props = new Properties();
props.load(reader);
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
Map<String, String> propsAsMap = (Map) props;
TransactionFileLogger2 logger = new TransactionFileLogger2(path, groupId, kafkaBootstrapServers, propsAsMap);
logger.start();
Runtime.getRuntime().addShutdownHook(new Thread(logger::stop));
}
private static OptionSet parseOptions(String[] args) throws IOException {
OptionParser parser = new OptionParser();
parser.acceptsAll(Arrays.asList("h", "help"), "Prints help").forHelp();
parser.acceptsAll(Arrays.asList("p", "path"), "Path to log directory").withRequiredArg().required();
parser.acceptsAll(Arrays.asList("k", "kafka"), "Kafka bootstrap servers connection string").withRequiredArg();
parser.acceptsAll(Arrays.asList("g", "group-id"), "Kafka consumer group.id; if absent, a unique string will be used").withRequiredArg();
parser.accepts("properties", "properties file to configure Kafka consumer (overrides k and g arguments)").withRequiredArg();
OptionSet options;
try {
options = parser.parse(args);
if (!options.has("k") && !options.has("properties")) {
System.out.println("Error parsing options: kafka or properties option required");
parser.printHelpOn(System.out);
System.exit(1);
return null;
}
} catch (OptionException e) {
System.out.println("Error parsing options: " + e.getMessage());
parser.printHelpOn(System.out);
System.exit(1);
return null;
}
if (options.has("h")) {
System.out.println("This tool will read from a kafka and write messages to single line separated json log file");
parser.printHelpOn(System.out);
System.exit(1);
return null;
}
return options;
}
public TransactionFileLogger2(Path dir, String groupId, String kafkaBootstrapServers, Map<String, String> props) {
files = new DailyFileLogger(dir);
int numConsumerThreads = 24;
Pattern pattern = CordraServiceFactory.patternExcluding("TransactionFileReplayer");
Alerter alerter = new LoggingAlerter();
this.stripedTaskRunner = new StripedThreadPoolExecutorService(numConsumerThreads, numConsumerThreads, 500, (thread, exception) -> {
alerter.alert("Exception in stripedTaskRunner " + exception);
});
this.consumer = new MultithreadedKafkaConsumer(pattern, groupId, props, kafkaBootstrapServers, alerter, stripedTaskRunner);
gson = GsonUtility.getGson();
}
public void start() {
consumer.start(this::consume, this::stripePicker);
}
Object stripePicker(String message) {
ReplicationMessage txn = gson.fromJson(message, ReplicationMessage.class);
return txn.handle;
}
public void consume(String message, long timestamp) {
String singleLine = toSingleLineJson(message);
try {
files.appendLineToFileForTimestamp(singleLine, timestamp);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
static String toSingleLineJson(String json) {
JsonParser parser = new JsonParser();
JsonElement el = parser.parse(json);
String singleLine = gson.toJson(el);
return singleLine;
}
public void stop() {
consumer.shutdown();
stripedTaskRunner.shutdown();
if (files != null) {
files.close();
}
}
}
| 38.979167 | 144 | 0.665063 |
0a5412a544348672a65e979210fb53e61b0708cc | 874 | // Copyright 2019 Intel Corporation
// SPDX-License-Identifier: Apache 2.0
package org.sdo.rendezvous.model.types.serialization;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import org.sdo.rendezvous.model.types.PkNull;
public class PkNullSerializer extends JsonSerializer<PkNull> {
@Override
public void serialize(PkNull value, JsonGenerator jsonGenerator, SerializerProvider serializers)
throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeNumber(value.getPkType().getIndex());
jsonGenerator.writeNumber(value.getPkEnc().getIndex());
jsonGenerator.writeStartArray();
jsonGenerator.writeNumber(0);
jsonGenerator.writeEndArray();
jsonGenerator.writeEndArray();
}
}
| 33.615385 | 98 | 0.792906 |
e8b9b61e95c85418aadeaeb074639a54fecf9c1b | 2,213 | package com.github.LucasOyarzun.finalreality.model.character;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.junit.jupiter.api.Assertions;
/**
* Abstract class containing the common tests for all the types of characters.
* @author Ignacio Slater Muñoz.
* @author Lucas Oyarzun Mendez.
* @see ICharacter
*/
public abstract class AbstractCharacterTest {
protected BlockingQueue<ICharacter> turns;
/**
* Checks that the character waits the appropriate amount of time for it's turn.
*/
protected void checkWaitTurn(ICharacter character) {
Assertions.assertTrue(turns.isEmpty());
character.waitTurn();
try {
// Thread.sleep is not accurate so this values may be changed to adjust the
// acceptable error margin.
// We're testing that the character waits approximately 1 second.
Thread.sleep(900);
Assertions.assertEquals(0, turns.size());
Thread.sleep(200);
Assertions.assertEquals(1, turns.size());
Assertions.assertEquals(character, turns.peek());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Checks that the class' constructor works properly.
*/
protected void checkConstruction(final ICharacter expectedCharacter,
final ICharacter testEqualCharacter,
final ICharacter sameClassDifferentCharacter,
final ICharacter differentClassCharacter,
final ICharacter opponent) {
assertEquals(expectedCharacter, testEqualCharacter);
assertNotEquals(sameClassDifferentCharacter, testEqualCharacter);
assertNotEquals(differentClassCharacter, testEqualCharacter);
assertNotEquals(opponent, testEqualCharacter);
assertEquals(expectedCharacter.hashCode(), testEqualCharacter.hashCode());
}
/**
* Create a LinkedBlockingQueue of turns that will be used by characters.
*/
protected void basicSetUp() {
turns = new LinkedBlockingQueue<>();
}
} | 35.693548 | 82 | 0.704022 |
1ad501c422e03f521497a0bdaa5b1765e1e1d35b | 3,689 | import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import static java.lang.System.out;
import static java.util.Collections.sort;
import static java.lang.String.format;
public abstract class Initialization {
public synchronized double canRateQueueYears() {
return (double) this.intermediateBideDays / this.performedTreat.size();
}
public int queuePeriod = 0;
public synchronized void determinedLiveTic(int presentlyMarch) {
this.formerGene = (presentlyMarch);
}
public synchronized int goAccomplishedProcedureHeight() {
if (performedTreat.isEmpty()) {
return 0;
} else {
return performedTreat.size();
}
}
public int gushingNow = 0;
public synchronized double beatHalfTurnJuncture() {
return (double) this.typicalRevitalizationHour / this.performedTreat.size();
}
public boolean isMoving = false;
public synchronized int beatTypicalGenetic() {
return formerGene;
}
public Initialization() {
this.isMoving = (false);
this.gushingNow = (0);
this.queuePeriod = (0);
this.intermediateBideDays = (0);
this.typicalRevitalizationHour = (0);
this.formerGene = (-1);
this.performedTreat = (new LinkedList<>());
}
public int formerGene = 0;
public LinkedList<System> performedTreat = null;
public int typicalRevitalizationHour = 0;
public abstract void bpsRetick();
public int intermediateBideDays = 0;
public ReplacingScheme alternatePolicy = null;
public synchronized void nsoInitiate() {}
public abstract System eagerCycle();
public static final int HoursHuge = 3;
public abstract void inflowingSummons(System mechanisms);
public synchronized void occlusiveInitialization(String alternative) {
this.isMoving = (false);
this.lithographRecommendations(alternative);
}
public System underwayTreat = null;
public synchronized void lithographRecommendations(String understudyStrategize) {
try {
String qualification;
String usb;
String distance;
sort(performedTreat);
PhaseSimulations.VolumeArchiving.write("\n");
out.println();
qualification = (understudyStrategize + " - Fixed");
PhaseSimulations.VolumeArchiving.write(qualification + "\n");
out.println(qualification);
usb =
(format(
"%-7s%12s%19s%12s%14s",
"PID", "Process Name", "Turnaround Time", "# Faults", "Fault Times"));
PhaseSimulations.VolumeArchiving.write(usb + "\n");
out.println(usb);
for (System writes : performedTreat) synx135(writes);
PhaseSimulations.VolumeArchiving.write("\n");
out.println();
distance = (new String(new char[50]).replace("\0", "-"));
PhaseSimulations.VolumeArchiving.write(distance + "\n");
out.println(distance);
} catch (IOException late) {
out.println("Unable to write to file.");
}
}
public synchronized void commenceProgramming(String understudy) {
this.isMoving = (true);
if ("LRU" == understudy) {
this.alternatePolicy = (new Fsu());
} else if ("CLOCK" == understudy) {
}
this.nsoInitiate();
}
public synchronized boolean goIsMoving() {
return isMoving;
}
private synchronized void synx135(System writes) {
String phaseExtinct;
phaseExtinct =
(format(
"%-7d%-16s%-19d%-11d%-10s",
writes.goQuod(),
writes.findMention(),
writes.takeExpirationPeriod(),
writes.receiveDefect().size(),
writes.obtainDemeritHours()));
PhaseSimulations.VolumeArchiving.write(phaseExtinct + "\n");
out.println(phaseExtinct);
}
}
| 27.736842 | 84 | 0.673624 |
f0709ebc556749b384a9c4ce91efc05a327d299d | 4,562 | package com.vesit.imaginar.one;
import android.content.Context;
import android.view.MotionEvent;
import android.widget.TextView;
import com.google.ar.sceneform.FrameTime;
import com.google.ar.sceneform.HitTestResult;
import com.google.ar.sceneform.Node;
import com.google.ar.sceneform.math.Quaternion;
import com.google.ar.sceneform.math.Vector3;
import com.google.ar.sceneform.rendering.ModelRenderable;
import com.google.ar.sceneform.rendering.ViewRenderable;
public class Planet extends Node implements Node.OnTapListener {
private final String planetName;
private final float planetScale;
private final float orbitDegreesPerSecond;
private final float axisTilt;
private final ModelRenderable planetRenderable;
private final SolarSettings solarSettings;
private Node infoCard;
private RotatingNode planetVisual;
private final Context context;
private static final float INFO_CARD_Y_POS_COEFF = 0.55f;
public Planet(
Context context,
String planetName,
float planetScale,
float orbitDegreesPerSecond,
float axisTilt,
ModelRenderable planetRenderable,
SolarSettings solarSettings) {
this.context = context;
this.planetName = planetName;
this.planetScale = planetScale;
this.orbitDegreesPerSecond = orbitDegreesPerSecond;
this.axisTilt = axisTilt;
this.planetRenderable = planetRenderable;
this.solarSettings = solarSettings;
setOnTapListener(this);
}
@Override
@SuppressWarnings({"AndroidApiChecker", "FutureReturnValueIgnored"})
public void onActivate() {
if (getScene() == null) {
throw new IllegalStateException("Scene is null!");
}
if (infoCard == null) {
infoCard = new Node();
infoCard.setParent(this);
infoCard.setEnabled(false);
infoCard.setLocalPosition(new Vector3(0.0f, planetScale * INFO_CARD_Y_POS_COEFF, 0.0f));
ViewRenderable.builder()
.setView(context, R.layout.planet_card_view)
.build()
.thenAccept(
(renderable) -> {
infoCard.setRenderable(renderable);
TextView textView = (TextView) renderable.getView();
textView.setText(planetName);
})
.exceptionally(
(throwable) -> {
throw new AssertionError("Could not load plane card view.", throwable);
});
}
if (planetVisual == null) {
// Put a rotator to counter the effects of orbit, and allow the planet orientation to remain
// of planets like Uranus (which has high tilt) to keep tilted towards the same direction
// wherever it is in its orbit.
RotatingNode counterOrbit = new RotatingNode(solarSettings, true, true, 0f);
counterOrbit.setDegreesPerSecond(orbitDegreesPerSecond);
counterOrbit.setParent(this);
planetVisual = new RotatingNode(solarSettings, false, false, axisTilt);
planetVisual.setParent(counterOrbit);
planetVisual.setRenderable(planetRenderable);
planetVisual.setLocalScale(new Vector3(planetScale, planetScale, planetScale));
}
}
@Override
public void onTap(HitTestResult hitTestResult, MotionEvent motionEvent) {
if (infoCard == null) {
return;
}
infoCard.setEnabled(!infoCard.isEnabled());
}
@Override
public void onUpdate(FrameTime frameTime) {
if (infoCard == null) {
return;
}
// Typically, getScene() will never return null because onUpdate() is only called when the node
// is in the scene.
// However, if onUpdate is called explicitly or if the node is removed from the scene on a
// different thread during onUpdate, then getScene may be null.
if (getScene() == null) {
return;
}
Vector3 cameraPosition = getScene().getCamera().getWorldPosition();
Vector3 cardPosition = infoCard.getWorldPosition();
Vector3 direction = Vector3.subtract(cameraPosition, cardPosition);
Quaternion lookRotation = Quaternion.lookRotation(direction, Vector3.up());
infoCard.setWorldRotation(lookRotation);
}
}
| 37.702479 | 104 | 0.629768 |
ae6a3f6f71a3c203810bc7682376d6a195a42708 | 1,194 | package com.github.fmjsjx.myboot.autoconfigure.redis;
import java.net.URI;
import org.springframework.lang.NonNull;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* Properties class for {@code REDIS/Lettuce} cluster client.
*/
@Getter
@Setter
@ToString(callSuper = true)
public class RedisClusterClientProperties extends RedisClientProperties {
/**
* The name of the {@code REDIS/Lettuce} cluster client
*/
@NonNull
private String name;
/**
* The REDIS URI.
*/
private URI uri;
/**
* Weather this cluster client is primary or not.
*/
private boolean primary;
/**
* The host.
* <p>
* Can't be set with {@code uri}.
*/
private String host;
/**
* The default is 6379
* <p>
* Can't be set with {@code uri}.
*/
private int port = 6379;
/**
* The user name to AUTH.
* <p>
* Can't be set with {@code uri}.
* <p>
* Will be ignored when {@code password} no be set.
*/
private String username;
/**
* The password to AUTH.
* <p>
* Can't be set with {@code uri}.
*/
private String password;
}
| 19.9 | 73 | 0.588777 |
fcf8d9435c8d62fdbf9a235082706cad55d6d5c9 | 3,247 | /*
Copyright 2012, 2013 Jonathan West
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.socketanywhere.nonbreaking;
import java.io.IOException;
import com.socketanywhere.net.IServerSocketTL;
import com.socketanywhere.net.ISocketFactory;
import com.socketanywhere.net.ISocketTL;
import com.socketanywhere.net.TLAddress;
import com.socketanywhere.socketfactory.TCPSocketFactory;
/** Wraps an inner factory, and has the ability to detect when a socket generated by that factory dies.
* If it dies, this factory will attempt to re-establish it ASAP. The fact that the underlying socket died
* will not be made visible to the caller of the NBSocket; it will be as if it never happened.
*
* In this way, potentially unreliable underlying socket layers can be made reliable using NBSocket.
* */
public class NBSocketFactory implements ISocketFactory {
// We keep these separate, in order to avoid of the problem of our
// ConnectionBrain maps conflicting with each other in the case where the same process creates
// a server socket, and then connects to that server socket from that same process.
//
// It's also helpful when debugging to think of connector and connectee as "separate" entities.
ConnectionBrain _socketBrain;
ConnectionBrain _serverSocketBrain;
ISocketFactory _socketFactory;
private NBOptions _options = new NBOptions();
/** Default is just TCP factory */
public NBSocketFactory() {
_socketFactory = new TCPSocketFactory();
_socketBrain = new ConnectionBrain(_socketFactory, _options);
_serverSocketBrain = new ConnectionBrain(_socketFactory, _options);
}
public NBSocketFactory(ISocketFactory factory) {
_socketFactory = factory;
_socketBrain = new ConnectionBrain(_socketFactory, _options);
_serverSocketBrain = new ConnectionBrain(_socketFactory, _options);
}
@Override
public IServerSocketTL instantiateServerSocket() throws IOException {
NBServerSocket sock;
sock = new NBServerSocket(_serverSocketBrain, _socketFactory, _options);
return sock;
}
@Override
public IServerSocketTL instantiateServerSocket(TLAddress address) throws IOException {
return new NBServerSocket(address, _serverSocketBrain, _socketFactory, _options);
}
@Override
public ISocketTL instantiateSocket() throws IOException {
NBSocket sock = new NBSocket(_socketBrain, _socketFactory, _options);
return sock;
}
@Override
public ISocketTL instantiateSocket(TLAddress address) throws IOException {
NBSocket sock = new NBSocket(address, _socketBrain, _socketFactory, _options);
return sock;
}
public NBOptions getOptions() {
return _options;
}
}
| 33.822917 | 108 | 0.753619 |
62a1bbd62d75ba82b67a7577dfe529e6834acc9c | 262 | package org.tms.web.rest;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;
@ApplicationPath("rest")
public class TmsRestProvider extends ResourceConfig
{
public TmsRestProvider()
{
packages("org.tms.teq.rest");
}
}
| 17.466667 | 52 | 0.770992 |
66306b23cdf6887f0fd404ad39c430d2d50a75c0 | 5,418 | package com.quartzodev.utils;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import com.quartzodev.buddybook.R;
import com.quartzodev.data.Book;
import org.supercsv.cellprocessor.ConvertNullTo;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvMapWriter;
import org.supercsv.io.ICsvMapWriter;
import org.supercsv.prefs.CsvPreference;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import androidx.core.content.FileProvider;
/**
* Created by victoraldir on 10/03/2018.
*/
public class ExportCSVUtil {
private static final String EXTENSION_CSV = ".csv";
public static void writeWithCsvMapWriter(String folderTitle, List<Book> bookList, Activity activity) throws Exception {
final String[] header = new String[]{
"Book Title",
"Author",
"Publisher",
"Publishing Date",
"ISBN (10 - 13)",
"Print type",
"Language",
"Number of pages",
"Annotations",
"Description"};
// create the customer Maps (using the header elements for the column keys)
List<Map<String, Object>> mapList = new ArrayList<>();
for (Book book : bookList) {
final Map<String, Object> row = new HashMap<>();
row.put(header[0], book.getVolumeInfo().title);
row.put(header[1], formatStringList(book.getVolumeInfo().getAuthors()));
row.put(header[2], book.getVolumeInfo().getPublisher());
//row.put(header[3], new GregorianCalendar(1945, Calendar.JUNE, 13).getTime());
//TODO set as Calendar so that user can order
row.put(header[3], book.getVolumeInfo().getPublishedDate());
row.put(header[4], formatStringList(Arrays.asList(book.getVolumeInfo().getIsbn10(), book.getVolumeInfo().getIsbn13())));
row.put(header[5], book.getVolumeInfo().getPrintType());
row.put(header[6], book.getVolumeInfo().language);
row.put(header[7], book.getVolumeInfo().pageCount);
row.put(header[8], book.getAnnotation());
row.put(header[9], book.getVolumeInfo().getDescription());
mapList.add(row);
}
ICsvMapWriter mapWriter = null;
try {
ContentValues values = new ContentValues();
Uri reportPathUri;
File reportPath = new File(activity.getFilesDir(), "csvreports");
if (!reportPath.exists()) reportPath.mkdir();
File newFile = new File(reportPath, folderTitle + EXTENSION_CSV);
mapWriter = new CsvMapWriter(new FileWriter(newFile),
CsvPreference.STANDARD_PREFERENCE);
if (Build.VERSION.SDK_INT > 21) { //use this if Lollipop_Mr1 (API 22) or above
reportPathUri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", newFile);
} else {
reportPathUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
final CellProcessor[] processors = getProcessors();
// write the header
mapWriter.writeHeader(header);
// write the customer maps
for (Map<String, Object> row : mapList) {
mapWriter.write(row, header, processors);
}
Intent intent = new Intent(Intent.ACTION_SEND).setType("text/csv");
intent.putExtra(Intent.EXTRA_STREAM, reportPathUri);
activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.send_to)));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (mapWriter != null) {
mapWriter.close();
}
}
}
public static String formatStringList(List<String> strings) {
String result = "";
if (strings == null)
return result;
if (strings.isEmpty()) {
return result;
} else {
for (int x = 0; x < strings.size(); x++) {
if (strings.get(x) != null) {
if (result.isEmpty()) {
result = strings.get(x);
} else {
result = result + " - " + strings.get(x);
}
}
}
}
return result;
}
public static CellProcessor[] getProcessors() {
final CellProcessor[] processors = new CellProcessor[]{
new ConvertNullTo(""), // firstName
new ConvertNullTo(""), // lastName
new ConvertNullTo(""), // birthDate
new ConvertNullTo(""), // mailingAddress
new ConvertNullTo(""), // married
new ConvertNullTo(""), // numberOfKids
new ConvertNullTo(""), // favouriteQuote
new ConvertNullTo(""), // email
new ConvertNullTo(""), // loyaltyPoints
new ConvertNullTo("")
};
return processors;
}
}
| 34.075472 | 132 | 0.580842 |
23c7bb56c18129547bce3ea4dea126c60344c018 | 2,244 | package com.aoc;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.stream.Stream;
import static java.lang.System.out;
public class SonarSweep {
private SonarSweep() {
}
public static void main(String... args) {
var sonarSweep = new SonarSweep();
sonarSweep.solve(loadFirstMeasurements("testInput.txt"));
sonarSweep.solve(loadFirstMeasurements("input.txt"));
sonarSweep.solve(loadSecondMeasurements("testInput.txt"));
sonarSweep.solve(loadSecondMeasurements("input.txt"));
}
private static Integer[] loadFirstMeasurements(final String measurementFile) {
try (Stream<String> lines = Files.lines(Paths.get(SonarSweep.class.getClassLoader().getResource(measurementFile).toURI()))) {
var data = lines.map(Integer::valueOf).toList();
var array = new Integer[data.size()];
return data.toArray(array);
} catch (URISyntaxException | IOException e) {
return new Integer[]{};
}
}
private static Integer[] loadSecondMeasurements(final String measurementFile) {
try (Stream<String> lines = Files.lines(Paths.get(SonarSweep.class.getClassLoader().getResource(measurementFile).toURI()))) {
var linesRead = lines.map(Integer::valueOf).toList();
var data = new ArrayList<Integer>();
for (int i = 0; i < linesRead.size() - 2; i++) {
data.add(linesRead.get(i) + linesRead.get(i + 1) + linesRead.get(i + 2));
}
var array = new Integer[data.size()];
return data.toArray(array);
} catch (URISyntaxException | IOException e) {
return new Integer[]{};
}
}
void solve(final Integer[] measurements) {
Integer previousMeasurement = null;
var increasedMeasurements = 0;
for (var measurement : measurements) {
if (isMeasurable(previousMeasurement, measurement)) {
increasedMeasurements++;
}
previousMeasurement = measurement;
}
out.printf("Increased measurements: %d%n", increasedMeasurements);
}
private boolean isMeasurable(Integer previousMeasurement, Integer measurement) {
return previousMeasurement != null && previousMeasurement < measurement;
}
}
| 33.492537 | 129 | 0.697415 |
21051d802ec9b8f7f280611419443b53edd5fe9e | 25,670 | package edu.neu.ccs.pyramid.multilabel_classification.cbm;
import edu.neu.ccs.pyramid.classification.Classifier;
import edu.neu.ccs.pyramid.classification.lkboost.LKBOutputCalculator;
import edu.neu.ccs.pyramid.classification.lkboost.LKBoost;
import edu.neu.ccs.pyramid.classification.lkboost.LKBoostOptimizer;
import edu.neu.ccs.pyramid.classification.logistic_regression.ElasticNetLogisticTrainer;
import edu.neu.ccs.pyramid.classification.logistic_regression.LogisticLoss;
import edu.neu.ccs.pyramid.classification.logistic_regression.LogisticRegression;
import edu.neu.ccs.pyramid.classification.logistic_regression.RidgeLogisticOptimizer;
import edu.neu.ccs.pyramid.dataset.DataSetUtil;
import edu.neu.ccs.pyramid.dataset.MultiLabel;
import edu.neu.ccs.pyramid.dataset.MultiLabelClfDataSet;
import edu.neu.ccs.pyramid.eval.Entropy;
import edu.neu.ccs.pyramid.eval.KLDivergence;
import edu.neu.ccs.pyramid.multilabel_classification.MultiLabelClassifier;
import edu.neu.ccs.pyramid.optimization.Terminator;
import edu.neu.ccs.pyramid.regression.regression_tree.RegTreeConfig;
import edu.neu.ccs.pyramid.regression.regression_tree.RegTreeFactory;
import edu.neu.ccs.pyramid.util.MathUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.mahout.math.Vector;
import org.apache.xpath.operations.Bool;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
/**
* Created by yuyuxu on 12/19/16.
*/
public class CBMNoiseOptimizerFixed {
private static final Logger logger = LogManager.getLogger();
private CBM cbm;
private MultiLabelClfDataSet dataSet;
private Terminator terminator;
// format [#data][#components]
double[][] gammas;
// format [#components][#data]
double[][] gammasT;
// format [#labels][#data][2]
// to be fit by binary classifiers
private double[][][] binaryTargetsDistributions;
// lr parameters
// regularization for multiClassClassifier
private double priorVarianceMultiClass =1;
// regularization for binary logisticRegression
private double priorVarianceBinary =1;
// elasticnet parameters
private double regularizationMultiClass = 1.0;
private double regularizationBinary = 1.0;
private double l1RatioBinary = 0.0;
private double l1RatioMultiClass = 0.0;
private boolean lineSearch = true;
// boosting parameters
private int numLeavesBinary = 2;
private int numLeavesMultiClass = 2;
private double shrinkageBinary = 0.1;
private double shrinkageMultiClass = 0.1;
private int numIterationsBinary = 20;
private int numIterationsMultiClass = 20;
private List<MultiLabel> combinations;
// size = [num data][num combination]
private double[][] targets;
// size = [num data][num combination]
private double[][] probabilities;
// size = [num data][num combination]
private double[][] scores;
public CBMNoiseOptimizerFixed(CBM cbm, MultiLabelClfDataSet dataSet, MultiLabelClfDataSet dataSetGroundTruth, MultiLabelClassifier.AssignmentProbEstimator classifier, Boolean includeFeature) {
System.out.println("Enter CBMNoiseOptimizerFixed constructor ...");
this.cbm = cbm;
this.dataSet = dataSet;
this.combinations = DataSetUtil.gatherMultiLabels(dataSetGroundTruth);
this.terminator = new Terminator();
this.terminator.setGoal(Terminator.Goal.MINIMIZE);
this.gammas = new double[dataSet.getNumDataPoints()][cbm.getNumComponents()];
this.gammasT = new double[cbm.getNumComponents()][dataSet.getNumDataPoints()];
this.binaryTargetsDistributions = new double[cbm.getNumClasses()][dataSet.getNumDataPoints()][2];
this.scores = new double[dataSet.getNumDataPoints()][combinations.size()];
// for (int i=0;i<dataSet.getNumDataPoints();i++){
// for (int j=0;j<combinations.size();j++){
// MultiLabel truth = dataSet.getMultiLabels()[i];
// MultiLabel combination = combinations.get(j);
// double f = classifier.predictAssignmentProb(combination.toVector(dataSet.getNumClasses()), truth);
// scores[i][j] = f;
// }
// }
System.out.println("#data points: " + dataSet.getNumDataPoints() + ", #combinations: " + combinations.size());
IntStream.range(0, dataSet.getNumDataPoints()).forEach(i-> IntStream.range(0,combinations.size()).parallel()
.forEach(j->{
// y
MultiLabel truth = dataSet.getMultiLabels()[i];
// z
MultiLabel combination = combinations.get(j);
double f = 0.0;
if (!includeFeature) {
f = classifier.predictAssignmentProb(combination.toVector(dataSet.getNumClasses()), truth);
} else {
MultiLabel xz = new MultiLabel();
MultiLabel x = new MultiLabel(dataSet.getRow(i));
for (int k = 0; k < dataSet.getNumFeatures(); k++) {
if (x.matchClass(k)) {
xz.addLabel(k);
}
}
for (int k = 0; k < dataSet.getNumClasses(); k++) {
if (combination.matchClass(k)) {
xz.addLabel(k + dataSet.getNumFeatures());
}
}
f = classifier.predictAssignmentProb(
xz.toVector(dataSet.getNumFeatures() + dataSet.getNumClasses()), truth);
}
scores[i][j] = f;
}));
System.out.println("Finished evaluating fixed noise model p(y_n | z) ...");
this.targets = new double[dataSet.getNumDataPoints()][combinations.size()];
this.probabilities = new double[dataSet.getNumDataPoints()][combinations.size()];
this.updateProbabilities();
if (logger.isDebugEnabled()){
logger.debug("finish constructor");
}
}
private void updateProbabilities(int dataPointIndex){
probabilities[dataPointIndex] = cbm.predictAssignmentProbs(dataSet.getRow(dataPointIndex), combinations);
}
private void updateProbabilities(){
if (logger.isDebugEnabled()){
logger.debug("start updateProbabilities()");
}
IntStream.range(0, dataSet.getNumDataPoints()).parallel().forEach(this::updateProbabilities);
if (logger.isDebugEnabled()){
logger.debug("finish updateProbabilities()");
}
// // todo check probabilities
// for (int i=0;i<dataSet.getNumDataPoints();i++){
// for (int c=0;c<cbm.numComponents;c++){
// if (probabilities[i][c]<0){
// throw new RuntimeException("probability = "+probabilities[i][c]);
// }
// }
// }
}
private void updateTargets(int dataPointIndex){
double[] probs = probabilities[dataPointIndex];
double[] product = new double[probs.length];
double[] s = this.scores[dataPointIndex];
for (int j=0;j<probs.length;j++){
product[j] = probs[j]*s[j];
}
double denominator = MathUtil.arraySum(product);
for (int j=0;j<probs.length;j++){
targets[dataPointIndex][j] = product[j]/denominator;
}
}
private void updateTargets(){
if (logger.isDebugEnabled()){
logger.debug("start updateTargets()");
}
IntStream.range(0, dataSet.getNumDataPoints()).parallel().forEach(this::updateTargets);
if (logger.isDebugEnabled()){
logger.debug("finish updateTargets()");
}
}
private void updateBinaryTargets(){
if (logger.isDebugEnabled()){
logger.debug("start updateBinaryTargets()");
}
IntStream.range(0, dataSet.getNumDataPoints()).parallel()
.forEach(this::updateBinaryTarget);
if (logger.isDebugEnabled()){
logger.debug("finish updateBinaryTargets()");
}
// System.out.println(Arrays.deepToString(binaryTargetsDistributions));
}
private void updateBinaryTarget(int dataPointIndex){
double[] comProb = targets[dataPointIndex];
double[] marginals = new double[cbm.getNumClasses()];
for (int c=0;c<comProb.length;c++){
MultiLabel multiLabel = combinations.get(c);
double prob = comProb[c];
for (int l: multiLabel.getMatchedLabels()){
marginals[l] += prob;
}
}
for (int l=0;l<cbm.getNumClasses();l++){
// the sum may exceed 1 due to numerical issues
// when that happens, the probability of the negative class would be negative
// we need to add some protection
if (marginals[l]>1){
marginals[l]=1;
}
binaryTargetsDistributions[l][dataPointIndex][0] = 1-marginals[l];
binaryTargetsDistributions[l][dataPointIndex][1] = marginals[l];
}
}
public void setPriorVarianceMultiClass(double priorVarianceMultiClass) {
this.priorVarianceMultiClass = priorVarianceMultiClass;
}
public void setPriorVarianceBinary(double priorVarianceBinary) {
this.priorVarianceBinary = priorVarianceBinary;
}
public void setNumLeavesBinary(int numLeavesBinary) {
this.numLeavesBinary = numLeavesBinary;
}
public void setNumLeavesMultiClass(int numLeavesMultiClass) {
this.numLeavesMultiClass = numLeavesMultiClass;
}
public void setShrinkageBinary(double shrinkageBinary) {
this.shrinkageBinary = shrinkageBinary;
}
public void setShrinkageMultiClass(double shrinkageMultiClass) {
this.shrinkageMultiClass = shrinkageMultiClass;
}
public void setNumIterationsBinary(int numIterationsBinary) {
this.numIterationsBinary = numIterationsBinary;
}
public void setNumIterationsMultiClass(int numIterationsMultiClass) {
this.numIterationsMultiClass = numIterationsMultiClass;
}
public void optimize() {
while (true) {
iterate();
if (terminator.shouldTerminate()) {
break;
}
}
}
public void iterate() {
updateTargets();
updateBinaryTargets();
updateGamma();
updateMultiClassClassifier();
updateBinaryClassifiers();
updateProbabilities();
this.terminator.add(objective());
}
private void updateGamma() {
if (logger.isDebugEnabled()){
logger.debug("start updateGamma()");
}
IntStream.range(0, dataSet.getNumDataPoints()).parallel()
.forEach(this::updateGamma);
if (logger.isDebugEnabled()){
logger.debug("finish updateGamma()");
}
// System.out.println("gamma="+Arrays.deepToString(gammas));
}
private void updateGamma(int n) {
Vector x = dataSet.getRow(n);
BMDistribution bmDistribution = cbm.computeBM(x);
// size = combination * components
List<double[]> logPosteriors = new ArrayList<>();
for (int c=0;c<combinations.size();c++){
MultiLabel combination = combinations.get(c);
double[] pos = bmDistribution.logPosteriorMembership(combination);
logPosteriors.add(pos);
}
double[] sums = new double[cbm.numComponents];
for (int k=0;k<cbm.numComponents;k++){
double sum = 0;
for (int c=0;c<combinations.size();c++){
sum += targets[n][c]*logPosteriors.get(c)[k];
}
sums[k] = sum;
}
double[] posterior = MathUtil.softmax(sums);
for (int k=0; k<cbm.numComponents; k++) {
gammas[n][k] = posterior[k];
gammasT[k][n] = posterior[k];
}
}
private void updateBinaryClassifiers() {
if (logger.isDebugEnabled()){
logger.debug("start updateBinaryClassifiers()");
}
IntStream.range(0, cbm.numComponents).forEach(this::updateBinaryClassifiers);
if (logger.isDebugEnabled()){
logger.debug("finish updateBinaryClassifiers()");
}
}
//todo pay attention to parallelism
private void updateBinaryClassifiers(int component){
String type = cbm.getBinaryClassifierType();
switch (type){
case "lr":
IntStream.range(0, cbm.numLabels).parallel().forEach(l-> updateBinaryLogisticRegression(component,l));
break;
case "boost":
// no parallel for boosting
IntStream.range(0, cbm.numLabels).forEach(l -> updateBinaryBoosting(component, l));
break;
case "elasticnet":
IntStream.range(0, cbm.numLabels).parallel().forEach(l-> updateBinaryLogisticRegressionEL(component,l));
break;
default:
throw new IllegalArgumentException("unknown type: " + cbm.getBinaryClassifierType());
}
}
private void updateBinaryBoosting(int componentIndex, int labelIndex){
int numIterations = numIterationsBinary;
double shrinkage = shrinkageBinary;
LKBoost boost = (LKBoost)this.cbm.binaryClassifiers[componentIndex][labelIndex];
RegTreeConfig regTreeConfig = new RegTreeConfig()
.setMaxNumLeaves(numLeavesBinary);
RegTreeFactory regTreeFactory = new RegTreeFactory(regTreeConfig);
regTreeFactory.setLeafOutputCalculator(new LKBOutputCalculator(2));
LKBoostOptimizer optimizer = new LKBoostOptimizer(boost,dataSet, regTreeFactory,
gammasT[componentIndex], binaryTargetsDistributions[labelIndex]);
optimizer.setShrinkage(shrinkage);
optimizer.initialize();
optimizer.iterate(numIterations);
}
private void updateBinaryLogisticRegression(int componentIndex, int labelIndex){
RidgeLogisticOptimizer ridgeLogisticOptimizer;
// System.out.println("for component "+componentIndex+" label "+labelIndex);
// System.out.println("weights="+Arrays.toString(gammasT[componentIndex]));
// System.out.println("binary target distribution="+Arrays.deepToString(binaryTargetsDistributions[labelIndex]));
// double posProb = 0;
// double negProb = 0;
// for (int i=0;i<dataSet.getNumDataPoints();i++){
// posProb += gammasT[componentIndex][i] * binaryTargetsDistributions[labelIndex][i][1];
// negProb += gammasT[componentIndex][i] * binaryTargetsDistributions[labelIndex][i][0];
// }
// System.out.println("sum pos prob = "+posProb);
// System.out.println("sum neg prob = "+negProb);
// no parallelism
ridgeLogisticOptimizer = new RidgeLogisticOptimizer((LogisticRegression)cbm.binaryClassifiers[componentIndex][labelIndex],
dataSet, gammasT[componentIndex], binaryTargetsDistributions[labelIndex], priorVarianceBinary, false);
//TODO maximum iterations
ridgeLogisticOptimizer.getOptimizer().getTerminator().setMaxIteration(10);
ridgeLogisticOptimizer.optimize();
// if (logger.isDebugEnabled()){
// logger.debug("for cluster "+clusterIndex+" label "+labelIndex+" history= "+ridgeLogisticOptimizer.getOptimizer().getTerminator().getHistory());
// }
}
private void updateBinaryLogisticRegressionEL(int componentIndex, int labelIndex) {
ElasticNetLogisticTrainer elasticNetLogisticTrainer = new ElasticNetLogisticTrainer.Builder((LogisticRegression)
cbm.binaryClassifiers[componentIndex][labelIndex], dataSet, 2, binaryTargetsDistributions[labelIndex], gammasT[componentIndex])
.setRegularization(regularizationBinary)
.setL1Ratio(l1RatioBinary)
.setLineSearch(lineSearch).build();
//TODO: maximum iterations
elasticNetLogisticTrainer.getTerminator().setMaxIteration(10);
elasticNetLogisticTrainer.optimize();
}
private void updateMultiClassClassifier(){
if (logger.isDebugEnabled()){
logger.debug("start updateMultiClassClassifier()");
}
String type = cbm.getMultiClassClassifierType();
switch (type){
case "lr":
updateMultiClassLR();
break;
case "boost":
updateMultiClassBoost();
break;
case "elasticnet":
updateMultiClassEL();
break;
default:
throw new IllegalArgumentException("unknown type: " + cbm.getMultiClassClassifierType());
}
if (logger.isDebugEnabled()){
logger.debug("finish updateMultiClassClassifier()");
}
}
private void updateMultiClassEL() {
ElasticNetLogisticTrainer elasticNetLogisticTrainer = new ElasticNetLogisticTrainer.Builder((LogisticRegression)
cbm.multiClassClassifier, dataSet, cbm.multiClassClassifier.getNumClasses(), gammas)
.setRegularization(regularizationMultiClass)
.setL1Ratio(l1RatioMultiClass)
.setLineSearch(lineSearch).build();
// TODO: maximum iterations
elasticNetLogisticTrainer.getTerminator().setMaxIteration(10);
elasticNetLogisticTrainer.optimize();
}
private void updateMultiClassLR() {
// parallel
RidgeLogisticOptimizer ridgeLogisticOptimizer = new RidgeLogisticOptimizer((LogisticRegression)cbm.multiClassClassifier,
dataSet, gammas, priorVarianceMultiClass, true);
//TODO maximum iterations
ridgeLogisticOptimizer.getOptimizer().getTerminator().setMaxIteration(10);
ridgeLogisticOptimizer.optimize();
}
private void updateMultiClassBoost() {
int numComponents = cbm.numComponents;
int numIterations = numIterationsMultiClass;
double shrinkage = shrinkageMultiClass;
LKBoost boost = (LKBoost)this.cbm.multiClassClassifier;
RegTreeConfig regTreeConfig = new RegTreeConfig()
.setMaxNumLeaves(numLeavesMultiClass);
RegTreeFactory regTreeFactory = new RegTreeFactory(regTreeConfig);
regTreeFactory.setLeafOutputCalculator(new LKBOutputCalculator(numComponents));
LKBoostOptimizer optimizer = new LKBoostOptimizer(boost, dataSet, regTreeFactory, gammas);
optimizer.setShrinkage(shrinkage);
optimizer.initialize();
optimizer.iterate(numIterations);
}
// public static Object[] getColumn(Object[][] array, int index){
// Object[] column = new Object[array[0].length]; // Here I assume a rectangular 2D array!
// for(int i=0; i<column.length; i++){
// column[i] = array[i][index];
// }
// return column;
// }
private double objective(int dataPointIndex){
double sum = 0;
double[] p = probabilities[dataPointIndex];
double[] s = scores[dataPointIndex];
for (int j=0;j<p.length;j++){
sum += p[j]*s[j];
}
return -Math.log(sum);
}
public double objective(){
if (logger.isDebugEnabled()){
logger.debug("start objective()");
}
double obj= IntStream.range(0, dataSet.getNumDataPoints()).parallel()
.mapToDouble(this::objective).sum();
if (logger.isDebugEnabled()){
logger.debug("finish obj");
}
double penalty = penalty();
if (logger.isDebugEnabled()){
logger.debug("finish penalty");
}
if (logger.isDebugEnabled()){
logger.debug("finish objective()");
}
return obj+penalty;
}
// regularization
private double penalty(){
double sum = 0;
LogisticLoss logisticLoss = new LogisticLoss((LogisticRegression) cbm.multiClassClassifier,
dataSet, gammas, priorVarianceMultiClass, true);
sum += logisticLoss.penaltyValue();
for (int k=0;k<cbm.numComponents;k++){
for (int l=0;l<cbm.getNumClasses();l++){
sum += new LogisticLoss((LogisticRegression) cbm.binaryClassifiers[k][l],
dataSet, gammasT[k], binaryTargetsDistributions[l], priorVarianceBinary, true).penaltyValue();
}
}
return sum;
}
// //TODO: use direct obj
// public double getObjective() {
// return multiClassClassifierObj() + binaryObj() +(1-temperature)*getEntropy();
// }
// private double getMStepObjective() {
// KLLogisticLoss logisticLoss = new KLLogisticLoss(bmmClassifier.multiClassClassifier,
// dataSet, gammas, priorVarianceMultiClass);
// // Q function for \Thata + gamma.entropy and Q function for Weights
// return logisticLoss.getValue() + binaryLRObj();
// }
private double getEntropy() {
return IntStream.range(0, dataSet.getNumDataPoints()).parallel()
.mapToDouble(this::getEntropy).sum();
}
private double getEntropy(int i) {
return Entropy.entropy(gammas[i]);
}
private double binaryObj(){
return IntStream.range(0, cbm.numComponents).mapToDouble(this::binaryObj).sum();
}
private double binaryObj(int clusterIndex){
return IntStream.range(0, cbm.numLabels).parallel().mapToDouble(l->binaryObj(clusterIndex,l)).sum();
}
private double binaryObj(int clusterIndex, int classIndex){
String type = cbm.getBinaryClassifierType();
switch (type){
case "lr":
return binaryLRObj(clusterIndex, classIndex);
case "boost":
return binaryBoostObj(clusterIndex, classIndex);
case "elasticnet":
// todo
return binaryLRObj(clusterIndex, classIndex);
default:
throw new IllegalArgumentException("unknown type: " + type);
}
}
// consider regularization penalty
private double binaryLRObj(int clusterIndex, int classIndex) {
LogisticLoss logisticLoss = new LogisticLoss((LogisticRegression) cbm.binaryClassifiers[clusterIndex][classIndex],
dataSet, gammasT[clusterIndex], binaryTargetsDistributions[classIndex], priorVarianceBinary, false);
return logisticLoss.getValue();
}
private double binaryBoostObj(int clusterIndex, int classIndex){
Classifier.ProbabilityEstimator estimator = cbm.binaryClassifiers[clusterIndex][classIndex];
double[][] targets = binaryTargetsDistributions[classIndex];
double[] weights = gammasT[clusterIndex];
return KLDivergence.kl(estimator, dataSet, targets, weights);
}
private double multiClassClassifierObj(){
String type = cbm.getMultiClassClassifierType();
switch (type){
case "lr":
return multiClassLRObj();
case "boost":
return multiClassBoostObj();
//TODO: change to elastic net
case "elasticnet":
return multiClassLRObj();
default:
throw new IllegalArgumentException("unknown type: " + type);
}
}
private double multiClassBoostObj(){
Classifier.ProbabilityEstimator estimator = cbm.multiClassClassifier;
double[][] targets = gammas;
return KLDivergence.kl(estimator,dataSet,targets);
}
private double multiClassLRObj(){
LogisticLoss logisticLoss = new LogisticLoss((LogisticRegression) cbm.multiClassClassifier,
dataSet, gammas, priorVarianceMultiClass, true);
return logisticLoss.getValue();
}
public Terminator getTerminator() {
return terminator;
}
public double[][] getGammas() {
return gammas;
}
public double[][] getPIs() {
double[][] PIs = new double[dataSet.getNumDataPoints()][cbm.getNumComponents()];
for (int n=0; n<PIs.length; n++) {
double[] logProbs = cbm.multiClassClassifier.predictLogClassProbs(dataSet.getRow(n));
for (int k=0; k<PIs[n].length; k++) {
PIs[n][k] = Math.exp(logProbs[k]);
}
}
return PIs;
}
// For ElasticEet Parameters
public double getRegularizationMultiClass() {
return regularizationMultiClass;
}
public void setRegularizationMultiClass(double regularizationMultiClass) {
this.regularizationMultiClass = regularizationMultiClass;
}
public double getRegularizationBinary() {
return regularizationBinary;
}
public void setRegularizationBinary(double regularizationBinary) {
this.regularizationBinary = regularizationBinary;
}
public boolean isLineSearch() {
return lineSearch;
}
public void setLineSearch(boolean lineSearch) {
this.lineSearch = lineSearch;
}
public double getL1RatioBinary() {
return l1RatioBinary;
}
public void setL1RatioBinary(double l1RatioBinary) {
this.l1RatioBinary = l1RatioBinary;
}
public double getL1RatioMultiClass() {
return l1RatioMultiClass;
}
public void setL1RatioMultiClass(double l1RatioMultiClass) {
this.l1RatioMultiClass = l1RatioMultiClass;
}
}
| 38.893939 | 196 | 0.634125 |
3389cb7e7044cdd5c084968392ec48ded6d7106e | 2,621 | /*******************************************************************************
* Copyright 2017-present, PureLauncher Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.zql.android.purelauncher.adapter.model.utils.expr;
import com.zqlite.android.logly.Logly;
import java.util.Hashtable;
import java.util.Set;
/**
* A variable is a simple expression with a name (like "x") and a
* settable value.
*/
public class Variable extends Expr {
private static Hashtable variables = new Hashtable();
/**
* Return a unique variable named `name'. There can be only one
* variable with the same name returned by this method; that is,
* make(s1) == make(s2) if and only if s1.equals(s2).
* @param name the variable's name
* @return the variable; create it initialized to 0 if it doesn't
* yet exist */
static public synchronized Variable make(String name) {
Variable result = (Variable) variables.get(name);
if (result == null)
variables.put(name, result = new Variable(name));
return result;
}
private String name;
private double val;
/**
* Create a new variable, with initial value 0.
* @param name the variable's name
*/
public Variable(String name) {
this.name = name; val = 0;
}
/** Return the name. */
public String toString() { return name; }
/** Get the value.
* @return the current value */
public double value() {
return val;
}
/** Set the value.
* @param value the new value */
public void setValue(double value) {
val = value;
}
public static void clean(){
variables.clear();
Variable pi = Variable.make("pi");
pi.setValue(Math.PI);
}
public static boolean isEmpty(String key){
Set<String> keys = variables.keySet();
for(String k : keys){
if(k.equals(key)){
return true;
}
}
return false;
}
}
| 29.449438 | 80 | 0.595574 |
954b9f335c8c3168938637673bb4323ef108a5a0 | 12,382 | /* Copyright (C) 2001 ACUNIA
This file is part of Mauve.
Mauve is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
Mauve 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 Mauve; see the file COPYING. If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// Tags: JDK1.2
// Uses: Entry ESet EIterator
package gnu.testlet.java.util.AbstractMap;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
import java.util.*;
/**
* Written by ACUNIA. <br>
* <br>
* this file contains test for java.util.AbstractMap <br>
*
*/
public class AcuniaAbstractMapTest extends AbstractMap implements Testlet {
protected TestHarness th;
public void test(TestHarness harness) {
th = harness;
test_get();
test_containsKey();
test_containsValue();
test_isEmpty();
test_size();
test_clear();
test_put();
test_putAll();
test_remove();
test_entrySet();
test_keySet();
test_values();
test_equals();
test_hashCode();
test_toString();
}
protected AcuniaAbstractMapTest buildHT() {
AcuniaAbstractMapTest t = new AcuniaAbstractMapTest();
String s;
for (int i = 0; i < 15; i++) {
s = "a" + i;
t.put(s, s + " value");
}
return t;
}
/**
* implemented. <br>
*
*/
public void test_get() {
th.checkPoint("get(java.lang.Object)java.lang.Object");
AcuniaAbstractMapTest ehm = buildHT();
Object o;
String s = "a1";
o = ehm.get(s);
th.check((s + " value").equals(o), "checking return value");
o = ehm.get(null);
th.check(o == null);
o = ehm.get(s + " value");
th.check(o == null);
ehm.put(null, s);
o = ehm.get(null);
th.check(s.equals(o));
}
/**
* implemented. <br>
*
*/
public void test_containsKey() {
th.checkPoint("containsKey(java.lang.Object)boolean");
AcuniaAbstractMapTest ehm = buildHT();
th.check(!ehm.containsKey(null), "null not there");
ehm.put(null, "test");
th.check(ehm.containsKey(null), "null is in there");
th.check(ehm.containsKey("a1"), "object is in there");
th.check(!ehm.containsKey("a1 value"), "object is not in there -- 1");
th.check(!ehm.containsKey(new Object()), "object is not in there -- 2");
}
/**
* implemented. <br>
*
*/
public void test_containsValue() {
th.checkPoint("containsValue(java.lang.Object)boolean");
AcuniaAbstractMapTest ehm = buildHT();
th.check(!ehm.containsValue(null), "null not there");
ehm.put(null, null);
th.check(ehm.containsValue(null), "null is in there");
th.check(!ehm.containsValue("a1"), "object is not in there -- 1");
th.check(ehm.containsValue("a1 value"), "object is in there -- 1");
th.check(!ehm.containsValue(new Object()), "object is not in there -- 2");
}
/**
* implemented. <br>
*
*/
public void test_isEmpty() {
th.checkPoint("isEmpty()boolean");
AcuniaAbstractMapTest ehm = new AcuniaAbstractMapTest();
th.check(ehm.isEmpty(), "true");
ehm = buildHT();
th.check(!ehm.isEmpty(), "false");
}
/**
* not implemented. <br>
* Abstract Method
*/
public void test_size() {
th.checkPoint("()");
}
/**
* implemented. <br>
*
*/
public void test_clear() {
th.checkPoint("clear()void");
AcuniaAbstractMapTest ehm = buildHT();
ehm.clear();
th.check(ehm.isEmpty(), "true");
}
/**
* implemented. <br>
*
*/
public void test_put() {
th.checkPoint("put(java.lang.Object,java.lang.Object)java.lang.Object");
AcuniaAbstractMapTest ehm = buildHT();
ehm.set_edit(false);
try {
ehm.put("a", "b");
th.fail("should throw an UnsupportedOperationException");
} catch (UnsupportedOperationException uoe) {
th.check(true);
}
}
/**
* implemented. <br>
*
*/
public void test_putAll() {
th.checkPoint("putAll(java.util.Map)void");
Hashtable ht = new Hashtable();
AcuniaAbstractMapTest ehm = new AcuniaAbstractMapTest();
th.check(ehm.equals(ht), "true -- both empty");
ht.put("a", "b");
ht.put("c", "d");
ht.put("e", "f");
ehm.putAll(ht);
th.check(ehm.equals(ht), "true -- 1");
ht.put("a1", "f");
ht.put("e", "b");
ehm.putAll(ht);
th.check(ehm.equals(ht), "true -- 2");
ehm = buildHT();
try {
ehm.putAll(ht);
th.check(true, "putAll: " + ht);
} catch (NoSuchElementException nse) {
th.check(false, "putAll: " + ht);
}
th.check(ehm.size() == 18, "added three elements");
th.check("f".equals(ehm.get("a1")), "overwritten old value");
}
/**
* implemented. <br>
*
*/
public void test_remove() {
th.checkPoint("remove(java.lang.Object)java.lang.Object");
AcuniaAbstractMapTest ehm = buildHT();
ehm.remove("a1");
th.check(!ehm.containsKey("a1"), "key removed -- 1");
th.check(!ehm.containsValue("a1 value"), "value removed -- 1");
ehm.remove("a0");
th.check(!ehm.containsKey("a0"), "key removed -- 2");
th.check(!ehm.containsValue("a0 value"), "value removed -- 2");
for (int i = 2; i < 15; i++) {
ehm.remove("a" + i);
}
th.check(ehm.isEmpty());
}
/**
* not implemented. <br>
* Abstract Method
*/
public void test_entrySet() {
th.checkPoint("()");
}
/**
* implemented. <br>
* check only on methods not inherited from AbstractSet
*/
public void test_keySet() {
th.checkPoint("keySet()java.util.Set");
AcuniaAbstractMapTest ehm = buildHT();
Set s = ehm.keySet();
th.check(s.size() == 15);
ehm.put(null, "test");
th.check(s.size() == 16);
th.check(s.contains("a1"), "does contain a1");
th.check(s.contains(null), "does contain null");
th.check(!s.contains(new Object()), "does contain new Object");
th.check(!s.contains("test"), "does contain test");
th.check(s == ehm.keySet(), "same Set is returned");
Iterator it = s.iterator();
Vector v = ehm.getKeyV();
int i;
Object o;
for (i = 0; i < 16; i++) {
o = it.next();
th.check(v.indexOf(o) == 0, "order is not respected");
if (!v.remove(o)) {
th.debug("didn't find " + o);
}
}
it = s.iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
th.check(s.isEmpty(), "everything is removed");
s = ehm.keySet();
th.check(s.isEmpty(), "new Set is also empty");
ehm.put("a", "B");
th.check(!s.isEmpty(), "Set is updated by underlying actions");
}
/**
* implemented. <br>
* check only on methods not inherited from AbstractCollection
*/
public void test_values() {
th.checkPoint("values()java.util.Collection");
AcuniaAbstractMapTest ehm = buildHT();
Collection s = ehm.values();
th.check(s.size() == 15);
ehm.put(null, "test");
ehm.put("a10", null);
th.check(s.size() == 16);
th.check(s.contains("a1 value"), "does contain a1 value");
th.check(s.contains(null), "does contain null");
th.check(!s.contains(new Object()), "does contain new Object");
th.check(s.contains("test"), "does contain test");
th.check(!s.contains("a1"), "does not contain a1");
th.check(s == ehm.values(), "same Set is returned");
Iterator it = s.iterator();
Vector v = ehm.getValuesV();
int i;
Object o;
for (i = 0; i < 16; i++) {
o = it.next();
th.check(v.indexOf(o) == 0, "order is not respected");
if (!v.remove(o)) {
th.debug("didn't find " + o);
}
}
it = s.iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
th.check(s.isEmpty(), "everything is removed");
s = ehm.values();
th.check(s.isEmpty(), "new Set is also empty");
ehm.put("a", "B");
th.check(!s.isEmpty(), "Set is updated by underlying actions");
}
/**
* implemented. <br>
*
*/
public void test_equals() {
th.checkPoint("equals(java.lang.Object)boolean");
Hashtable ht = new Hashtable();
AcuniaAbstractMapTest ehm = new AcuniaAbstractMapTest();
th.check(ehm.equals(ht), "true -- both empty");
ht.put("a", "b");
ht.put("c", "d");
ht.put("e", "f");
ehm.put("a", "b");
ehm.put("c", "d");
ehm.put("e", "f");
th.check(ehm.equals(ht), "true -- same key && values");
ht.put("a", "f");
th.check(!ehm.equals(ht), "false -- same key && diff values");
ht.put("e", "b");
th.check(!ehm.equals(ht), "false -- key with diff values");
th.check(!ehm.equals(ht.entrySet()), "false -- no Map");
th.check(!ehm.equals(new Object()), "false -- Object is no Map");
th.check(!ehm.equals(null), "false -- Object is null");
}
/**
* implemented. <br>
*
*/
public void test_hashCode() {
th.checkPoint("hashCode()int");
AcuniaAbstractMapTest ehm = new AcuniaAbstractMapTest();
th.check(ehm.hashCode() == 0, "hashCode of Empty Map is 0, got " + ehm.hashCode());
int hash = 0;
Iterator s = ehm.entrySet().iterator();
while (s.hasNext()) {
hash += s.next().hashCode();
}
th.check(ehm.hashCode(), hash, "hashCode of Empty Map -- checking Algorithm");
}
/**
* implemented. <br>
*
*/
public void test_toString() {
th.checkPoint("toString()java.lang.String");
AcuniaAbstractMapTest ehm = new AcuniaAbstractMapTest();
th.check("{}".equals(ehm.toString()), "checking empty Map");
ehm.put("a", "b");
th.debug(ehm.toString());
th.check("{a=b}".equals(ehm.toString()), "checking Map with one element");
ehm.put("c", "d");
ehm.put("e", "f");
th.debug(ehm.toString());
th.check("{a=b, c=d, e=f}".equals(ehm.toString()), "checking Map with three elements");
}
public String toString() {
return super.toString();
}
// The following field and methods are needed to use this class as an
// implementation test for AbstractMap
//
Vector keys = new Vector();
Vector values = new Vector();
private boolean edit = true;
boolean deleteInAM(Object e) {
if (!keys.contains(e)) {
return false;
}
values.remove(keys.indexOf(e));
return keys.remove(e);
}
public Vector getKeyV() {
return (Vector) keys.clone();
}
public Vector getValuesV() {
return (Vector) values.clone();
}
public AcuniaAbstractMapTest() {
super();
}
public Set entrySet() {
return new ESet(this);
}
public Object put(Object key, Object value) {
if (edit) {
if (keys.contains(key)) {
return values.set(keys.indexOf(key), value);
}
values.add(value);
keys.add(key);
return null;
}
return super.put(key, value);
}
public void set_edit(boolean b) {
edit = b;
}
}
| 29.341232 | 95 | 0.536424 |
434788f207b2d649b11725d1ceaf4325cab4f6f0 | 273 | package com.fsck.k9.controller;
import com.fsck.k9.Account;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Message;
import java.util.List;
public interface MessageActor {
void act(final Account account, final Folder folder, final List<Message> messages);
}
| 22.75 | 87 | 0.772894 |
1656e2200a0c664af464d2aa3f643c8543e82b9d | 408 | package com.leandroasouza.restapidemo;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;
/**
* Created by leandrosouza on 24/06/2016.
*/
public interface BookAPI {
@Headers({
"content-type: application/json",
"cache-control: no-cache"
})
@GET("getBooks")
Call<List<Book>> getBooks();
}
| 18.545455 | 46 | 0.625 |
0d5a5634e3d269da5d99ea50a98c7f5a4eb9369b | 5,943 | package pdftable;
import java.nio.file.Path;
/**
* Image conversion settings.
*/
public class PdfTableSettings {
public static class PdfTableSettingsBuilder {
// --------------
// DEFAULT VALUES
// --------------
// DPI SETTINGS
private static final int DEFAULT_PDF_DPI = 72;
private int pdfRenderingDpi = 120;
// CANNY EDGE DETECTION FLAG
private boolean cannyFiltering = false;
// BINARY INVERTED THRESHOLD SETTINGS
private double bitThreshold = 150;
private double bitMaxVal = 255;
// CANNY FILTER SETTINGS
private double cannyThreshold1 = 50;
private double cannyThreshold2 = 200;
private int cannyApertureSize = 5;
private boolean cannyL2Gradient = false;
// BOUNDING RECT PARAMS
private double approxDistScaleFactor = 0.02;
// DEBUG IMAGES PARAMS
private boolean debugImages = true;
private Path debugFileOutputDir;
private String debugFilename;
public PdfTableSettingsBuilder setPdfRenderingDpi(int pdfRenderingDpi) {
this.pdfRenderingDpi = pdfRenderingDpi;
return this;
}
public PdfTableSettingsBuilder setCannyFiltering(boolean cannyFiltering) {
this.cannyFiltering = cannyFiltering;
return this;
}
public PdfTableSettingsBuilder setBitThreshold(double bitThreshold) {
this.bitThreshold = bitThreshold;
return this;
}
public PdfTableSettingsBuilder setBitMaxVal(double bitMaxVal) {
this.bitMaxVal = bitMaxVal;
return this;
}
public PdfTableSettingsBuilder setCannyThreshold1(double cannyThreshold1) {
this.cannyThreshold1 = cannyThreshold1;
return this;
}
public PdfTableSettingsBuilder setCannyThreshold2(double cannyThreshold2) {
this.cannyThreshold2 = cannyThreshold2;
return this;
}
public PdfTableSettingsBuilder setCannyApertureSize(int cannyApertureSize) {
this.cannyApertureSize = cannyApertureSize;
return this;
}
public PdfTableSettingsBuilder setCannyL2Gradient(boolean cannyL2Gradient) {
this.cannyL2Gradient = cannyL2Gradient;
return this;
}
public PdfTableSettingsBuilder setApproxDistScaleFactor(double approxDistScaleFactor) {
this.approxDistScaleFactor = approxDistScaleFactor;
return this;
}
public PdfTableSettingsBuilder setDebugImages(boolean debugImages) {
this.debugImages = debugImages;
return this;
}
public PdfTableSettingsBuilder setDebugFileOutputDir(Path debugFileOutputDir) {
this.debugFileOutputDir = debugFileOutputDir;
return this;
}
public PdfTableSettingsBuilder setDebugFilename(String debugFilename) {
this.debugFilename = debugFilename;
return this;
}
public PdfTableSettings build() {
return new PdfTableSettings(this);
}
}
// DPI SETTINGS
private int defaultPdfDpi;
private int pdfRenderingDpi;
// CANNY EDGE DETECTION FLAG
private boolean cannyFiltering;
// BINARY INVERTED THRESHOLD SETTINGS
private double bitThreshold;
private double bitMaxVal;
// CANNY FILTER SETTINGS
private double cannyThreshold1;
private double cannyThreshold2;
private int cannyApertureSize;
private boolean cannyL2Gradient;
// BOUNDING RECT PARAMS
private double approxDistScaleFactor;
// DEBUG IMAGES PARAMS
private boolean debugImages;
private Path debugFileOutputDir;
private String debugFilename;
private PdfTableSettings(PdfTableSettingsBuilder builder) {
this.defaultPdfDpi = PdfTableSettingsBuilder.DEFAULT_PDF_DPI;
this.pdfRenderingDpi = builder.pdfRenderingDpi;
this.cannyFiltering = builder.cannyFiltering;
this.bitThreshold = builder.bitThreshold;
this.bitMaxVal = builder.bitMaxVal;
this.cannyThreshold1 = builder.cannyThreshold1;
this.cannyThreshold2 = builder.cannyThreshold2;
this.cannyApertureSize = builder.cannyApertureSize;
this.cannyL2Gradient = builder.cannyL2Gradient;
this.approxDistScaleFactor = builder.approxDistScaleFactor;
this.debugImages = builder.debugImages;
this.debugFileOutputDir = builder.debugFileOutputDir;
this.debugFilename = builder.debugFilename;
}
public PdfTableSettings() {
this(new PdfTableSettingsBuilder());
}
public static PdfTableSettingsBuilder getBuilder() {
return new PdfTableSettingsBuilder();
}
public int getDefaultPdfDpi() {
return defaultPdfDpi;
}
public int getPdfRenderingDpi() {
return pdfRenderingDpi;
}
public boolean hasCannyFiltering() {
return cannyFiltering;
}
public double getBitThreshold() {
return bitThreshold;
}
public double getBitMaxVal() {
return bitMaxVal;
}
public double getCannyThreshold1() {
return cannyThreshold1;
}
public double getCannyThreshold2() {
return cannyThreshold2;
}
public int getCannyApertureSize() {
return cannyApertureSize;
}
public boolean hasCannyL2Gradient() {
return cannyL2Gradient;
}
public double getApproxDistScaleFactor() {
return approxDistScaleFactor;
}
public boolean hasDebugImages() {
return debugImages;
}
public Path getDebugFileOutputDir() {
return debugFileOutputDir;
}
public String getDebugFilename() {
return debugFilename;
}
public double getDpiRatio() {
return (double) defaultPdfDpi / pdfRenderingDpi;
}
}
| 28.033019 | 95 | 0.659263 |
6745114b5dd13bc1c7bc942e317c2cbde8c5add2 | 544 | package de.swapab.csvupload.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class CsvUploadController {
@PostMapping(value = "/api/upload/csv")
public String upload(@RequestParam(value = "file") MultipartFile file) {
System.out.println(file.getOriginalFilename());
return "success";
}
}
| 34 | 76 | 0.777574 |
03748d4a995e4f6e5472e9220d84430f8a48c01e | 14,849 | /**
*
*/
package com.transcend.rds.worker;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import com.msi.tough.cf.json.DatabagParameter;
import com.msi.tough.core.Appctx;
import com.msi.tough.core.HibernateUtil;
import com.msi.tough.core.JsonUtil;
import com.msi.tough.model.AccountBean;
import com.msi.tough.model.rds.RdsDbinstance;
import com.msi.tough.model.rds.RdsDbparameterGroup;
import com.msi.tough.model.rds.RdsParameter;
import com.msi.tough.query.ErrorResponse;
import com.msi.tough.query.QueryFaults;
import com.msi.tough.query.ServiceRequestContext;
import com.msi.tough.rds.ValidationManager;
import com.msi.tough.rds.json.RDSConfigDatabagItem;
import com.msi.tough.rds.json.RDSDatabag;
import com.msi.tough.rds.json.RDSParameterGroupDatabagItem;
import com.msi.tough.utils.AccountUtil;
import com.msi.tough.utils.ChefUtil;
import com.msi.tough.utils.ConfigurationUtil;
import com.msi.tough.utils.RDSQueryFaults;
import com.msi.tough.utils.rds.InstanceEntity;
import com.msi.tough.utils.rds.ParameterGroupEntity;
import com.msi.tough.utils.rds.RDSUtilities;
import com.msi.tough.workflow.core.AbstractWorker;
import com.transcend.rds.message.RDSMessage.Parameter;
import com.transcend.rds.message.ResetDBParameterGroupActionMessage.ResetDBParameterGroupActionRequestMessage;
import com.transcend.rds.message.ResetDBParameterGroupActionMessage.ResetDBParameterGroupActionResultMessage;
/**
* @author tdhite
*/
public class ResetDBParameterGroupActionWorker extends
AbstractWorker<ResetDBParameterGroupActionRequestMessage, ResetDBParameterGroupActionResultMessage> {
private final static Logger logger = Appctx
.getLogger(ResetDBParameterGroupActionWorker.class.getName());
/**
* We need a local copy of this doWork to provide the transactional
* annotation. Transaction management is handled by the annotation, which
* can only be on a concrete class.
* @param req
* @return
* @throws Exception
*/
@Transactional
public ResetDBParameterGroupActionResultMessage doWork(
ResetDBParameterGroupActionRequestMessage req) throws Exception {
logger.debug("Performing work for ResetDBParameterGroupAction.");
return super.doWork(req, getSession());
}
/**
* resetDBParameterGroup **************************************************
* This Operation resets the parameters associated with the named
* DBParameterGroup to the engine/system default value. To reset specific
* parameters submit a list of parameters containing at least the
* ParameterName and ApplyMethod. To reset the entire DBParameterGroup
* ResetAllParameters. When resetting the entire group, dynamic parameters
* are updated immediately and static parameters are set to pending-reboot
* to take effect on the next MySQL reboot or RebootDBInstance request.
* Request: DBParameterGroupName (R) ResetAllParameters Array of Parameter
* records Response: DBParameterGroupName Exceptions:
* DBParameterGroupNotFound InvalidDBParameterGroupState Processing 1.
* Confirm that DBParameterGroup exists and is in the appropriate state 2.
* scroll through all of the parameters and call resetParameter 3. Return
* response
*/
@Override
protected ResetDBParameterGroupActionResultMessage doWork0(ResetDBParameterGroupActionRequestMessage req,
ServiceRequestContext context) throws Exception {
ResetDBParameterGroupActionResultMessage.Builder resp = ResetDBParameterGroupActionResultMessage.newBuilder();
final Logger logger = LoggerFactory
.getLogger(this.getClass().getName());
String msg = "";
final Session sess = HibernateUtil.newSession();
try {
sess.beginTransaction();
final AccountBean ac = context.getAccountBean();
final long userId = ac.getId();
final String grpName0 = req.getDbParameterGroupName();
if (grpName0 == null || "".equals(grpName0)) {
throw QueryFaults
.MissingParameter("DBParameterGroupName must be supplied for ResetDBParameterGroup request.");
}
final String grpName = ValidationManager.validateIdentifier(
grpName0, 255, true);
final List<Parameter> pList = req.getParametersList();
final boolean resetAll = req.getResetAllParameters();
final int pListLen = pList.size();
logger.info("resetDBParameterGroup: " + " UserID = " + userId
+ " ParameterGroupName = " + grpName
+ " ResetAllParameters + " + resetAll
+ " Total Number of Listed Parameters = " + pListLen);
if (grpName == null || "".equals(grpName)) {
throw QueryFaults
.MissingParameter("DBParameterGroupName has to be passed for ResetDBParameterGroup request.");
}
if (grpName.equals("default.mysql5.5")) {
throw RDSQueryFaults
.InvalidClientTokenId("You do not have privilege to modify default DBParameterGroup.");
}
// check that DBParameterGroup exists
final RdsDbparameterGroup pGrpRec = ParameterGroupEntity
.getParameterGroup(sess, grpName, ac.getId());
if (pGrpRec == null) {
throw RDSQueryFaults.DBParameterGroupNotFound();
}
// confirm that either resetAll or ParameterList is greater than 1
if (resetAll == false && pListLen < 1) {
msg = "You must either set ResetAllParameters or provide a list of parameters to be reset.";
throw QueryFaults.MissingParameter(msg);
}
// check if conflicting parameters exist
if (resetAll == true && pListLen > 0) {
msg = "You cannot set ResetAllParameters true while providing a list of parameters to be reset.";
throw QueryFaults.InvalidParameterCombination(msg);
}
final Collection<RdsDbinstance> dbInstances = InstanceEntity
.selectDBInstancesByParameterGroup(sess, grpName, -1, ac);
// make sure that all DBInstances using this DBParameterGroup are in
// available state
for (final RdsDbinstance dbinstance : dbInstances) {
if (!dbinstance.getDbinstanceStatus().equals(
RDSUtilities.STATUS_AVAILABLE)) {
throw RDSQueryFaults
.InvalidDBParameterGroupState("Currently there are DBInstance(s) that use this DBParameterGroup and it"
+ " is not in available state.");
}
}
// reset the parameters in the DB
RdsDbparameterGroup parent = null;
List<RdsParameter> forRebootPending = null;
if (resetAll) {
final List<RdsParameter> params = pGrpRec.getParameters();
/*
* for(RdsParameter param : params){
* if(param.getApplyType().equals
* (RDSUtilities.PARM_APPTYPE_DYNAMIC)){ sess.delete(param); } }
*/
final String paramGrpFamily = pGrpRec
.getDbparameterGroupFamily();
final AccountBean sac = AccountUtil.readAccount(sess, 1L);
if (paramGrpFamily.toUpperCase().equals("MYSQL5.1")) {
logger.debug("Inserting Parameters into " + grpName
+ " with MySQL5.1 family Parameters");
parent = ParameterGroupEntity.getParameterGroup(sess,
"default.mysql5.1", sac.getId());
logger.debug("There are " + parent.getParameters().size()
+ " parameters to copy.");
ParameterGroupEntity.copyAndSetDynamicParamGroup(sess,
pGrpRec, parent.getParameters(), userId);
} else if (paramGrpFamily.toUpperCase().equals("MYSQL5.5")) {
logger.debug("Inserting Parameters into " + grpName
+ " with MySQL5.5 family Parameters");
parent = ParameterGroupEntity.getParameterGroup(sess,
"default.mysql5.5", sac.getId());
logger.debug("There are " + parent.getParameters().size()
+ " parameters to copy.");
ParameterGroupEntity.copyAndSetDynamicParamGroup(sess,
pGrpRec, parent.getParameters(), userId);
}
} else {
final String paramGrpFamily = pGrpRec
.getDbparameterGroupFamily();
final AccountBean sac = AccountUtil.readAccount(sess, 1L);
if (paramGrpFamily.toUpperCase().equals("MYSQL5.1")) {
parent = ParameterGroupEntity.getParameterGroup(sess,
"default.mysql5.1", sac.getId());
} else if (paramGrpFamily.toUpperCase().equals("MYSQL5.5")) {
parent = ParameterGroupEntity.getParameterGroup(sess,
"default.mysql5.5", sac.getId());
}
if (parent == null) {
throw RDSQueryFaults.InternalFailure();
}
forRebootPending = new LinkedList<RdsParameter>();
for (final Parameter p : pList) {
final RdsParameter target = ParameterGroupEntity
.getParameter(sess, grpName, p.getParameterName(),
userId);
if (target == null) {
throw RDSQueryFaults.InvalidParameterValue(p
.getParameterName()
+ " parameter does not exist.");
}
logger.debug("Current target parameter: "
+ target.toString());
if (!target.getIsModifiable()) {
throw RDSQueryFaults.InvalidParameterValue(p
.getParameterName()
+ " is not modifiable parameter.");
} else if (p.getApplyMethod().equals(
RDSUtilities.PARM_APPMETHOD_IMMEDIATE)) {
if (target.getApplyType().equals(
RDSUtilities.PARM_APPTYPE_STATIC)) {
throw QueryFaults
.InvalidParameterCombination(target
.getParameterName()
+ " is not dynamic. You can only"
+ " use \"pending-reboot\" as valid ApplyMethod for this parameter.");
}
final RdsParameter original = ParameterGroupEntity
.getParameter(sess,
parent.getDbparameterGroupName(),
p.getParameterName(), 1L);
if (original == null) {
throw RDSQueryFaults.InvalidParameterValue(p
.getParameterName()
+ " could not be found in " + grpName);
}
target.setParameterValue(original.getParameterValue());
target.setSource(original.getSource());
sess.save(target);
} else if (p.getApplyMethod().equals(
RDSUtilities.PARM_APPMETHOD_PENDING)) {
final RdsParameter original = ParameterGroupEntity
.getParameter(sess,
parent.getDbparameterGroupName(),
p.getParameterName(), 1L);
if (original == null) {
throw RDSQueryFaults.InvalidParameterValue(p
.getParameterName()
+ " could not be found in " + grpName);
}
final RdsParameter temp = new RdsParameter();
temp.setParameterName(p.getParameterName());
temp.setApplyMethod(p.getApplyMethod());
temp.setParameterValue(original.getParameterValue());
forRebootPending.add(temp);
}
}
}
// Delete and regenerate the Databag
logger.debug("There are " + dbInstances.size()
+ " databags to modify.");
for (final RdsDbinstance instance : dbInstances) {
logger.debug("Currently updating the databag for DBInstance "
+ instance.getDbinstanceId());
final String databagName = "rds-" + ac.getId() + "-"
+ instance.getDbinstanceId();
logger.debug("Deleting the databag " + databagName);
ChefUtil.deleteDatabagItem(databagName, "config");
final String postWaitUrl = (String) ConfigurationUtil
.getConfiguration(Arrays.asList(new String[] {
"TRANSCEND_URL", instance.getAvailabilityZone() }));
final String servletUrl = (String) ConfigurationUtil
.getConfiguration(Arrays.asList(new String[] {
"SERVLET_URL", instance.getAvailabilityZone() }));
final RDSConfigDatabagItem configDataBagItem = new RDSConfigDatabagItem(
"config", instance.getAllocatedStorage().toString(),
instance.getMasterUsername(),
instance.getMasterUserPassword(),
instance.getAutoMinorVersionUpgrade(),
instance.getEngine(), instance.getEngineVersion(),
instance.getDbName(), instance
.getBackupRetentionPeriod().toString(),
instance.getPreferredBackupWindow(),
instance.getPreferredMaintenanceWindow(), instance
.getPort().toString(), postWaitUrl, servletUrl,
instance.getDbinstanceId(), "rds." + ac.getId() + "."
+ instance.getDbinstanceId(), ac.getId(), instance.getDbinstanceClass(), "false");
final RDSParameterGroupDatabagItem parameterGroupDatabagItem = new RDSParameterGroupDatabagItem(
"parameters", pGrpRec);
parameterGroupDatabagItem.getParameters().remove("read_only");
parameterGroupDatabagItem.getParameters().put(
"read_only",
DatabagParameter.factory("boolean",
"" + instance.getRead_only(), true, "dynamic"));
parameterGroupDatabagItem.getParameters().remove("port");
parameterGroupDatabagItem.getParameters().put(
"port",
DatabagParameter.factory("integer",
"" + instance.getPort(), false, "static"));
final RDSDatabag bag = new RDSDatabag(configDataBagItem,
parameterGroupDatabagItem);
logger.debug("Databag: "
+ JsonUtil.toJsonPrettyPrintString(bag));
logger.debug("Regenerating the databag " + databagName);
ChefUtil.createDatabagItem(databagName, "config", bag.toJson());
}
if (resetAll) {
// update the database record and get the copy of the list
forRebootPending = ParameterGroupEntity
.copyAndSetStaticParamGroup(sess, pGrpRec,
parent.getParameters(), userId);
} else {
// forRebootPending is now a list of static parameters and
// dynamic parameters with pending-reboot ApplyMethod
forRebootPending = ParameterGroupEntity
.resetParamGroupWithPartialList(sess, pGrpRec,
forRebootPending, userId);
}
for (final RdsDbinstance instance : dbInstances) {
final List<RdsParameter> alreadyPending = instance
.getPendingRebootParameters();
if (alreadyPending == null) {
instance.setPendingRebootParameters(forRebootPending);
// instance.setDbinstanceStatus(RDSUtilities.STATUS_MODIFYING);
sess.save(instance);
} else {
for (final RdsParameter newParam : forRebootPending) {
boolean found = false;
int i = 0;
while (!found && i < alreadyPending.size()) {
if (alreadyPending.get(i).getParameterName()
.equals(newParam.getParameterName())) {
alreadyPending.get(i).setParameterValue(
newParam.getParameterValue());
found = true;
}
++i;
}
if (!found) {
alreadyPending.add(newParam);
}
}
}
}
// build response document - returns DBParameterGroupName
resp.setDbParameterGroupName(grpName);
// commit this current transaction
sess.getTransaction().commit();
} catch (final ErrorResponse rde) {
sess.getTransaction().rollback();
throw rde;
} catch (final Exception e) {
e.printStackTrace();
sess.getTransaction().rollback();
msg = "ResetDBSecurityGroup: Class: " + e.getClass() + "Msg:"
+ e.getMessage();
logger.error(msg);
throw RDSQueryFaults.InternalFailure();
} finally {
sess.close();
}
return resp.buildPartial();
}
}
| 39.916667 | 112 | 0.709341 |
330f9bae1cf7def26f5196c47576c7683608d65d | 4,941 | package com.program.moist.utils;
import android.content.Context;
import android.util.Log;
import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.DeleteObjectRequest;
import com.alibaba.sdk.android.oss.model.DeleteObjectResult;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.OSSResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import java.util.Date;
import static com.program.moist.base.AppConst.TAG;
/**
* Author: SilentSherlock
* Date: 2021/5/8
* Description: 对象存储工具类
*/
public class OssUtil {
public interface OssUpCallback {
void onSuccess(String imgName,String imgUrl);
void onFail(String message);
void onProgress(long progress,long totalSize);
}
private OSSClient ossClient;
private static OssUtil ossUtil;
private String endpoint = "oss-cn-shanghai.aliyuncs.com";
private String bucket = "moist-life";
public OssUtil() {
}
public static OssUtil getInstance() {
if (ossUtil == null) {
ossUtil = new OssUtil();
}
return ossUtil;
}
/**
* 上传图片 上传文件
* @param context application上下文对象
* @param ossUpCallback 成功的回调
* @param imgName 上传到oss后的文件名称,图片要记得带后缀 如:.jpg
* @param imgPath 图片的本地路径
*/
public void uploadImage(Context context, String accessKeyId, String secretKeyId, String securityToken,
final OssUtil.OssUpCallback ossUpCallback,
String imgName, String imgPath) {
Log.i(TAG, "upImage: 进入upImage");
getOSS(context,accessKeyId,secretKeyId,securityToken);
Log.i(TAG, "upImage: 构建OssClient");
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, imgName, imgPath);
putObjectRequest.setProgressCallback((OSSProgressCallback) (request, currentSize, totalSize) -> ossUpCallback.onProgress(currentSize, totalSize));
Log.i(TAG, "upImage: 开始上传");
ossClient.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.i(TAG, "onSuccess: " + result.getStatusCode());
ossUpCallback.onSuccess(imgName, imgPath);
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
}
});
}
public void uploadMultiImage(Context context, String accessKeyId, String secretKeyId, String securityToken,
final OssUtil.OssUpCallback ossUpCallback,
String imgName, String imgPath) {
}
public void deleteImage(Context context,
String accessKeyId, String accessKeySecret, String securityToken,
String objectKey) {
getOSS(context, accessKeyId, accessKeySecret, securityToken);
DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucket, objectKey);
ossClient.asyncDeleteObject(deleteObjectRequest, new OSSCompletedCallback<DeleteObjectRequest, DeleteObjectResult>() {
@Override
public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {
Log.i(TAG, "onSuccess: deleteImage success " + result.getStatusCode());
}
@Override
public void onFailure(DeleteObjectRequest request, ClientException clientException, ServiceException serviceException) {
Log.e(TAG, "onFailure: deleteImage failed", serviceException);
}
});
}
private void getOSS(Context context, String accessKeyId, String accessKeySecret, String token) {
OSSCredentialProvider ossCredentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, token);
Log.i(TAG, "upImage: 构建OssClient配置");
ClientConfiguration conf = ClientConfiguration.getDefaultConf();
conf.setConnectionTimeout(15 *1000);// 连接超时,默认15秒
conf.setSocketTimeout(15 *1000);// socket超时,默认15秒
conf.setMaxConcurrentRequest(5);// 最大并发请求数,默认5个
conf.setMaxErrorRetry(2);// 失败后最大重试次数,默认2次
ossClient = new OSSClient(context, endpoint, ossCredentialProvider);
}
}
| 39.846774 | 154 | 0.695001 |
b7e7832d7f7a6c93a8a02035b9dccd3ccc4a4b9c | 4,219 | package nickrout.lenslauncher.util;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
/**
* Created by nickrout on 2016/04/02.
*/
public class BitmapUtil {
// Old method - does not allow for adding options i.e. lower quality
// Source: http://stackoverflow.com/questions/3035692/how-to-convert-a-drawable-to-a-bitmap
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
bitmapDrawable.setAntiAlias(true);
bitmapDrawable.setDither(true);
bitmapDrawable.setTargetDensity(Integer.MAX_VALUE);
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
// Get bitmap from resource id, with quality options
public static Bitmap resIdToBitmap(Resources res, int resId) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inPreferQualityOverSpeed = true;
try {
return BitmapFactory.decodeResource(res, resId, options);
} catch (OutOfMemoryError e1) {
e1.printStackTrace();
return null;
}
}
// Get res id from app package name
public static int packageNameToResId(PackageManager packageManager, String packageName) {
try {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
return applicationInfo.icon;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return -1;
}
}
// Get bitmap from app package name
public static Bitmap packageNameToBitmap(PackageManager packageManager, String packageName) {
try {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
Resources resources = packageManager.getResourcesForApplication(applicationInfo);
int appIconResId = applicationInfo.icon;
return resIdToBitmap(resources, appIconResId);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
// Get bitmap from app package name (with res id)
public static Bitmap packageNameToBitmap(Context context, PackageManager packageManager, String packageName, int resId) {
try {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
Resources resources = packageManager.getResourcesForApplication(applicationInfo);
Bitmap bitmap = resIdToBitmap(resources, resId);
if (bitmap == null) {
Drawable drawable = packageManager.getApplicationIcon(packageName);
if (drawable != null) {
bitmap = drawableToBitmap(drawable);
}
}
return bitmap;
} catch (PackageManager.NameNotFoundException | Resources.NotFoundException e) {
e.printStackTrace();
return null;
}
}
}
| 40.961165 | 127 | 0.668405 |
2cc31a0b8c613b05dce9ad427efcc39b4b956e74 | 9,633 | package com.hsy.springboot.oauth2.all.multiLogin.config;
import com.hsy.springboot.oauth2.all.multiLogin.filter.AiLoginRedirectFilter;
import com.hsy.springboot.oauth2.all.multiLogin.filter.ParamTogetherFilter;
import com.hsy.springboot.oauth2.all.multiLogin.handler.MyLoginFailureHandler;
import com.hsy.springboot.oauth2.all.multiLogin.handler.MyLoginSuccessHandler;
import com.hsy.springboot.oauth2.all.multiLogin.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.cors.CorsUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Order(2)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MultiWebSecurityConfig {
@Bean
PasswordEncoder passwordEncoder(){
// 动态决定密码加密方式
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
/**
* 通过自定义userDetailsService 来实现查询数据库,手机,二维码等多种验证方式
*/
@Bean
protected UserDetailsService userDetailsService(){
//采用一个自定义的实现UserDetailsService接口的类
return new UserServiceImpl();
}
/**
* 配置两个用户, he、admin
* @param authenticationManagerBuilder
* @throws Exception
*/
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
authenticationManagerBuilder.userDetailsService(userDetailsService())
;
}
/**
* order中的数字越小,优先级越高
*/
@Configuration
@Order(1)
public static class UsernameSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
MyLoginFailureHandler myLoginFailureHandler;
@Autowired
MyLoginSuccessHandler myLoginSuccessHandler;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
AiLoginRedirectFilter aiLoginRedirectFilter() throws Exception {
AiLoginRedirectFilter aiLoginRedirectFilter = new AiLoginRedirectFilter();
aiLoginRedirectFilter.setAuthenticationManager(authenticationManagerBean());
return aiLoginRedirectFilter;
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
// 配置拦截范围
httpSecurity
.addFilterBefore(aiLoginRedirectFilter() , UsernamePasswordAuthenticationFilter.class)
.requestMatchers().antMatchers("/admin/**", "/login/**", "/oauth/**", "/logout/**", "/view/**")
.and()
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers("/admin/**", "/login/**", "/oauth/**", "/logout/**", "/view/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/view/username")
.loginProcessingUrl("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout/username")
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.sendRedirect("/view/username");
}
})
.and()
.csrf().disable()
;
}
}
@Configuration
@Order(2)
public static class TelSecurityConfig extends WebSecurityConfigurerAdapter{
/**
* 配置两个用户, he、admin
* @param authenticationManagerBuilder
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
// authenticationManagerBuilder.userDetailsService(userDetailsService()) ;
super.configure(authenticationManagerBuilder);
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity
.requestMatchers().antMatchers("/tel/**", "/loginTel/**", "/oauth/**", "/login/**", "/logout/**", "/view/**")
.and()
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers("/tel/**", "/loginTel/**", "/oauth/**", "/login/**", "/logout/**", "/view/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/view/tel")
.loginProcessingUrl("/loginTel")
.usernameParameter("tel")
.passwordParameter("code")
.permitAll()
.and()
.logout()
.logoutUrl("/logout/tel")
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.sendRedirect("/view/tel");
}
})
.and()
.csrf().disable()
;
}
}
/*@Configuration
@Order(3)
public static class WorkIdSecurityConfig extends WebSecurityConfigurerAdapter{
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
*//**
* 通过自定义userDetailsService 来实现查询数据库,手机,二维码等多种验证方式
*//*
@Bean
@Override
protected UserDetailsService userDetailsService(){
//采用一个自定义的实现UserDetailsService接口的类
return new UserServiceImpl();
}
@Autowired
MyLoginFailureHandler myLoginFailureHandler;
@Autowired
MyLoginSuccessHandler myLoginSuccessHandler;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity
.antMatcher("/work/**").antMatcher("/loginWork/**")
.authorizeRequests()
// .antMatchers("/login/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/view/work-id")
.loginProcessingUrl("/loginWork")
.usernameParameter("work-id")
.successHandler(myLoginSuccessHandler)
.failureHandler(myLoginFailureHandler)
.permitAll()
.and()
.logout()
.logoutUrl("/logout/work-id")
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.sendRedirect("/view/work-id");
}
})
.and()
.csrf().disable()
;
}
}*/
}
| 45.438679 | 209 | 0.601682 |
6f3a4a949e0e830f1681736528566b7c7bf4ca3a | 2,901 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.xacml.geoxacml.cond;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.wso2.balana.attr.AttributeValue;
import org.wso2.balana.attr.DoubleAttribute;
import org.wso2.balana.attr.StringAttribute;
import org.wso2.balana.cond.Evaluatable;
import org.wso2.balana.cond.EvaluationResult;
import org.wso2.balana.ctx.EvaluationCtx;
/**
* Converts units to square metres
*
* @author Christian Mueller
*
*/
public class ConvertToSquareMetre extends ConvertFunction {
public static final String NAME = NAME_PREFIX + "convert-to-square-metre";
private static Map<String, Double> UnitToSquareMetre;
static {
UnitToSquareMetre = new HashMap<String, Double>();
UnitToSquareMetre.put("acre", 4.046873E+03);
UnitToSquareMetre.put("are", 1.0E+02);
UnitToSquareMetre.put("a", 1.0E+02);
UnitToSquareMetre.put("barn", 1.0E-28);
UnitToSquareMetre.put("b", 1.0E-28);
UnitToSquareMetre.put("circular mil", 5.067075E-10);
UnitToSquareMetre.put("hectare", 1.0E+04);
UnitToSquareMetre.put("ha", 1.0E+04);
UnitToSquareMetre.put("ft2", 9.290304E-02);
UnitToSquareMetre.put("in2", 6.4516E-04);
UnitToSquareMetre.put("mi2", 2.589988E+06);
UnitToSquareMetre.put("yd2", 8.361274E-01);
}
public ConvertToSquareMetre() {
super(NAME);
}
//public EvaluationResult evaluate(List<? extends Expression> inputs, EvaluationCtx context) {
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {
AttributeValue[] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
DoubleAttribute value = (DoubleAttribute) (argValues[0]);
StringAttribute unit = (StringAttribute) (argValues[1]);
Double multiplyBy = UnitToSquareMetre.get(unit.getValue());
if (multiplyBy == null) {
exceptionError(new Exception("Unit" + unit + " not supported"));
}
double resultValue = value.getValue() * multiplyBy;
return new EvaluationResult(new DoubleAttribute(resultValue));
}
}
| 32.233333 | 98 | 0.685281 |
bd6e797584a675eaa49640de4b63ded3cad2c4d6 | 856 | package arraydeque;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Scanner;
public class HotPotato {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] players = scanner.nextLine().split("\\s+");
int n = Integer.parseInt(scanner.nextLine());
ArrayDeque<String> queue = new ArrayDeque<>();
Collections.addAll(queue, players);
while (queue.size() > 1) {
for (int i = 1; i < n; i++) {
String child = queue.remove();
queue.offer(child);
}
String name = queue.remove();
System.out.println("Removed " + name);
}
String name = queue.peek();
System.out.println("Last is " + name);
}
}
| 23.135135 | 61 | 0.53271 |
b50278308a99279e65403b47432d8476931521d6 | 529 | package com.thinkaurelius.titan.diskstorage.berkeleydb.je;
import com.thinkaurelius.titan.diskstorage.util.KeyValueStorageManager;
import com.thinkaurelius.titan.diskstorage.util.KeyValueStorageManagerAdapter;
import org.apache.commons.configuration.Configuration;
/**
* (c) Matthias Broecheler ([email protected])
*/
public class BerkeleyJEStorageAdapter extends KeyValueStorageManagerAdapter {
public BerkeleyJEStorageAdapter(Configuration config) {
super(new BerkeleyJEStorageManager(config),config);
}
}
| 31.117647 | 78 | 0.814745 |
233767ccc75f374a119618e8bbe3ba5e0817c441 | 26,725 | package com.termux.zerocore.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.example.xh_lib.utils.UUtils;
import com.google.gson.Gson;
import com.termux.R;
import com.termux.app.TermuxActivity;
import com.termux.app.TermuxInstaller;
import com.termux.app.TermuxService;
import com.termux.zerocore.activity.adapter.CreateSystemAdapter;
import com.termux.zerocore.bean.CreateSystemBean;
import com.termux.zerocore.bean.ReadSystemBean;
import com.termux.zerocore.dialog.MyDialog;
import com.termux.zerocore.shell.ExeCommand;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class SwitchActivity extends AppCompatActivity implements View.OnClickListener {
private ListView list;
private ImageView create_img;
private File mFile = new File("/data/data/com.termux/");
private File mFileTEMP = new File("/data/data/com.termux/temp");
private File mDefFile = new File("/data/data/com.termux/files/xinhao_system.infoJson");
private File mFileHomeStatic = new File("/data/data/com.termux/busybox_static");
private File mFileHome = new File("/data/data/com.termux/busybox");
private static final String ACTION_STOP_SERVICE = "com.termux.service_stop";
private CreateSystemAdapter createSystemAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch);
list = findViewById(R.id.list_switch);
create_img = findViewById(R.id.create_img);
create_img.setOnClickListener(this);
clickList();
isIofo();
readFile();
// testJson();
}
//判断默认系统
private void isIofo() {
if (!mDefFile.exists()) {
try {
mDefFile.createNewFile();
CreateSystemBean createSystemBean = new CreateSystemBean();
createSystemBean.systemName = UUtils.getString(R.string.无名称系统);
createSystemBean.dir = "/data/data/com.termux/files";
String s = new Gson().toJson(createSystemBean);
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(mDefFile)));
printWriter.print(s);
printWriter.flush();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//点击事件
private void clickList() {
// Toast.makeText(this, "执行了", Toast.LENGTH_SHORT).show();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
List<ReadSystemBean> mList = createSystemAdapter.mList;
// Toast.makeText(SwitchActivity.this, "" + position, Toast.LENGTH_SHORT).show();
//当前系统
String[] strings = {UUtils.getString(R.string.删除), UUtils.getString(R.string.切换)};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog
.Builder(SwitchActivity.this);
builder.setTitle(UUtils.getString(R.string.删除完成_需要重进才能刷新));
// builder.setMessage("这是个滚动列表,往下滑");
builder.setItems(strings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Toast.makeText(TermuxActivity.this, "选择了第" + which + "个", Toast.LENGTH_SHORT).show();
if (which == 0) {
builder.create().dismiss();
AlertDialog.Builder a = new AlertDialog.Builder(SwitchActivity.this);
a.setTitle("你确定要删除吗");
a.setMessage("请确保你的sd卡权限未被获取!\n否则很可能会清空你SD卡(内部存储)上的所有内容!\n否则很可能会清空你SD卡(内部存储)上的所有内容!\n否则很可能会清空你SD卡(内部存储)上的所有内容!\n你确定要删除掉你的系统吗?\n请慎重,删除后你的数据不可恢复!!!!!!");
a.setNegativeButton("我确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
a.create().dismiss();
new Thread(new Runnable() {
@Override
public void run() {
if (mList.get(position).dir.equals("/data/data/com.termux/files")) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(SwitchActivity.this, "你不能删除主系统", Toast.LENGTH_SHORT).show();
}
});
return;
}
Log.e("XINHAO_HAN", "删除系统: " + mList.get(position).dir);
runOnUiThread(new Runnable() {
@Override
public void run() {
MyDialog myDialog = new MyDialog(SwitchActivity.this);
myDialog.show();
myDialog.getDialog_title().setText("正在删除,请耐心等待...");
myDialog.getDialog_pro().setText("时间长短,由您的系统大小决定的");
}
});
Log.e("XINHAO_HAN", "删除目录: " + mList.get(position).dir);
String cpu = TermuxInstaller.determineTermuxArchName();
switch (cpu) {
case "aarch64":
writerFile("arm_64/busybox", mFileHome, 1024);
writerFile("arm_64/busybox_static", mFileHomeStatic, 1024);
// writerFile("arm_64/proot", mFileHomeProot, 1024);
break;
case "arm":
writerFile("arm/busybox", mFileHome, 1024);
// writerFile("arm/busybox_static", mFileHomeStatic, 1024);
// writerFile("arm/proot", mFileHomeProot, 1024);
break;
case "x86_64":
writerFile("x86/busybox", mFileHome, 1024);
// writerFile("x86/busybox_static", mFileHomeStatic, 1024);
// writerFile("x86/proot", mFileHomeProot, 1024);
break;
}
try {
Runtime.getRuntime().exec("chmod 777 " + mFileHome.getAbsolutePath());
Runtime.getRuntime().exec("chmod 777 " + mFileHomeStatic.getAbsolutePath());
//Runtime.getRuntime().exec("chmod 777 " + mFileHomeProot.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
ExeCommand cmd2 = new ExeCommand(false).run(mFileHome.getAbsolutePath() + " rm -rf " + mList.get(position).dir, 60000,false);
while (cmd2.isRunning()) {
try {
Thread.sleep(5);
} catch (Exception e) {
}
String buf = cmd2.getResult();
//do something}
Log.e("XINHAO_HAN", "run: " + buf);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
if(new File(mList.get(position).dir).exists()){
Toast.makeText(SwitchActivity.this, "正在清除系统残留文件", Toast.LENGTH_SHORT).show();
TermuxActivity.mTerminalView.sendTextToTerminal("chmod 777 -R "+mList.get(position).dir+"&& rm -rf " + mList.get(position).dir + " \n");
finish();
}else{
Toast.makeText(SwitchActivity.this, "删除成功!", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}
}).start();
}
});
a.setPositiveButton("我不删除", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
a.create().dismiss();
Toast.makeText(SwitchActivity.this, "操作忽略", Toast.LENGTH_SHORT).show();
}
});
//setNegativeButton
a.setNeutralButton("别删除", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
a.create().dismiss();
Toast.makeText(SwitchActivity.this, "操作忽略", Toast.LENGTH_SHORT).show();
}
});
a.show();
} else {
try {
//本目录系统
String temp;
String tempStr = "";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(mDefFile)));
while ((temp = bufferedReader.readLine()) != null) {
tempStr += temp;
}
//要被替换的系统
ReadSystemBean readSystemBean = mList.get(position);
//本目录的系统
CreateSystemBean readSystemBean1 = new Gson().fromJson(tempStr, CreateSystemBean.class);
//要被替换的
String path = readSystemBean.dir;
// Log.e("XINHAO_HAN", "要被替换的: " + path);
//本目录的
String pathThis = readSystemBean1.dir;
// Log.e("XINHAO_HAN", "本目录的: " + pathThis);
File filePath = new File(path);
File filePathThis = new File(pathThis);
File fileOutPath = new File(filePath, "/xinhao_system.infoJson");
// /data/data/com.termux/files1/xinhao_system.infoJson
File fileOutPathThis = new File(filePathThis, "/xinhao_system.infoJson");
// /data/data/com.termux/files/xinhao_system.infoJson
try {
fileOutPathThis.delete();
fileOutPathThis.createNewFile();
readSystemBean1.dir = readSystemBean.dir;
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileOutPathThis)));
printWriter.print(new Gson().toJson(readSystemBean1));
Log.e("XINHAO_HAN", "写入json: " + new Gson().toJson(readSystemBean1));
printWriter.flush();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutPath.delete();
fileOutPath.createNewFile();
readSystemBean1.dir = "/data/data/com.termux/files";
readSystemBean1.systemName = readSystemBean.name;
// readSystemBean1.systemName = readSystemBean.name;
// readSystemBean1.systemName = readSystemBean1.systemName;
// Log.e("XINHAO_HAN", "本目录的: " + pathThis);
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileOutPath)));
printWriter.print(new Gson().toJson(readSystemBean1));
printWriter.flush();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
filePath.renameTo(mFileTEMP);
filePathThis.renameTo(filePath);
mFileTEMP.renameTo(filePathThis);
} catch (Exception e) {
Toast.makeText(SwitchActivity.this, "读取失败!", Toast.LENGTH_SHORT).show();
}
setAllFlase(mList);
mList.get(position).isCkeck = true;
createSystemAdapter.notifyDataSetChanged();
AlertDialog.Builder ab = new AlertDialog.Builder(SwitchActivity.this);
ab.setTitle("提示");
ab.setCancelable(false);
ab.setMessage("切换成功!\n重启APP生效\n需要重启吗\n其实点击需要没用\n自己手动重启\n进入任务管理器,一般点击 '□'这个建,然后滑退APP ");
ab.setNegativeButton("需要", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(SwitchActivity.this, "请手动退出APP", Toast.LENGTH_SHORT).show();
new Intent(SwitchActivity.this, TermuxService.class).setAction(ACTION_STOP_SERVICE);
System.exit(0);
finish();
}
});
ab.setPositiveButton("不需要", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(SwitchActivity.this, "设置已生效!请重启APP", Toast.LENGTH_SHORT).show();
finish();
}
});
ab.show();
}
}
});
builder.show();
//readSystemBean.dir
}
});
}
//全部flase
private void setAllFlase(List<ReadSystemBean> mList) {
for (int i = 0; i < mList.size(); i++) {
mList.get(i).isCkeck = false;
}
createSystemAdapter.notifyDataSetChanged();
}
//全部ture
//先读取
private void readFile() {
File[] files = mFile.listFiles();
ArrayList<ReadSystemBean> arrayList = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
if (files[i].getName().startsWith("files")) {
ReadSystemBean readSystemBean = new ReadSystemBean();
readSystemBean.dir = files[i].getAbsolutePath();
String name = readInfo(files[i].getAbsolutePath());
if (name == null) {
new File(files[i],"/xinhao_system.infoJson").delete();
Toast.makeText(this, "配置文件已损坏,请重新进入创建,多点几次,直到进入为止", Toast.LENGTH_SHORT).show();
finish();
return;
}
readSystemBean.name = name;
arrayList.add(readSystemBean);
}
}
Log.e("XINHAO_HAN", "readFile: " + arrayList);
setAdapter(arrayList);
}
//开始设置
private void setAdapter(ArrayList<ReadSystemBean> arrayList) {
createSystemAdapter = new CreateSystemAdapter(arrayList, this);
list.setAdapter(createSystemAdapter);
setDefSystem(arrayList);
}
//设置默认
private void setDefSystem(ArrayList<ReadSystemBean> arrayList) {
//取本地的系统目录
try {
File file = new File("/data/data/com.termux/files/xinhao_system.infoJson");
if (!file.exists()) {
Toast.makeText(this, "你当前的默认系统没有配置文件", Toast.LENGTH_SHORT).show();
return;
}
String temp;
String tempStr = "";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((temp = bufferedReader.readLine()) != null) {
tempStr += temp;
}
CreateSystemBean createSystemBean = new Gson().fromJson(tempStr, CreateSystemBean.class);
if(createSystemBean == null){
createSystemBean = new CreateSystemBean();
createSystemBean.dir = "/data/data/com.termux/files/";
createSystemBean.systemName = "默认系统";
}
for (int i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).name.equals(createSystemBean.systemName)) {
arrayList.get(i).isCkeck = true;
break;
}
}
createSystemAdapter.notifyDataSetChanged();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//读取
private String readInfo(String path) {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(new File(path), "/xinhao_system.infoJson"))));
String temp = "";
String tempSystem = "";
while ((temp = bufferedReader.readLine()) != null) {
tempSystem += temp;
}
bufferedReader.close();
Log.e("XINHAO_HAN", "readInfo: " + tempSystem);
CreateSystemBean createSystemBean = new Gson().fromJson(tempSystem, CreateSystemBean.class);
if(createSystemBean == null){
return"损坏的系统";
}else{
return createSystemBean.systemName;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "默认系统";
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.create_img:
createSystemDialog();
break;
}
}
//创建新的系统
private void createSystemDialog() {
final EditText et = new EditText(this);
new AlertDialog.Builder(this).setTitle("请输入新的linux名称")
.setIcon(R.mipmap.linux_new_ico)
.setView(et)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//按下确定键后的事件
createSystem(et.getText().toString());
}
}).setNegativeButton("取消", null).show();
}
//创建
private void createSystem(String name) {
//先扫描有多少文件
File[] files = mFile.listFiles();
if (files.length == 1) {
//默认只有一个系统
//直接创建
File createFile = new File(mFile, "files1");
createFile.mkdirs();
CreateSystemBean createSystemBean = new CreateSystemBean();
createSystemBean.dir = createFile.getAbsolutePath();
createSystemBean.systemName = name;
String s = new Gson().toJson(createSystemBean);
File fileInfo = new File(createFile, "/xinhao_system.infoJson");
PrintWriter printWriter = null;
try {
fileInfo.createNewFile();
printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileInfo)));
printWriter.print(s);
printWriter.flush();
printWriter.close();
} catch (IOException e) {
Toast.makeText(this, "系统创建失败!请重试", Toast.LENGTH_SHORT).show();
e.printStackTrace();
return;
} finally {
if (printWriter != null) {
printWriter.close();
}
}
} else {
//有多个系统
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
if (files[i].getName().startsWith("files")) {
// Log.e("XINHAO_HAN", "readFile: " + files[i].getAbsolutePath());
String name1 = files[i].getName();
String substring = name1.substring(5, name1.length());
if (substring.isEmpty()) {
arrayList.add(0);
} else {
arrayList.add(Integer.parseInt(substring));
}
}
}
// Log.e("XINHAO_HAN", "createSystem: " + arrayList);
int max = getMax(arrayList);
Log.e("XINHAO_HAN", "最大值: " + max);
//直接创建
File createFile = new File(mFile, "files" + (max + 1));
createFile.mkdirs();
CreateSystemBean createSystemBean = new CreateSystemBean();
createSystemBean.dir = createFile.getAbsolutePath();
createSystemBean.systemName = name;
String s = new Gson().toJson(createSystemBean);
File fileInfo = new File(createFile, "/xinhao_system.infoJson");
PrintWriter printWriter = null;
try {
fileInfo.createNewFile();
printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileInfo)));
printWriter.print(s);
printWriter.flush();
printWriter.close();
} catch (IOException e) {
Toast.makeText(this, "系统创建失败!请重试", Toast.LENGTH_SHORT).show();
e.printStackTrace();
return;
} finally {
if (printWriter != null) {
printWriter.close();
}
}
}
readFile();
createSystemAdapter.notifyDataSetChanged();
}
private void createSystem() {
}
//比大小
private int getMax(ArrayList<Integer> number) {
int temp = number.get(0);
for (int i = 0; i < number.size(); i++) {
if (number.get(i) > temp) {
temp = number.get(i);
}
}
return temp;
}
private void writerFile(String name, File mFile, int size) {
try {
InputStream open = this.getAssets().open(name);
int len = 0;
byte[] b = new byte[size];
if (!mFile.exists()) {
mFile.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(mFile);
while ((len = open.read(b)) != -1) {
fileOutputStream.write(b, 0, len);
}
fileOutputStream.flush();
open.close();
fileOutputStream.close();
} catch (Exception e) {
Log.e("XINHAO_HAN_FILE ", "writerFile: " + e.toString());
}
}
}
| 35.303831 | 192 | 0.455716 |
ba51746dee43a8f274a3dacb322e94990b8dd01b | 672 | package com.google.android.gms.measurement.internal;
public class zzgl {
public static final String[] zzpp = {"firebase_last_notification", "first_open_time", "first_visit_time", "last_deep_link_referrer", "user_id", "first_open_after_install", "lifetime_user_engagement", "session_user_engagement", "non_personalized_ads", "session_number", "ga_session_number", "session_id", "ga_session_id", "last_gclid"};
public static final String[] zzpq = {"_ln", "_fot", "_fvt", "_ldl", "_id", "_fi", "_lte", "_se", "_npa", "_sno", "_sno", "_sid", "_sid", "_lgclid"};
public static String zzbe(String str) {
return zzho.zza(str, zzpp, zzpq);
}
}
| 61.090909 | 340 | 0.693452 |
7c1c9890c0181e4f01f7a9d2b93820bc4fa741bc | 3,004 | /*
*
* * Copyright 2015 Skymind,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.deeplearning4j.scaleout.perform.text;
import org.canova.api.conf.Configuration;
import org.deeplearning4j.berkeley.Counter;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.deeplearning4j.models.word2vec.wordstore.inmemory.InMemoryLookupCache;
import org.deeplearning4j.scaleout.aggregator.JobAggregator;
import org.deeplearning4j.scaleout.job.Job;
import java.util.HashSet;
import java.util.Set;
/**
* Word count aggregator for a vocab cache
*
* @author Adam Gibson
*/
public class WordCountJobAggregator implements JobAggregator {
private VocabCache vocabCache;
public final static String MIN_WORD_FREQUENCY = "org.deeplearning4j.scaleout.perform.text.minwordfrequency";
private int minWordFrequency = 5;
public WordCountJobAggregator() {
this(new InMemoryLookupCache());
}
public WordCountJobAggregator(VocabCache vocabCache) {
this.vocabCache = vocabCache;
}
@Override
public void accumulate(Job job) {
Counter<String> wordCounts = (Counter<String>) job.getResult();
Set<String> seen = new HashSet<>();
for(String word : wordCounts.keySet()) {
vocabCache.incrementWordCount(word,(int) wordCounts.getCount(word));
if(!seen.contains(word)) {
vocabCache.incrementTotalDocCount();
vocabCache.incrementDocCount(word,1);
}
VocabWord token = vocabCache.tokenFor(word);
if(token == null) {
token = new VocabWord(wordCounts.getCount(word),word);
vocabCache.addToken(token);
}
else if(vocabCache.wordFrequency(word) >= minWordFrequency) {
//add to the vocab if it was already a token and occurred >= min word frequency times
VocabWord vocabWord = vocabCache.wordFor(word);
if(vocabWord == null) {
vocabCache.putVocabWord(word);
}
}
}
}
@Override
public Job aggregate() {
Job ret = new Job("","");
ret.setResult(vocabCache);
return ret;
}
@Override
public void init(Configuration conf) {
minWordFrequency = conf.getInt(MIN_WORD_FREQUENCY,5);
}
}
| 33.010989 | 112 | 0.655792 |
7161871d3617010c02e3ccc87dc2f49150f0f4f6 | 2,290 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.xuegao.netty_chat_room_server.Netty进阶之路.第八章;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by 李林峰 on 2018/8/18.
*/
public class IotCarsServerHandler extends ChannelInboundHandlerAdapter {
static AtomicInteger sum = new AtomicInteger(0);
static ExecutorService executorService = new ThreadPoolExecutor(1, 3, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(1000), new ThreadPoolExecutor.CallerRunsPolicy());
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println(new Date() + "--> Server receive client message : " + sum.incrementAndGet());
executorService.execute(() ->
{
ByteBuf req = (ByteBuf) msg;
//其它业务逻辑处理,访问数据库
if (sum.get() % 100 == 0 || (Thread.currentThread() == ctx.channel().eventLoop()))
try {
//访问数据库,模拟偶现的数据库慢,同步阻塞15秒
TimeUnit.SECONDS.sleep(15);
} catch (Exception e) {
e.printStackTrace();
}
//转发消息,此处代码省略,转发成功之后返回响应给终端
ctx.writeAndFlush(req);
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
| 37.540984 | 104 | 0.685153 |
28110a8ac031d94f3d8a69f3790bc9cc44b37e4c | 11,419 | package co.etornam.freeminds;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.mikepenz.itemanimators.ScaleUpAnimator;
import com.shashank.sony.fancydialoglib.Animation;
import com.shashank.sony.fancydialoglib.FancyAlertDialog;
import com.shashank.sony.fancydialoglib.FancyAlertDialogListener;
import com.shashank.sony.fancydialoglib.Icon;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import co.etornam.freeminds.authenticate.SignupActivity;
import co.etornam.freeminds.model.Comment;
import static co.etornam.freeminds.util.DateConventer.calculateTimePeriod;
public class CommentActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private FloatingActionButton sendBtn;
private EditText edtComment;
private FirebaseFirestore mDatabase,mComment;
private FirebaseAuth firebaseAuth;
private FirebaseUser firebaseUser;
private String key;
private FirestoreRecyclerAdapter<Comment, CommentViewHolder> adapter;
ProgressDialog progressDialog;
DocumentSnapshot r;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
mRecyclerView = findViewById(R.id.recyclerView);
sendBtn = findViewById(R.id.sendFab);
edtComment = findViewById(R.id.edtComment);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
mRecyclerView.setItemAnimator(new ScaleUpAnimator());
mDatabase = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Sending...");
firebaseUser = firebaseAuth.getCurrentUser();
Bundle extras = getIntent().getExtras();
if (extras != null) {
key = extras.getString("KEY");
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Date date = new Date();
progressDialog.show();
SimpleDateFormat dateFt = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
String userComment = edtComment.getText().toString();
if (!TextUtils.isEmpty(edtComment.getText().toString())) {
Map<String, Object> objectMap = new HashMap<>();
objectMap.put("timeStamp", FieldValue.serverTimestamp());
objectMap.put("comment", userComment);
objectMap.put("time", dateFt.format(date));
objectMap.put("currentId", firebaseUser.getUid());
mDatabase.collection("Posts").document(key).collection("Comment").add(objectMap)
.addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
@Override
public void onComplete(@NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
Toast.makeText(CommentActivity.this, "Comment Sent!", Toast.LENGTH_SHORT).show();
edtComment.setText("");
adapter.notifyDataSetChanged();
} else {
Toast.makeText(CommentActivity.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
});
} else {
edtComment.setError("Enter a comment");
}
}
});
Query query = mDatabase.collection("Posts").document(key).collection("Comment").orderBy("timeStamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Comment> options = new FirestoreRecyclerOptions.Builder<Comment>()
.setQuery(query, Comment.class).build();
adapter = new FirestoreRecyclerAdapter<Comment, CommentViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull final CommentViewHolder holder, int position, @NonNull Comment model) {
r = getSnapshots().getSnapshot(position);
holder.setIsRecyclable(false);
Date date = new Date();
SimpleDateFormat nwDateFt = new SimpleDateFormat("HH:mm:ss",Locale.getDefault());
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss");
DateTime time1 = formatter.parseDateTime(nwDateFt.format(date));
DateTime time2 = formatter.parseDateTime(model.getTime());
Duration duration = new Duration(time2,time1);
holder.commentTime.setText(calculateTimePeriod(Math.abs(duration.getStandardSeconds())));
holder.commentText.setText(model.getComment());
if (model.currentId.equalsIgnoreCase(Objects.requireNonNull(firebaseUser.getUid()))) {
holder.username.setText("You");
holder.username.setTextColor(getResources().getColor(R.color.colorPrimary));
}else{
mDatabase.collection("Users").document(firebaseUser.getUid()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot doc = task.getResult();
String senderName = doc.get("username").toString();
holder.username.setText(senderName);
}else{
holder.username.setText(Objects.requireNonNull(firebaseUser.getEmail()));
}
}
});
}
holder.cardViewLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new FancyAlertDialog.Builder(CommentActivity.this)
.setTitle("Delete Comment")
.setBackgroundColor(Color.parseColor("#f90202")) //Don't pass R.color.colorvalue
.setMessage("Do you really want to Delete this comment ?")
.setNegativeBtnText("No")
.setPositiveBtnBackground(Color.parseColor("#f90202")) //Don't pass R.color.colorvalue
.setPositiveBtnText("Sure")
.setNegativeBtnBackground(Color.parseColor("#FFA9A7A8")) //Don't pass R.color.colorvalue
.setAnimation(Animation.POP)
.isCancellable(true)
.setIcon(R.drawable.ic_delete_forever_black_24dp,Icon.Visible)
.OnPositiveClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
deleteComment();
}
})
.OnNegativeClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
Toast.makeText(getApplicationContext(),"Cancel",Toast.LENGTH_SHORT).show();
}
})
.build();
}
});
}
@NonNull
@Override
public CommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_comment_row, parent, false);
return new CommentViewHolder(view);
}
};
}
adapter.notifyDataSetChanged();
mRecyclerView.setAdapter(adapter);
}
//delete comment
private void deleteComment() {
Toast.makeText(this, "key is : "+r.getId(), Toast.LENGTH_SHORT).show();
}
//ViewHolder for our Firebase UI
public static class CommentViewHolder extends RecyclerView.ViewHolder{
TextView commentTime;
TextView commentText;
TextView username;
RelativeLayout cardViewLayout;
CommentViewHolder(View v) {
super(v);
cardViewLayout = v.findViewById(R.id.commentLayout);
username = v.findViewById(R.id.txtUser);
commentText = v.findViewById(R.id.txtComment);
commentTime = v.findViewById(R.id.txtPostedTime);
}
}
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
if (firebaseUser == null){
startActivity(new Intent(getApplicationContext(), SignupActivity.class));
finish();
}
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
@Override
protected void onResume() {
super.onResume();
adapter.startListening();
}
}
| 46.044355 | 154 | 0.605219 |
6f8eb7826b383398e5e7c87abbaf556586fe435d | 867 | package ru.otus.repository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import ru.otus.domain.Comment;
@RequiredArgsConstructor
public class CommentRepositoryCustomImpl implements CommentRepositoryCustom {
private final MongoTemplate mongoTemplate;
@Override
public void updateById(String id, String authorName, String comment) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Update update = new Update();
update.set("authorName", authorName)
.set("comment", comment);
mongoTemplate.updateFirst(query, update, Comment.class);
}
}
| 36.125 | 77 | 0.749712 |
6af048ea120aae67e53cc04fafd7c1b2a7b991dd | 464 | package arez.persist.runtime.browser;
import arez.persist.runtime.Converter;
import javax.annotation.Nonnull;
/**
* Represent Integer as doubles when emitting as json.
*/
final class IntegerConverter
implements Converter<Integer, Double>
{
@Override
public Integer decode( @Nonnull final Double encoded )
{
return encoded.intValue();
}
@Override
public Double encode( @Nonnull final Integer value )
{
return value.doubleValue();
}
}
| 19.333333 | 56 | 0.730603 |
acbebf4e979f085444d36f5022cb54366af6d757 | 2,453 | // @formatter:off
/*
* ---------------------------------------------------------
* Copyright(C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license. See License.txt in the project root.
* ---------------------------------------------------------
*
* ---------------------------------------------------------
* Generated file, DO NOT EDIT
* ---------------------------------------------------------
*
* See following wiki page for instructions on how to regenerate:
* https://vsowiki.com/index.php?title=Rest_Client_Generation
*/
package com.microsoft.alm.visualstudio.services.webplatform;
import java.util.Date;
import java.util.UUID;
/**
*/
public class WebSessionToken {
private UUID appId;
private String extensionName;
private boolean force;
private String name;
private String namedTokenId;
private String publisherName;
private String token;
private DelegatedAppTokenType tokenType;
private Date validTo;
public UUID getAppId() {
return appId;
}
public void setAppId(final UUID appId) {
this.appId = appId;
}
public String getExtensionName() {
return extensionName;
}
public void setExtensionName(final String extensionName) {
this.extensionName = extensionName;
}
public boolean getForce() {
return force;
}
public void setForce(final boolean force) {
this.force = force;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getNamedTokenId() {
return namedTokenId;
}
public void setNamedTokenId(final String namedTokenId) {
this.namedTokenId = namedTokenId;
}
public String getPublisherName() {
return publisherName;
}
public void setPublisherName(final String publisherName) {
this.publisherName = publisherName;
}
public String getToken() {
return token;
}
public void setToken(final String token) {
this.token = token;
}
public DelegatedAppTokenType getTokenType() {
return tokenType;
}
public void setTokenType(final DelegatedAppTokenType tokenType) {
this.tokenType = tokenType;
}
public Date getValidTo() {
return validTo;
}
public void setValidTo(final Date validTo) {
this.validTo = validTo;
}
}
| 22.925234 | 70 | 0.594374 |
a4f47de8778aeb1602ad28598fb4980a9e4cbb74 | 171 | package jchopp.strategies.interfaces;
import jchopp.objects.logical.standards.LogicalObject;
public interface TickingStrategy {
void tick(LogicalObject object);
}
| 17.1 | 54 | 0.807018 |
c3230241dc88ccbc4095b988dd2d2ad29f7d856e | 1,592 | /*
* Copyright 2017 Max Schuster.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.maxschuster.vaadin.v7.migrationfield.demo;
import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
*
* @author Max Schuster
*/
class DateToLocalDateConverter implements Converter<Date, LocalDate> {
@Override
public Result<LocalDate> convertToModel(Date value, ValueContext context) {
if (value == null) {
return Result.ok(null);
}
Instant i = value.toInstant();
return Result.ok(LocalDateTime.ofInstant(i, ZoneId.systemDefault()).toLocalDate());
}
@Override
public Date convertToPresentation(LocalDate value, ValueContext context) {
if (value == null) {
return null;
}
Instant i = value.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
return Date.from(i);
}
}
| 30.615385 | 91 | 0.699121 |
c3fd922a99e603ea97a8b16f417db521c945cd6f | 1,455 | package org.scribble.ext.assrt.core.type.name;
import org.scribble.core.type.name.DataName;
import org.scribble.ext.assrt.core.type.kind.AssrtAnnotDataKind;
// Cf. GDelegType; similarly located in name package -- CHECKME: maybe refactor (both) out of name, and (Assrt)PayloadType
public class AssrtAnnotDataName
implements AssrtPayElemType<AssrtAnnotDataKind>
{
// TODO: currently hardcoded to int data
public final AssrtIntVar var;
public final DataName data; // currently only int
// CHECKME: generalise beyond data?
public AssrtAnnotDataName(AssrtIntVar varName, DataName data)
{
this.var = varName;
this.data = data;
}
@Override
public AssrtAnnotDataKind getKind()
{
return AssrtAnnotDataKind.KIND;
}
@Override
public boolean isAnnotVarDecl()
{
return true;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (!(o instanceof AssrtAnnotDataName))
{
return false;
}
AssrtAnnotDataName them = (AssrtAnnotDataName) o;
return them.canEquals(this) && them.var.equals(this.var)
&& them.data.equals(this.data);
}
public boolean canEquals(Object o)
{
return o instanceof AssrtAnnotDataName;
}
@Override
public String toString()
{
return this.var + ": " + this.data.getSimpleName();
}
@Override
public int hashCode()
{
int hash = 2767;
hash = hash*31 + this.data.hashCode();
hash = hash*31 + this.var.hashCode();
return hash;
}
}
| 21.086957 | 122 | 0.709278 |
b070e62ff591cfd54ddaa66dcf1f2a395eb2e715 | 371 | package com.ctrip.xpipe.redis.console.model;
public class MigrationEventModel implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private MigrationEventTbl event;
public MigrationEventModel(){}
public MigrationEventTbl getEvent() {
return event;
}
public void setEvent(MigrationEventTbl event) {
this.event = event;
}
}
| 19.526316 | 65 | 0.768194 |
29308c9b2a1802c38807d3720d06257c59f14667 | 1,174 | package dev.hoot.api.game;
import dev.hoot.bot.managers.Static;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Slf4j
public class GameThread
{
private static final long TIMEOUT = 1000;
public static void invoke(Runnable runnable)
{
if (Static.getClient().isClientThread())
{
runnable.run();
}
else
{
Static.getClientThread().invokeLater(runnable);
}
}
public static <T> T invokeLater(Callable<T> callable)
{
if (Static.getClient().isClientThread())
{
try
{
return callable.call();
}
catch (Exception e)
{
e.printStackTrace();
}
}
try
{
FutureTask<T> futureTask = new FutureTask<>(callable);
Static.getClientThread().invokeLater(futureTask);
return futureTask.get(TIMEOUT, TimeUnit.MILLISECONDS);
}
catch (ExecutionException | InterruptedException | TimeoutException e)
{
e.printStackTrace();
throw new RuntimeException("Client thread invoke timed out after " + TIMEOUT + " ms");
}
}
}
| 20.596491 | 89 | 0.715503 |
0d02a6fdf242505203947e81f01233e33d7d9537 | 166 | package servlet.vo;
import lombok.Builder;
import lombok.Data;
import java.util.List;
@Data
@Builder
public class SeasonsVO {
private List<String> seasons;
}
| 12.769231 | 34 | 0.746988 |
63c2fe3de2f26e35dd945795044b8e10e3d0e945 | 3,710 | package pl.stqa.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pl.stqa.pft.addressbook.model.ContactData;
import pl.stqa.pft.addressbook.model.Contacts;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class ModifyContact extends TestBase{
@BeforeMethod
public void checkPreconditions() {
if(app.contact().all().size() == 0) {
app.contact().create(new ContactData()
.withFirstName(app.properties.getProperty("contact.firstName"))
.withLastName(app.properties.getProperty("contact.lastName"))
.withTitle(app.properties.getProperty("contact.title"))
.withCompany(app.properties.getProperty("contact.company"))
.withAddress(app.properties.getProperty("contact.address"))
.withHomePhone(app.properties.getProperty("contact.homePhone"))
.withMobilePhone(app.properties.getProperty("contact.mobilePhone"))
.withWorkPhone(app.properties.getProperty("contact.workPhone"))
.withEmail(app.properties.getProperty("contact.email"))
.withEmail2(app.properties.getProperty("contact.email2"))
.withEmail3(app.properties.getProperty("contact.email3"))
.withAddress2(app.properties.getProperty("contact.address2"))
.withBirth_day(app.properties.getProperty("contact.birthDay"))
.withBirth_month(app.properties.getProperty("contact.birthMonth"))
.withBirth_year(app.properties.getProperty("contact.birthYear"))
.withPhoto(app.properties.getProperty("contact.photo")));
}
}
@Test
public void testContactModification() {
Contacts before = app.db().contacts();
ContactData modifiedContact = before.iterator().next();
ContactData contact = new ContactData()
.withId(modifiedContact.getId())
.withFirstName(app.properties.getProperty("contact.modifiedFirstName"))
.withLastName(app.properties.getProperty("contact.modifiedLastName"))
.withTitle(app.properties.getProperty("contact.modifiedTitle"))
.withCompany(app.properties.getProperty("contact.modifiedCompany"))
.withAddress(app.properties.getProperty("contact.modifiedAddress"))
.withHomePhone(app.properties.getProperty("contact.modifiedHomePhone"))
.withMobilePhone(app.properties.getProperty("contact.modifiedMobilePhone"))
.withWorkPhone(app.properties.getProperty("contact.modifiedWorkPhone"))
.withEmail(app.properties.getProperty("contact.modifiedEmail"))
.withEmail2(app.properties.getProperty("contact.modifiedEmail2"))
.withEmail3(app.properties.getProperty("contact.modifiedEmail3"))
.withAddress2(app.properties.getProperty("contact.modifiedAddress2"))
.withBirth_day(app.properties.getProperty("contact.modifiedBirthDay"))
.withBirth_month(app.properties.getProperty("contact.modifiedBirthMonth"))
.withBirth_year(app.properties.getProperty("contact.modifiedBirthYear"))
.withPhoto(app.properties.getProperty("contact.photo"));
app.contact().modify(contact);
Contacts after = app.db().contacts();
Assert.assertEquals(after.size(), before.size());
assertThat(after, equalTo(before.without(modifiedContact).withAdded(contact)));
}
}
| 55.373134 | 91 | 0.666038 |
8529ea8dcddeaffe25dde52209185958aa3b3d6a | 6,876 | /*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package org.doublecloud.ws.util;
import java.lang.reflect.Array;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.nimblestorage.hi.utils.Logger;
public class TypeUtil
{
private static final Logger logger = Logger.getLogger(TypeUtil.class);
final public static Class<?> INT_ARRAY_CLASS = new int[] {}.getClass();
final public static Class<?> BYTE_ARRAY_CLASS = new byte[] {}.getClass();
final public static Class<?> LONG_ARRAY_CLASS = new long[] {}.getClass();
private final static Set<String> PRIMITIVE_TYPES = new HashSet<String>();
static {
PRIMITIVE_TYPES.add("int");
PRIMITIVE_TYPES.add("boolean");
PRIMITIVE_TYPES.add("short");
PRIMITIVE_TYPES.add("float");
PRIMITIVE_TYPES.add("byte");
PRIMITIVE_TYPES.add("long");
PRIMITIVE_TYPES.add("double");
}
public static boolean isPrimitiveType(String type) {
return PRIMITIVE_TYPES.contains(type);
}
private static String[] BASIC_TYPES = new String[] { "String", "int", "short", "long", "float", "Float", "byte",
"boolean", "Boolean", "Calendar", "double" };
public static boolean isBasicType(String type) {
for (int i = 0; i < BASIC_TYPES.length; i++) {
if (type.startsWith(BASIC_TYPES[i]))
return true;
}
return false;
}
final private static Package LANG_PKG = String.class.getPackage();
final private static Package UTIL_PKG = Calendar.class.getPackage();
public static boolean isBasicType(Class<?> clazz) {
Package pkg = clazz.getPackage(); // for primitive type like int, the pkg is null
if (pkg == null || pkg == LANG_PKG || pkg == UTIL_PKG) {
return true;
}
return false;
}
public static String PACKAGE_NAME = "com.vmware.vim25";
public static String SMS_PACKAGE_NAME = "com.vmware.vim.sms";
public static String PBM_PACKAGE_NAME = "com.vmware.pbm";
private final static Map<String, Class<?>> VIM_CLASSES = new ConcurrentHashMap<String, Class<?>>();
public final static Class<?> getVimClass(String type) {
if (VIM_CLASSES.containsKey(type)) {
return VIM_CLASSES.get(type);
} else {
try {
Class<?> clazz = null;
if (type.endsWith("[]") == false) {
if (type.startsWith("vim25:")) {
type = type.substring(type.indexOf(":") + 1);
}
if (type.startsWith("sms:")) {
type = type.substring(type.indexOf(":") + 1);
}
if (type.startsWith("pbm:")) {
type = type.substring(type.indexOf(":") + 1);
}
try {
clazz = Class.forName(PACKAGE_NAME + "." + type);
} catch (ClassNotFoundException ex) {
try {
// failed to find class in the vim25 namespace. Check sms
clazz = Class.forName(SMS_PACKAGE_NAME + "." + type);
} catch (ClassNotFoundException e) {
// failed to find class in the sms namespace. Check pbm
clazz = Class.forName(PBM_PACKAGE_NAME + "." + type);
}
}
} else {
String arrayType = type.substring(0, type.length() - 2);
clazz = Array.newInstance(getVimClass(arrayType), 0).getClass();
}
VIM_CLASSES.put(type, clazz);
return clazz;
} catch (ClassNotFoundException cnfe) {
logger.error(cnfe, "Could not find type {0}", type);
return null;
}
}
}
private static Class<?>[] clazzes = new Class[] {
java.lang.Integer.class,
java.lang.Long.class,
java.lang.Boolean.class,
java.lang.Short.class,
java.lang.Float.class,
java.lang.String.class,
java.lang.Byte.class,
java.lang.Double.class };
private static String[] xsdStrs = new String[] {
"xsd:int",
"xsd:long",
"xsd:boolean",
"xsd:short",
"xsd:float",
"xsd:string",
"xsd:byte",
"xsd:double" };
// only for the basic data types as shown above
public static String getXSIType(Object obj) {
Class<?> type = obj.getClass();
for (int i = 0; i < clazzes.length; i++) {
if (type == clazzes[i]) {
return xsdStrs[i];
}
}
if (obj instanceof java.util.Calendar) {
return "xsd:dateTime";
}
throw new RuntimeException("Unknown data type during serialization:" + type);
}
}
| 40.447059 | 117 | 0.566463 |
247437c6d6c4c472d8ae006ebabacfc82d8b403c | 1,536 | package frc.robot.commands;
import edu.wpi.first.math.filter.Debouncer;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.Constants;
import frc.robot.subsystems.IntakeFourBar;
public class IntakeExtendToLimit extends CommandBase {
private final IntakeFourBar intake;
private double currentLimit = 0;
private double motorSpeed = 0;
private Debouncer currentIsHigh =
new Debouncer(Constants.IntakeConstants.intakeHighCurrentMinimumTime);
public IntakeExtendToLimit(IntakeFourBar fourBar, double speed, double currentLim) {
this.intake = fourBar;
this.currentLimit = currentLim;
this.motorSpeed = speed;
addRequirements(intake);
}
public IntakeExtendToLimit(IntakeFourBar fourBar, double speed) {
this(fourBar, speed, Constants.IntakeConstants.intakeExtensionCurrentLimit);
}
@Override
public void initialize() {
// this.intake.setOperatorControlled(true);
this.intake.setFourBarMotor(this.motorSpeed);
}
@Override
public boolean isFinished() {
double fourBarCurrent = this.intake.getFilteredFourBarMotorCurrent();
boolean isHighCurrent = this.currentIsHigh.calculate(fourBarCurrent > currentLimit);
return isHighCurrent;
}
@Override
public void end(boolean interrupted) {
// this.intake.setFourBarMotor(0);
// this.intake.setOperatorControlled(false);
if (this.intake.getEncoderPosition() > 0.05) {
this.intake.setEncoderPosition(Constants.IntakeConstants.extensionPoint);
}
this.intake.resetFilter();
}
}
| 30.72 | 88 | 0.759766 |
b7f8b404afa9b4cb9aff31d49fb224b917cf9401 | 1,258 | package com.haulmont.sampler.web.ui.components.fieldgroup.simple;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.gui.components.AbstractFrame;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.sampler.entity.Order;
import javax.inject.Inject;
import java.util.Map;
public class SimpleFieldGroupSample extends AbstractFrame {
@Inject
private Datasource<Order> orderDs;
@Inject
private Metadata metadata;
@Override
public void init(Map<String, Object> params) {
// Datasource initialization. It is usually done automatically if the screen is
// inherited from AbstractEditor and is used as an entity editor.
Order order = metadata.create(Order.class);
orderDs.setItem(order);
}
public void showOrder() {
Order order = orderDs.getItem();
String sb = "date = " + order.getDate() + "\n" +
"customer = " + (order.getCustomer() != null
? order.getCustomer().getInstanceName()
: null) +
"\n" +
"amount = " + order.getAmount() + "\n" +
"description = " + order.getDescription();
showNotification(sb, NotificationType.HUMANIZED);
}
} | 34 | 87 | 0.644674 |
55988b0871dde379aaefa1d3194b062da1ae49e0 | 12,422 | package com.bebopze.jdk.patterndesign;
import static com.bebopze.jdk.patterndesign.State.*;
/**
* 16. 状态模式 ---> 状态机 的一种
*
* @author bebopze
* @date 2020/8/12
*/
public class _16_State {
// 核心: 状态机
// 状态模式:
// 状态机 的一种 实现方式
// 状态机 的实现:
// 1、分支逻辑法
// 2、查表法
// 3、状态模式
// 状态机 的3个组成部分:
// 状态(State)、事件(Event)、动作(Action)
// ---------------------------------------------------------------
public static void main(String[] args) {
// 1、分支逻辑法
test_1();
// 2、查表法
test_2();
// 3、状态模式
test_3();
test_4();
}
private static void test_1() {
State1.MarioStateMachine mario = new State1.MarioStateMachine();
mario.obtainMushRoom();
int score = mario.getScore();
State state = mario.getCurrentState();
System.out.println("mario score: " + score + "; state: " + state);
}
private static void test_2() {
State2.MarioStateMachine mario = new State2.MarioStateMachine();
mario.obtainMushRoom();
int score = mario.getScore();
State state = mario.getCurrentState();
System.out.println("mario score: " + score + "; state: " + state);
}
private static void test_3() {
// State3.MarioStateMachine mario = new State3.MarioStateMachine();
//
// mario.obtainMushRoom();
//
// int score = mario.getScore();
// State state = mario.getCurrentState();
//
// System.out.println("mario score: " + score + "; state: " + state);
}
private static void test_4() {
State4.MarioStateMachine mario = new State4.MarioStateMachine();
mario.obtainMushRoom();
int score = mario.getScore();
State state = mario.getCurrentState();
System.out.println("mario score: " + score + "; state: " + state);
}
}
// ----------------------------------- 实现 ----------------------------------------
// ----------------------------------- 1、分支逻辑法 ----------------------------------------
class State1 {
/**
* 马里奥-状态机
*/
public static class MarioStateMachine {
private int score;
private State currentState;
public MarioStateMachine() {
this.score = 0;
this.currentState = SMALL;
}
/**
* 获得🍄 -> SUPER 马里奥
*/
public void obtainMushRoom() {
if (currentState.equals(SMALL)) {
this.currentState = SUPER;
this.score += 100;
}
}
/**
* 获得披风 -> CAPE 马里奥
*/
public void obtainCape() {
if (currentState.equals(SMALL) || currentState.equals(SUPER)) {
this.currentState = CAPE;
this.score += 200;
}
}
/**
* 获得🔥 -> FIRE 马里奥
*/
public void obtainFireFlower() {
if (currentState.equals(SMALL) || currentState.equals(SUPER)) {
this.currentState = FIRE;
this.score += 300;
}
}
/**
* 撞到怪物👹 -> SMALL 马里奥
*/
public void meetMonster() {
if (currentState.equals(SUPER)) {
this.currentState = SMALL;
this.score -= 100;
return;
}
if (currentState.equals(CAPE)) {
this.currentState = SMALL;
this.score -= 200;
return;
}
if (currentState.equals(FIRE)) {
this.currentState = SMALL;
this.score -= 300;
return;
}
}
public int getScore() {
return this.score;
}
public State getCurrentState() {
return this.currentState;
}
}
}
enum State {
SMALL(0), SUPER(1), FIRE(2), CAPE(3);
private int value;
private State(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
// ----------------------------------- 2、查表法 --------------------------------------------
class State2 {
public enum Event {
GOT_MUSHROOM(0),
GOT_CAPE(1),
GOT_FIRE(2),
MET_MONSTER(3);
private int value;
private Event(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
public static class MarioStateMachine {
private int score;
private State currentState;
private static final State[][] transitionTable = {
{SUPER, CAPE, FIRE, SMALL},
{SUPER, CAPE, FIRE, SMALL},
{CAPE, CAPE, CAPE, SMALL},
{FIRE, FIRE, FIRE, SMALL}
};
private static final int[][] actionTable = {
{+100, +200, +300, +0},
{+0, +200, +300, -100},
{+0, +0, +0, -200},
{+0, +0, +0, -300}
};
public MarioStateMachine() {
this.score = 0;
this.currentState = SMALL;
}
public void obtainMushRoom() {
executeEvent(Event.GOT_MUSHROOM);
}
public void obtainCape() {
executeEvent(Event.GOT_CAPE);
}
public void obtainFireFlower() {
executeEvent(Event.GOT_FIRE);
}
public void meetMonster() {
executeEvent(Event.MET_MONSTER);
}
private void executeEvent(Event event) {
int stateValue = currentState.getValue();
int eventValue = event.getValue();
this.currentState = transitionTable[stateValue][eventValue];
this.score = actionTable[stateValue][eventValue];
}
public int getScore() {
return this.score;
}
public State getCurrentState() {
return this.currentState;
}
}
}
// ----------------------------------- 3、状态模式 --------------------------------------------
class State3 {
/**
* 所有状态类的接口
*/
public interface IMario {
State getName();
// ----------------- 以下是 定义的 事件 --------------------
void obtainMushRoom();
void obtainCape();
void obtainFireFlower();
void meetMonster();
}
class SmallMario implements IMario {
private MarioStateMachine stateMachine;
public SmallMario(MarioStateMachine stateMachine) {
this.stateMachine = stateMachine;
}
@Override
public State getName() {
return State.SMALL;
}
@Override
public void obtainMushRoom() {
stateMachine.setCurrentState(new SuperMario(stateMachine));
stateMachine.setScore(stateMachine.getScore() + 100);
}
@Override
public void obtainCape() {
// stateMachine.setCurrentState(new CapeMario(stateMachine));
// stateMachine.setScore(stateMachine.getScore() + 200);
}
@Override
public void obtainFireFlower() {
// stateMachine.setCurrentState(new FireMario(stateMachine));
// stateMachine.setScore(stateMachine.getScore() + 300);
}
@Override
public void meetMonster() {
// do nothing...
}
}
public class SuperMario implements IMario {
private MarioStateMachine stateMachine;
public SuperMario(MarioStateMachine stateMachine) {
this.stateMachine = stateMachine;
}
@Override
public State getName() {
return State.SUPER;
}
@Override
public void obtainMushRoom() {
// do nothing...
}
@Override
public void obtainCape() {
// stateMachine.setCurrentState(new CapeMario(stateMachine));
// stateMachine.setScore(stateMachine.getScore() + 200);
}
@Override
public void obtainFireFlower() {
// stateMachine.setCurrentState(new FireMario(stateMachine));
// stateMachine.setScore(stateMachine.getScore() + 300);
}
@Override
public void meetMonster() {
stateMachine.setCurrentState(new SmallMario(stateMachine));
stateMachine.setScore(stateMachine.getScore() - 100);
}
}
// 省略CapeMario、FireMario类...
public class MarioStateMachine {
private int score;
private IMario currentState; // 不再使用枚举来表示状态
public MarioStateMachine() {
this.score = 0;
this.currentState = new SmallMario(this);
}
public void obtainMushRoom() {
this.currentState.obtainMushRoom();
}
public void obtainCape() {
this.currentState.obtainCape();
}
public void obtainFireFlower() {
this.currentState.obtainFireFlower();
}
public void meetMonster() {
this.currentState.meetMonster();
}
public int getScore() {
return this.score;
}
public State getCurrentState() {
return this.currentState.getName();
}
public void setScore(int score) {
this.score = score;
}
public void setCurrentState(IMario currentState) {
this.currentState = currentState;
}
}
}
// ----------------------------------- 3_2、状态模式 --------------------------------------------
class State4 {
interface IMario {
State getName();
// -------------------- 以下是 定义的 事件 ----------------------
void obtainMushRoom(MarioStateMachine stateMachine);
void obtainCape(MarioStateMachine stateMachine);
void obtainFireFlower(MarioStateMachine stateMachine);
void meetMonster(MarioStateMachine stateMachine);
}
static class SmallMario implements IMario {
private static final SmallMario instance = new SmallMario();
private SmallMario() {
}
public static SmallMario getInstance() {
return instance;
}
@Override
public State getName() {
return State.SMALL;
}
@Override
public void obtainMushRoom(MarioStateMachine stateMachine) {
// stateMachine.setCurrentState(SuperMario.getInstance());
// stateMachine.setScore(stateMachine.getScore() + 100);
}
@Override
public void obtainCape(MarioStateMachine stateMachine) {
// stateMachine.setCurrentState(CapeMario.getInstance());
// stateMachine.setScore(stateMachine.getScore() + 200);
}
@Override
public void obtainFireFlower(MarioStateMachine stateMachine) {
// stateMachine.setCurrentState(FireMario.getInstance());
// stateMachine.setScore(stateMachine.getScore() + 300);
}
@Override
public void meetMonster(MarioStateMachine stateMachine) {
// do nothing...
}
}
// 省略SuperMario、CapeMario、FireMario类...
/**
* 马里奥 - 状态机
*/
public static class MarioStateMachine {
/**
* 分数
*/
private int score;
/**
* 当前状态:SmallMario/SuperMario/CapeMario/FireMario
*/
private IMario currentState;
public MarioStateMachine() {
this.score = 0;
this.currentState = SmallMario.getInstance();
}
public void obtainMushRoom() {
this.currentState.obtainMushRoom(this);
}
public void obtainCape() {
this.currentState.obtainCape(this);
}
public void obtainFireFlower() {
this.currentState.obtainFireFlower(this);
}
public void meetMonster() {
this.currentState.meetMonster(this);
}
public int getScore() {
return this.score;
}
public State getCurrentState() {
return this.currentState.getName();
}
public void setScore(int score) {
this.score = score;
}
public void setCurrentState(IMario currentState) {
this.currentState = currentState;
}
}
} | 23.003704 | 92 | 0.508614 |
3646b28e662fa4c6949f56dd5a899ac746f5453b | 2,023 | package com.zzx.humor.controller;
import com.zzx.humor.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
/**
* TODO 认证中心对外 api
*/
@RestController
public class OauthController {
@Autowired
private ConsumerTokenServices consumerTokenServices;
@Autowired
private TokenStore tokenStore;
/**
* 根据token获取登录用户主体相关信息(用户名,token,角色。。。等)
*
* @return
*/
@GetMapping("/principal")
public Principal principal(Principal principal) {
return principal;
}
/**
* 登出
*
* @param token
* @return
*/
@DeleteMapping(value = "/exit")
public R exit(String token) {
boolean b = consumerTokenServices.revokeToken(token);
if (b) {
return R.ok();
} else {
return R.failed();
}
}
/**
* 解析jwt token
*
* @param token
* @return
*/
@GetMapping("/decodeToken")
public R decodeToken(String token) {
Jwt decode = JwtHelper.decode(token);
return R.ok(decode);
}
/**
* 单线登陆 踢出前者
*
* @param clientId
* @param account
*/
@GetMapping("/exitFormer")
public R exitFormer(String clientId, String account) {
if (tokenStore.findTokensByClientIdAndUserName(clientId, account).size() == 1) {
return R.ok();
} else {
return R.failed();
}
}
}
| 24.670732 | 88 | 0.655462 |
e69cca9cb18b89d5dec0fd34512155f210367542 | 1,014 | package io.github.biezhi.json.gson.model;
import com.google.gson.annotations.SerializedName;
import java.lang.management.ManagementFactory;
public class Health {
public enum Status {
@SerializedName("1") UP,
@SerializedName("0") DOWN
}
private String hostname;
private String ip;
private long startTime;
private long upTime;
private Status status;
public Health(String hostname, String ip, Status status) {
this.hostname = hostname;
this.ip = ip;
this.startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
this.upTime = ManagementFactory.getRuntimeMXBean().getUptime();
this.status = status;
}
@Override
public String toString() {
return "Health{" +
"hostname='" + hostname + '\'' +
", ip='" + ip + '\'' +
", startTime=" + startTime +
", upTime=" + upTime +
", status=" + status +
'}';
}
} | 27.405405 | 77 | 0.573964 |
5239d4cc7b9f5ab82cc840f494e06364eb501c2c | 8,807 | /*
* 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.geode.internal;
import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.File;
import java.util.Collection;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.DiskStoreFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.internal.cache.DiskStoreImpl;
import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.util.BlobHelper;
import org.apache.geode.pdx.PdxInstance;
import org.apache.geode.pdx.PdxInstanceFactory;
import org.apache.geode.pdx.PdxReader;
import org.apache.geode.pdx.PdxSerializable;
import org.apache.geode.pdx.PdxWriter;
import org.apache.geode.pdx.internal.PdxField;
import org.apache.geode.pdx.internal.PdxInstanceImpl;
import org.apache.geode.pdx.internal.PdxType;
import org.apache.geode.pdx.internal.PdxUnreadData;
import org.apache.geode.pdx.internal.TypeRegistry;
import org.apache.geode.test.junit.categories.IntegrationTest;
@Category(IntegrationTest.class)
public class PdxDeleteFieldJUnitTest {
@Test
public void testPdxDeleteField() throws Exception {
String DS_NAME = "PdxDeleteFieldJUnitTestDiskStore";
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
File f = new File(DS_NAME);
f.mkdir();
try {
Cache cache =
(new CacheFactory(props)).setPdxPersistent(true).setPdxDiskStore(DS_NAME).create();
try {
{
DiskStoreFactory dsf = cache.createDiskStoreFactory();
dsf.setDiskDirs(new File[] {f});
dsf.create(DS_NAME);
}
RegionFactory<String, PdxValue> rf1 =
cache.createRegionFactory(RegionShortcut.LOCAL_PERSISTENT);
rf1.setDiskStoreName(DS_NAME);
Region<String, PdxValue> region1 = rf1.create("region1");
PdxValue pdxValue = new PdxValue(1, 2L);
region1.put("key1", pdxValue);
byte[] pdxValueBytes = BlobHelper.serializeToBlob(pdxValue);
{
PdxValue deserializedPdxValue = (PdxValue) BlobHelper.deserializeBlob(pdxValueBytes);
assertEquals(1, deserializedPdxValue.value);
assertEquals(2L, deserializedPdxValue.fieldToDelete);
}
cache.close();
Collection<PdxType> types = DiskStoreImpl.pdxDeleteField(DS_NAME, new File[] {f},
PdxValue.class.getName(), "fieldToDelete");
assertEquals(1, types.size());
PdxType pt = types.iterator().next();
assertEquals(PdxValue.class.getName(), pt.getClassName());
assertEquals(null, pt.getPdxField("fieldToDelete"));
types = DiskStoreImpl.getPdxTypes(DS_NAME, new File[] {f});
assertEquals(1, types.size());
pt = types.iterator().next();
assertEquals(PdxValue.class.getName(), pt.getClassName());
assertEquals(true, pt.getHasDeletedField());
assertEquals(null, pt.getPdxField("fieldToDelete"));
cache = (new CacheFactory(props)).setPdxPersistent(true).setPdxDiskStore(DS_NAME).create();
{
DiskStoreFactory dsf = cache.createDiskStoreFactory();
dsf.setDiskDirs(new File[] {f});
dsf.create(DS_NAME);
PdxValue deserializedPdxValue = (PdxValue) BlobHelper.deserializeBlob(pdxValueBytes);
assertEquals(1, deserializedPdxValue.value);
assertEquals(0L, deserializedPdxValue.fieldToDelete);
}
} finally {
if (!cache.isClosed()) {
cache.close();
}
}
} finally {
FileUtils.deleteDirectory(f);
}
}
@Test
public void testPdxFieldDelete() throws Exception {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
try {
InternalCache cache = (InternalCache) new CacheFactory(props).create();
try {
PdxValue pdxValue = new PdxValue(1, 2L);
byte[] pdxValueBytes = BlobHelper.serializeToBlob(pdxValue);
{
PdxValue deserializedPdxValue = (PdxValue) BlobHelper.deserializeBlob(pdxValueBytes);
assertEquals(1, deserializedPdxValue.value);
assertEquals(2L, deserializedPdxValue.fieldToDelete);
}
PdxType pt;
cache.setPdxReadSerializedOverride(true);
try {
PdxInstanceImpl pi = (PdxInstanceImpl) BlobHelper.deserializeBlob(pdxValueBytes);
pt = pi.getPdxType();
assertEquals(1, pi.getField("value"));
assertEquals(2L, pi.getField("fieldToDelete"));
} finally {
cache.setPdxReadSerializedOverride(false);
}
assertEquals(PdxValue.class.getName(), pt.getClassName());
PdxField field = pt.getPdxField("fieldToDelete");
pt.setHasDeletedField(true);
field.setDeleted(true);
assertEquals(null, pt.getPdxField("fieldToDelete"));
assertEquals(2, pt.getFieldCount());
{
PdxValue deserializedPdxValue = (PdxValue) BlobHelper.deserializeBlob(pdxValueBytes);
assertEquals(1, deserializedPdxValue.value);
// fieldToDelete should now be 0 (the default) instead of 2.
assertEquals(0L, deserializedPdxValue.fieldToDelete);
}
cache.setPdxReadSerializedOverride(true);
try {
PdxInstance pi = (PdxInstance) BlobHelper.deserializeBlob(pdxValueBytes);
assertEquals(1, pi.getField("value"));
assertEquals(false, pi.hasField("fieldToDelete"));
assertEquals(null, pi.getField("fieldToDelete"));
assertSame(pt, ((PdxInstanceImpl) pi).getPdxType());
PdxValue deserializedPdxValue = (PdxValue) pi.getObject();
assertEquals(1, deserializedPdxValue.value);
assertEquals(0L, deserializedPdxValue.fieldToDelete);
} finally {
cache.setPdxReadSerializedOverride(false);
}
TypeRegistry tr = ((GemFireCacheImpl) cache).getPdxRegistry();
// Clear the local registry so we will regenerate a type for the same class
tr.testClearLocalTypeRegistry();
{
PdxInstanceFactory piFactory = cache.createPdxInstanceFactory(PdxValue.class.getName());
piFactory.writeInt("value", 1);
PdxInstance pi = piFactory.create();
assertEquals(1, pi.getField("value"));
assertEquals(null, pi.getField("fieldToDelete"));
PdxType pt2 = ((PdxInstanceImpl) pi).getPdxType();
assertEquals(null, pt2.getPdxField("fieldToDelete"));
assertEquals(1, pt2.getFieldCount());
}
} finally {
if (!cache.isClosed()) {
cache.close();
}
}
} finally {
}
}
public static class PdxValue implements PdxSerializable {
public int value;
public long fieldToDelete = -1L;
public PdxValue() {} // for deserialization
public PdxValue(int v, long lv) {
this.value = v;
this.fieldToDelete = lv;
}
@Override
public void toData(PdxWriter writer) {
writer.writeInt("value", this.value);
writer.writeLong("fieldToDelete", this.fieldToDelete);
}
@Override
public void fromData(PdxReader reader) {
this.value = reader.readInt("value");
if (reader.hasField("fieldToDelete")) {
this.fieldToDelete = reader.readLong("fieldToDelete");
} else {
this.fieldToDelete = 0L;
PdxUnreadData unread = (PdxUnreadData) reader.readUnreadFields();
assertEquals(true, unread.isEmpty());
}
}
}
}
| 39.671171 | 100 | 0.684456 |
7f6636a10f6c92667a5e13a86dd8fc6c3a857f67 | 5,228 | /*
* Copyright (c) 2017. Mathias Ciliberto, Francisco Javier Ordoñez Morales,
* Hristijan Gjoreski, Daniel Roggen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package uk.ac.sussex.wear.android.datalogger.collector;
import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.LocationManager;
import android.os.SystemClock;
import android.util.Log;
import java.io.File;
import java.util.Date;
import uk.ac.sussex.wear.android.datalogger.log.CustomLogger;
// child class for collecting satellite data (GPS)
public class SatelliteDataCollector extends AbstractDataCollector {
private static final String TAG = SatelliteDataCollector.class.getSimpleName();
private CustomLogger logger = null;
// The location manager reference
private LocationManager mLocationManager = null;
// Listener class for monitoring changes in gps status
private GpsStatusListener mGpsStatusListener = null;
public SatelliteDataCollector(Context context, String sessionName, String sensorName, long nanosOffset, int logFileMaxSize){
mSensorName = sensorName;
String path = sessionName + File.separator + mSensorName + "_" + sessionName;
logger = new CustomLogger(context, path, sessionName, mSensorName, "txt", false, mNanosOffset, logFileMaxSize);
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
// Offset to match timestamps both in master and slaves devices
mNanosOffset = nanosOffset;
mGpsStatusListener = new GpsStatusListener();
}
private Iterable<GpsSatellite> getGpsSatellites(){
synchronized (this) {
GpsStatus status = mLocationManager.getGpsStatus(null);
return (status == null) ? null : status.getSatellites();
}
}
private void logSatelliteInfo(Iterable<GpsSatellite> gpsSatellites){
int satCounter = 0;
// System nanoseconds since boot, including time spent in sleep.
long nanoTime = SystemClock.elapsedRealtimeNanos() + mNanosOffset;
// System local time in millis
long currentMillis = (new Date()).getTime();
String message = String.format("%s", currentMillis) + ";"
+ String.format("%s", nanoTime) + ";"
+ String.format("%s", mNanosOffset);
for(GpsSatellite satellite: gpsSatellites){
satCounter++;
// PRN (pseudo-random number) for the satellite.
int prn = satellite.getPrn();
// Signal to noise ratio for the satellite.
float snr = satellite.getSnr();
// Azimuth of the satellite in degrees.
float azimuth = satellite.getAzimuth();
// Elevation of the satellite in degrees.
float elevation = satellite.getElevation();
message += ";" + prn
+ ";" + snr
+ ";" + azimuth
+ ";" + elevation;
}
message += ";" + Integer.toString(satCounter);
logger.log(message);
logger.log(System.lineSeparator());
}
private class GpsStatusListener implements GpsStatus.Listener {
@Override
public void onGpsStatusChanged(int event) {
if (event != GpsStatus.GPS_EVENT_STOPPED) {
logSatelliteInfo(getGpsSatellites());
}
}
}
@Override
public void start() {
Log.i(TAG, "start:: Starting listener for sensor: " + getSensorName());
logger.start();
mLocationManager.addGpsStatusListener(mGpsStatusListener);
}
@Override
public void stop() {
Log.i(TAG,"stop:: Stopping listener for sensor " + getSensorName());
logger.stop();
if (mLocationManager != null) {
mLocationManager.removeGpsStatusListener(mGpsStatusListener);
}
}
@Override
public void haltAndRestartLogging() {
logger.stop();
logger.resetByteCounter();
logger.start();
}
@Override
public void updateNanosOffset(long nanosOffset) {
mNanosOffset = nanosOffset;
}
}
| 34.169935 | 128 | 0.671576 |
c759385f7e026d219a91b9d7610332764697a51c | 427 | package net.kno3.season.roverruckus.solus.program.teleop;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import net.kno3.opMode.DriverControlledProgram;
import net.kno3.robot.Robot;
import net.kno3.season.roverruckus.solus.robot.Solus;
@TeleOp(name = "Solus Teleop")
public class SolusTeleop extends DriverControlledProgram {
@Override
protected Robot buildRobot() {
return new Solus(this);
}
} | 25.117647 | 58 | 0.770492 |
8e192739634f46272b7afb0ec4322dc88e9cf5e6 | 5,260 | /*
* 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.oodt.cas.filemgr.ingest;
//OODT imports
import org.apache.oodt.cas.filemgr.structs.exceptions.CatalogException;
import org.apache.oodt.cas.filemgr.structs.exceptions.IngestException;
import org.apache.oodt.cas.metadata.MetExtractor;
import org.apache.oodt.cas.metadata.Metadata;
//JDK imports
import java.io.Closeable;
import java.io.File;
import java.net.URL;
import java.util.List;
/**
* @author mattmann
* @author bfoster
* @version $Revision$
*
* <p>
* An interface for ingesting {@link Product}s
* </p>.
*/
public interface Ingester extends Closeable {
/**
* Ingests a {@link Product} to the file manager service object identified
* by the given {@link URL} parameter. The product {@link Metadata} is
* extracted dynamically using the provided {@link MetExtractor} interface.
*
* @param fmUrl
* The {@link URL} pointer to the file manager service.
* @param prodFile
* The {@link File} pointer to the product file.
* @param extractor
* The given {@link MetExtractor} to use to extract
* {@link Metadata} from the {@link Product}.
* @param metConfFile
* A Config{@link File} for the {@link MetExtractor}.
* @return The ID returned by the file manager for the newly ingested
* product.
* @throws IngestException
* If there is an error ingesting the {@link Product}
*/
String ingest(URL fmUrl, File prodFile, MetExtractor extractor,
File metConfFile) throws IngestException;
/**
* Ingests a {@link Product} to the file manager service object identified
* by the given {@link URL} parameter. The product {@link Metadata} is
* provided a priori.
*
* @param fmUrl
* The {@link URL} pointer to the file manager service.
* @param prodFile
* The {@link File} pointer to the product file.
* @param met
* The given {@link Metadata} object already extracted from the
* {@link Product}.
* @return The ID returned by the file manager for the newly ingested
* product.
* @throws IngestException
* If there is an error ingesting the {@link Product}
*/
String ingest(URL fmUrl, File prodFile, Metadata met)
throws IngestException;
/**
*
* @param fmUrl
* The {@link URL} pointer to the file manager service.
* @param prodFiles
* A {@link List} of {@link String} filePaths pointing to
* {@link Product} files to ingest.
* @param extractor
* The given {@link MetExtractor} to use to extract
* {@link Metadata} from the {@link Product}s.
* @param metConfFile
* A Config{@link File} for the {@link MetExtractor}.
* @throws IngestException
* If there is an error ingesting the {@link Product}s.
*/
void ingest(URL fmUrl, List<String> prodFiles, MetExtractor extractor,
File metConfFile);
/**
* Checks the file manager at the given {@link URL} to see whether or not it
* knows about the provided {@link Product} {@link File} parameter. To do
* this, it uses {@link File#getName()} as the {@link Metadata} key
* <code>Filename</code>.
*
* @param prodFile
* The {@link File} to check for existance of within the file
* manager at given {@link URL}.
* @url The {@link URL} pointer to the file manager service.
* @return
*/
boolean hasProduct(URL fmUrl, File prodFile) throws CatalogException;
/**
* Checks the file manager at the given {@link URL} to see whether or not it
* knows about the provided {@link Product} with the given
* <code>productName</code> parameter. To do this, it uses the provided
* <code>productName</code> key as the {@link Metadata} key to search for
* in the catalog.
*
* @param fmUrl
* The {@link URL} pointer to the file manager service.
* @param productName
* The {@link Product} to search for, identified by its (possibly
* not unique) name.
* @return True if the file manager has the product, false otherwise.
*/
boolean hasProduct(URL fmUrl, String productName) throws CatalogException;
}
| 39.253731 | 80 | 0.638213 |
c83f9a2bf1521f2145bb16b9c2a6c58a0940ab89 | 2,242 | package net.sf.l2j.gameserver.scripting.quests;
import net.sf.l2j.gameserver.model.actor.Creature;
import net.sf.l2j.gameserver.model.actor.Npc;
import net.sf.l2j.gameserver.model.actor.Player;
import net.sf.l2j.gameserver.scripting.Quest;
import net.sf.l2j.gameserver.scripting.QuestState;
public class Q050_LanoscosSpecialBait extends Quest
{
private static final String qn = "Q050_LanoscosSpecialBait";
// Item
private static final int ESSENCE_OF_WIND = 7621;
// Reward
private static final int WIND_FISHING_LURE = 7610;
public Q050_LanoscosSpecialBait()
{
super(50, "Lanosco's Special Bait");
setItemsIds(ESSENCE_OF_WIND);
addStartNpc(31570); // Lanosco
addTalkId(31570);
addKillId(21026); // Singing wind
}
@Override
public String onAdvEvent(String event, Npc npc, Player player)
{
String htmltext = event;
QuestState st = player.getQuestState(qn);
if (st == null)
return htmltext;
if (event.equalsIgnoreCase("31570-03.htm"))
{
st.setState(STATE_STARTED);
st.set("cond", "1");
st.playSound(QuestState.SOUND_ACCEPT);
}
else if (event.equalsIgnoreCase("31570-07.htm"))
{
htmltext = "31570-06.htm";
st.takeItems(ESSENCE_OF_WIND, -1);
st.rewardItems(WIND_FISHING_LURE, 4);
st.playSound(QuestState.SOUND_FINISH);
st.exitQuest(false);
}
return htmltext;
}
@Override
public String onTalk(Npc npc, Player player)
{
QuestState st = player.getQuestState(qn);
String htmltext = getNoQuestMsg();
if (st == null)
return htmltext;
switch (st.getState())
{
case STATE_CREATED:
htmltext = (player.getLevel() < 27) ? "31570-02.htm" : "31570-01.htm";
break;
case STATE_STARTED:
htmltext = (st.getQuestItemsCount(ESSENCE_OF_WIND) == 100) ? "31570-04.htm" : "31570-05.htm";
break;
case STATE_COMPLETED:
htmltext = getAlreadyCompletedMsg();
break;
}
return htmltext;
}
@Override
public String onKill(Npc npc, Creature killer)
{
final Player player = killer.getActingPlayer();
final QuestState st = checkPlayerCondition(player, npc, "cond", "1");
if (st == null)
return null;
if (st.dropItems(ESSENCE_OF_WIND, 1, 100, 500000))
st.set("cond", "2");
return null;
}
} | 23.113402 | 97 | 0.694023 |
37e3fb3a1548d55f640dfe85e305cd3486740b80 | 609 | package ch.uzh.feedbag.backend.repository;
import ch.uzh.feedbag.backend.entity.EventTimeStamp;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository("eventTimeStampRepository")
public interface EventTimeStampRepository extends CrudRepository<EventTimeStamp, Long> {
@Modifying
@Transactional
@Query(value = "DELETE FROM EventTimeStamp e")
void truncate();
}
| 35.823529 | 88 | 0.840722 |
f1976aac94a7822b03d4b72d25801547c26999e6 | 307 | package com.fsryan.forsuredb.api;
import org.junit.Before;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public abstract class FinderTest {
@Mock
protected Resolver mockResolver;
@Before
public void setUpResolver() {
MockitoAnnotations.initMocks(this);
}
}
| 18.058824 | 43 | 0.729642 |
b18308239ec72374e4a7cc8f4983beec76887442 | 323 | package pl.joegreen.sergeants.framework.model;
import lombok.Value;
@Value
public class ChatMessage {
public enum ChatType {
GAME, TEAM, UNKNOWN
}
ChatType roomType;
String message;
/**
* Name of player sending the message. Can be null for server messages.
*/
String username;
}
| 19 | 75 | 0.665635 |
9dc34ddf8fecd565d4bc87fd1e98490c6470b513 | 290 | package edu.sabanciuniv.berry.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import edu.sabanciuniv.berry.domain.DBFile;
@Repository
public interface DBFileRepository extends JpaRepository<DBFile, String> {
}
| 24.166667 | 73 | 0.841379 |
3deec57a7d3a86e456ad4643a37a692b67f165d9 | 3,899 | package net.voxelindustry.brokkgui.internal;
import net.voxelindustry.brokkgui.component.GuiNode;
import net.voxelindustry.brokkgui.component.IGuiPopup;
import net.voxelindustry.brokkgui.gui.IGuiSubWindow;
import net.voxelindustry.brokkgui.gui.IGuiWindow;
import net.voxelindustry.brokkgui.paint.RenderPass;
import net.voxelindustry.brokkgui.style.ICascadeStyleable;
import net.voxelindustry.brokkgui.style.IStyleable;
import net.voxelindustry.brokkgui.style.tree.StyleList;
import java.util.*;
import java.util.function.Supplier;
public class PopupHandler
{
private static Map<IGuiSubWindow, PopupHandler> instances = new IdentityHashMap<>();
public static PopupHandler getInstance(IGuiSubWindow window)
{
Objects.requireNonNull(window);
if (!instances.containsKey(window))
instances.put(window, new PopupHandler());
return instances.get(window);
}
private List<IGuiPopup> popups;
private List<IGuiPopup> toRemove;
private List<IGuiPopup> toAdd;
private Supplier<StyleList> styleSupplier;
private PopupHandler()
{
this.popups = new ArrayList<>();
this.toRemove = new ArrayList<>();
this.toAdd = new ArrayList<>();
}
public void addPopup(IGuiPopup popup)
{
this.toAdd.add(popup);
if (popup instanceof ICascadeStyleable)
{
((ICascadeStyleable) popup).setStyleTree(this.styleSupplier);
((ICascadeStyleable) popup).refreshStyle();
}
}
public boolean removePopup(IGuiPopup popup)
{
return this.toRemove.add(popup);
}
public boolean isPopupPresent(IGuiPopup popup)
{
return this.popups.contains(popup);
}
public void delete(IGuiWindow window)
{
this.popups.clear();
this.toAdd.clear();
this.toRemove.clear();
instances.remove(window);
}
public void renderPopupInPass(IGuiRenderer renderer, RenderPass pass, int mouseX, int mouseY)
{
this.popups.removeIf(toRemove::contains);
toRemove.clear();
this.popups.addAll(toAdd);
toAdd.clear();
this.popups.forEach(popup -> popup.renderNode(renderer, pass, mouseX, mouseY));
}
public void setStyleSupplier(Supplier<StyleList> styleSupplier)
{
this.styleSupplier = styleSupplier;
this.popups.forEach(popup ->
{
if (popup instanceof ICascadeStyleable)
{
((ICascadeStyleable) popup).setStyleTree(styleSupplier);
((ICascadeStyleable) popup).refreshStyle();
}
});
this.toAdd.forEach(popup ->
{
if (popup instanceof ICascadeStyleable)
{
((ICascadeStyleable) popup).setStyleTree(styleSupplier);
((ICascadeStyleable) popup).refreshStyle();
}
});
}
public void refreshStyle()
{
this.popups.forEach(popup ->
{
if (popup instanceof IStyleable)
((IStyleable) popup).refreshStyle();
});
this.toAdd.forEach(popup ->
{
if (popup instanceof ICascadeStyleable)
{
((ICascadeStyleable) popup).setStyleTree(styleSupplier);
((ICascadeStyleable) popup).refreshStyle();
}
});
}
public void handleHover(int mouseX, int mouseY)
{
popups.forEach(popup ->
{
if (popup instanceof GuiNode)
((GuiNode) popup).handleHover(mouseX, mouseY, ((GuiNode) popup).isPointInside(mouseX, mouseY));
});
}
public void handleClick(int mouseX, int mouseY, int key)
{
popups.forEach(popup ->
{
if (popup instanceof GuiNode)
((GuiNode) popup).handleClick(mouseX, mouseY, key);
});
}
}
| 28.05036 | 111 | 0.616825 |
dd1fcccf4546f45a5760bf3fc736b79afe48069c | 3,669 | /*-
* ============LICENSE_START==========================================
* ONAP Portal
* ===================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
* ===================================================================
*
* Unless otherwise specified, all software contained herein is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this software 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.
*
* Unless otherwise specified, all documentation contained herein is licensed
* under the Creative Commons License, Attribution 4.0 Intl. (the "License");
* you may not use this documentation except in compliance with the License.
* You may obtain a copy of the License at
*
* https://creativecommons.org/licenses/by/4.0/
*
* Unless required by applicable law or agreed to in writing, documentation
* 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.
*
* ============LICENSE_END============================================
*
*
*/
package org.onap.portalapp.portal.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.Test;
import org.onap.portalapp.portal.domain.EPRole;
import org.onap.portalsdk.core.domain.RoleFunction;
import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
public class EPRoleTest {
@Test
public void testEpRole() {
EPRole role=new EPRole();
role.setActive(true);
role.setAppId(1l);
role.setAppRoleId(2l);
role.setId(3l);
role.setName("TEST_ADMIN");
SortedSet<EPRole> childRoles = new TreeSet<EPRole>();
EPRole child=new EPRole();
child.setActive(true);
child.setAppId(1l);
child.setAppRoleId(3l);
child.setId(6l);
child.setName("TEST_USER");
childRoles.add(child);
role.setChildRoles(childRoles);
SortedSet<EPRole> parentRoles = new TreeSet<EPRole>();
EPRole parent=new EPRole();
parent.setActive(true);
parent.setAppId(1l);
parent.setAppRoleId(3l);
parent.setId(6l);
parent.setName("TEST_USER");
parentRoles.add(parent);
role.setParentRoles(parentRoles);
SortedSet<RoleFunction> rolefunction = new TreeSet<RoleFunction>();
RoleFunction function=new RoleFunction();
function.setAction("Test");;
function.setCode("code");
rolefunction.add(function);
role.setRoleFunctions(rolefunction);
role.setPriority(5);
role.setAppRoleId(3l);
assertEquals(3l, role.getAppRoleId().longValue());
assertNotNull(role.getChildRoles());
assertNotNull(role.getParentRoles());
assertNotNull(role.getRoleFunctions());
role.compareTo(role);
assertEquals(1l, role.getAppId().longValue());
assertEquals("TEST_ADMIN",role.getName());
role.removeChildRole(6l);
role.removeParentRole(6l);
assertEquals(role.toString(), "[Id = 3, name = TEST_ADMIN]");
role.removeRoleFunction("code");
role.addChildRole(child);
role.addParentRole(parent);
role.addRoleFunction(function);
}
}
| 33.66055 | 77 | 0.690924 |
bca160f6e36651149972f5fe8bdd7e93495740d9 | 2,129 | package com.admin.usermanagement.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.admin.usermanagement.bean.LoginBean;
public class LoginDao {
public static boolean validate(LoginBean loginBean) throws SQLException {
UserDao userdao = new UserDao();
Connection connection = userdao.getConnection();
boolean status = false;
try (PreparedStatement preparedStatement = connection
.prepareStatement("select * from user_table where username=? and password=?")) {
preparedStatement.setString(1, loginBean.getUsername());
preparedStatement.setString(2, loginBean.getPassword());
System.out.println(preparedStatement);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
status = true;
// connection.close();
} catch (SQLException e) {
printSQLException(e);
}
return status;
}
private static void printSQLException(SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
public static String getUserRole(String username1) {
UserDao userdao = new UserDao();
Connection connection = userdao.getConnection();
String status = "";
try {
PreparedStatement preparedStatement = connection
.prepareStatement("select * from users where name=?");
preparedStatement.setString(1,username1);
System.out.println(preparedStatement);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
status = rs.getString(5);
System.out.println(status);
}
// connection.close();
} catch (SQLException e) {
printSQLException(e);
}
return status;
}
} | 25.963415 | 85 | 0.669798 |
7fefc0800cd868fcf96ac84ed6dfa29026180df0 | 3,550 | /*
* Copyright 2020, OpenTelemetry 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.opentelemetry.sdk.metrics;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.testing.EqualsTester;
import io.opentelemetry.sdk.common.InstrumentationLibraryInfo;
import io.opentelemetry.sdk.internal.TestClock;
import io.opentelemetry.sdk.metrics.aggregator.NoopAggregator;
import io.opentelemetry.sdk.metrics.common.InstrumentValueType;
import io.opentelemetry.sdk.resources.Resource;
import java.util.Collections;
import org.junit.Test;
public class AbstractMeasureTest {
private static final boolean ABSOLUTE = true;
private static final boolean NON_ABSOLUTE = false;
@Test
public void getValues() {
assertThat(new TestMeasureInstrument(InstrumentValueType.LONG, ABSOLUTE).isAbsolute()).isTrue();
assertThat(new TestMeasureInstrument(InstrumentValueType.LONG, NON_ABSOLUTE).isAbsolute())
.isFalse();
}
@Test
public void attributeValue_EqualsAndHashCode() {
EqualsTester tester = new EqualsTester();
tester.addEqualityGroup(
new TestMeasureInstrument(InstrumentValueType.LONG, ABSOLUTE),
new TestMeasureInstrument(InstrumentValueType.LONG, ABSOLUTE));
tester.addEqualityGroup(
new TestMeasureInstrument(InstrumentValueType.LONG, NON_ABSOLUTE),
new TestMeasureInstrument(InstrumentValueType.LONG, NON_ABSOLUTE));
tester.addEqualityGroup(
new TestMeasureInstrument(InstrumentValueType.DOUBLE, ABSOLUTE),
new TestMeasureInstrument(InstrumentValueType.DOUBLE, ABSOLUTE));
tester.addEqualityGroup(
new TestMeasureInstrument(InstrumentValueType.DOUBLE, NON_ABSOLUTE),
new TestMeasureInstrument(InstrumentValueType.DOUBLE, NON_ABSOLUTE));
tester.testEquals();
}
private static final class TestMeasureInstrument extends AbstractMeasure<TestBoundMeasure> {
private static final InstrumentDescriptor INSTRUMENT_DESCRIPTOR =
InstrumentDescriptor.create(
"name",
"description",
"1",
Collections.singletonMap("key_2", "value_2"),
Collections.singletonList("key"));
private static final MeterProviderSharedState METER_PROVIDER_SHARED_STATE =
MeterProviderSharedState.create(TestClock.create(), Resource.getEmpty());
private static final MeterSharedState METER_SHARED_STATE =
MeterSharedState.create(InstrumentationLibraryInfo.getEmpty());
TestMeasureInstrument(InstrumentValueType instrumentValueType, boolean absolute) {
super(
INSTRUMENT_DESCRIPTOR,
instrumentValueType,
METER_PROVIDER_SHARED_STATE,
METER_SHARED_STATE,
absolute);
}
@Override
TestBoundMeasure newBinding(Batcher batcher) {
return new TestBoundMeasure();
}
}
private static final class TestBoundMeasure extends AbstractBoundInstrument {
TestBoundMeasure() {
super(NoopAggregator.getFactory().getAggregator());
}
}
}
| 37.765957 | 100 | 0.749577 |
449e34a2caded13c23ec1410843bd6d4df8b1a3f | 2,499 | package projectplayground.core;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter;
import javax.sql.DataSource;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
// not needed as JSF 2.2 is implicitly protected against CSRF
http.csrf().disable();
// require all requests to be authenticated except for the resource
http
.authorizeRequests()
.antMatchers("/javax.faces.resource/**").permitAll()
.antMatchers("/**").authenticated();
// login
http.formLogin().loginPage("/login.xhtml").permitAll()
.failureUrl("/login.xhtml?error=true");
// logout
http.logout()
.clearAuthentication(true)
.logoutSuccessUrl("/login.xhtml")
.invalidateHttpSession(true);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth
// .jdbcAuthentication().passwordEncoder(new BCryptPasswordEncoder()).dataSource(dataSource)
// .usersByUsernameQuery("select username,password from user where username=?")
// .authoritiesByUsernameQuery("select username, 'ROLE_USER' from user where login=?");
.inMemoryAuthentication()
.withUser("marvin")
.password("{noop}12345").roles("ADMIN")
.and()
.withUser("mark").password("{noop}12345").roles("ADMIN")
.and()
.withUser("katja").password("{noop}12345").roles("ADMIN")
.and()
.withUser("fabian").password("{noop}12345").roles("ADMIN");
//jdbc auth didnt work, thatswhy we're using hardcoded logins...
}
} | 41.65 | 107 | 0.665866 |
b57a2aed58107a6cd0ea0e657c4a1e0de7e32c70 | 1,921 | package ru.job4j.comparable;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class SortUserTest {
@Test
public void whenListThenSortSet() {
SortUser sortUser = new SortUser();
User serg = new User("Sergey", 23);
User nick = new User("Nick", 34);
User dima = new User("Dima", 12);
User ivan = new User("Ivan", 27);
List<User> users = Arrays.asList(serg, nick, dima, ivan);
List<User> list = sortUser.sort(users);
assertThat(list.toString(), is("[Dima(12), Sergey(23), Ivan(27), Nick(34)]"));
}
@Test
public void whenListThenSortListByNameLength() {
SortUser sortUser = new SortUser();
User serg = new User("Sergey", 23);
User nick = new User("Nickolay", 34);
User dima = new User("Dimon", 12);
User ivan = new User("Ivan", 27);
User ivanJunior = new User("Ivan", 7);
List<User> users = Arrays.asList(serg, nick, ivanJunior, dima, ivan);
List<User> list = sortUser.sortNameLength(users);
assertThat(list.toString(), is("[Ivan(27), Ivan(7), Dimon(12), Sergey(23), Nickolay(34)]"));
}
@Test
public void whenListThenSortListByAllFields() {
SortUser sortUser = new SortUser();
User serg = new User("Sergey", 23);
User dima = new User("Dimon", 10);
User nick = new User("Nickolay", 34);
User dimaP = new User("Dimon", 12);
User ivan = new User("Ivan", 27);
User sergP = new User("Sergey", 43);
List<User> users = Arrays.asList(serg, dima, nick, dimaP, ivan, sergP);
List<User> list = sortUser.sortByAllFields(users);
assertThat(list.toString(), is("[Dimon(10), Dimon(12), Ivan(27), Nickolay(34), Sergey(23), Sergey(43)]")
);
}
}
| 36.942308 | 112 | 0.605934 |
cc3aa99da44883f3479e694fe5460a8ea34d248d | 4,960 | package com.codeyn.wechat.sdk.msg.utils;
import java.lang.reflect.Field;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codeyn.wechat.sdk.base.model.WcBase;
import com.codeyn.wechat.sdk.msg.enums.MsgType;
import com.codeyn.wechat.sdk.msg.model.receive.ReceivedMsg;
import com.codeyn.wechat.sdk.msg.model.send.ImageMsg;
import com.codeyn.wechat.sdk.msg.model.send.MusicMsg;
import com.codeyn.wechat.sdk.msg.model.send.NewsItem;
import com.codeyn.wechat.sdk.msg.model.send.NewsMsg;
import com.codeyn.wechat.sdk.msg.model.send.SentMsg;
import com.codeyn.wechat.sdk.msg.model.send.VideoMsg;
import com.codeyn.wechat.sdk.msg.model.send.VoiceMsg;
/**
* 利用 Dom4j 动态生成 xml 内容
*/
public class MsgSentBuilder {
private static final Logger logger = LoggerFactory.getLogger(MsgSentBuilder.class);
public static String build(SentMsg msg) {
Document dd = DocumentHelper.createDocument();
dd.setXMLEncoding(WcBase.ENCODING);
Element root = dd.addElement("xml");
Class<?> clazz = msg.getClass();
Class<?> parent = clazz.getSuperclass();
boolean isParent = SentMsg.class.equals(parent);
if(isParent){
build(msg, root, parent, !isParent);
}
if(MsgType.NEWS.equals(MsgType.get(msg.getMsgType()))){
buildNews((NewsMsg)msg, root);
}else{
build(msg, root, clazz, isParent);
}
return root.asXML();
}
private static void build(SentMsg msg, Element root, Class<?> clazz, boolean isChild) {
if(clazz != null){
root = isChild ? root.addElement(firstCharUpper(msg.getMsgType())) : root;
for(Field f : clazz.getDeclaredFields()){
f.setAccessible(true);
String name = firstCharUpper(f.getName());
try{
Object x = f.get(msg);
if(x != null){
Element e = root.addElement(name);
if(String.class.equals(f.getType())){
e.addCDATA(x.toString());
}else{
e.addText(f.get(msg).toString());
}
}
} catch (Exception e){
logger.error("Msg xml build error: ", e);
}
}
}
}
private static void buildNews(NewsMsg msg, Element root) {
root.addElement("ArticleCount").setText(String.valueOf(msg.getArticleCount()));
Element articles = root.addElement("Articles");
for(NewsItem item : msg.getArticles()){
Element element = articles.addElement("item");
for(Field f : NewsItem.class.getDeclaredFields()){
f.setAccessible(true);
String name = firstCharUpper(f.getName());
try{
Object x = f.get(item);
if(x != null){
element.addElement(name).addCDATA(x.toString());
}
} catch (Exception e){
logger.error("News msg xml build error: ", e);
}
}
}
}
public static String firstCharUpper(String str){
if(StringUtils.isNotBlank(str)){
return str.substring(0, 1).toUpperCase().concat(str.substring(1));
}
return str;
}
/**
* 根据type获取需要发送的消息
*/
public static SentMsg getSentMsg(ReceivedMsg inMsg, MsgType sentType){
switch(sentType){
case TEXT :
return new SentMsg(inMsg);
case IMAGE :
return new ImageMsg(inMsg);
case VOICE :
return new VoiceMsg(inMsg);
case VIDEO :
return new VideoMsg(inMsg);
case SHORT_VIDEO :
return new VideoMsg(inMsg);
case NEWS :
return new NewsMsg(inMsg);
case MUSIC :
return new MusicMsg(inMsg);
default:
return null;
}
}
public static void main(String[] args) throws Exception {
NewsMsg img = new NewsMsg();
img.setCreateTime(123L);
img.setFromUserName("xxx");
img.setToUserName("yyy");
img.setMsgType("news");
img.addNews("title1", "description1", "www.baidu.com", "www.codeyn.com");
img.addNews("title1", "description1", "www.baidu.com", "www.codeyn.com");
img.addNews("title1", "description1", "www.baidu.com", "www.codeyn.com");
System.out.println(build(img));
}
}
| 33.288591 | 91 | 0.540927 |
395ea421b4dd1eb5299792f10aec6339d386f747 | 14,090 | /*
* 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.cassandra.security;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import io.netty.handler.ssl.SupportedCipherSuiteFilter;
import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.config.EncryptionOptions;
/**
* A Factory for providing and setting up client {@link SSLSocket}s. Also provides
* methods for creating both JSSE {@link SSLContext} instances as well as netty {@link SslContext} instances.
*
* Netty {@link SslContext} instances are expensive to create (as well as to destroy) and consume a lof of resources
* (especially direct memory), but instances can be reused across connections (assuming the SSL params are the same).
* Hence we cache created instances in {@link #clientSslContext} and {@link #serverSslContext}.
*/
public final class SSLFactory
{
private static final Logger logger = LoggerFactory.getLogger(SSLFactory.class);
@VisibleForTesting
static volatile boolean checkedExpiry = false;
/**
* A cached reference of the {@link SslContext} for client-facing connections.
*/
private static final AtomicReference<SslContext> clientSslContext = new AtomicReference<>();
/**
* A cached reference of the {@link SslContext} for peer-to-peer, internode messaging connections.
*/
private static final AtomicReference<SslContext> serverSslContext = new AtomicReference<>();
/**
* List of files that trigger hot reloading of SSL certificates
*/
private static volatile List<HotReloadableFile> hotReloadableFiles = ImmutableList.of();
/**
* Default initial delay for hot reloading
*/
public static final int DEFAULT_HOT_RELOAD_INITIAL_DELAY_SEC = 600;
/**
* Default periodic check delay for hot reloading
*/
public static final int DEFAULT_HOT_RELOAD_PERIOD_SEC = 600;
/**
* State variable to maintain initialization invariant
*/
private static boolean isHotReloadingInitialized = false;
/**
* Helper class for hot reloading SSL Contexts
*/
private static class HotReloadableFile
{
enum Type
{
SERVER,
CLIENT
}
private final File file;
private volatile long lastModTime;
private final Type certType;
HotReloadableFile(String path, Type type)
{
file = new File(path);
lastModTime = file.lastModified();
certType = type;
}
boolean shouldReload()
{
long curModTime = file.lastModified();
boolean result = curModTime != lastModTime;
lastModTime = curModTime;
return result;
}
public boolean isServer()
{
return certType == Type.SERVER;
}
public boolean isClient()
{
return certType == Type.CLIENT;
}
}
/**
* Create a JSSE {@link SSLContext}.
*/
@SuppressWarnings("resource")
public static SSLContext createSSLContext(EncryptionOptions options, boolean buildTruststore) throws IOException
{
TrustManager[] trustManagers = null;
if (buildTruststore)
trustManagers = buildTrustManagerFactory(options).getTrustManagers();
KeyManagerFactory kmf = buildKeyManagerFactory(options);
try
{
SSLContext ctx = SSLContext.getInstance(options.protocol);
ctx.init(kmf.getKeyManagers(), trustManagers, null);
return ctx;
}
catch (Exception e)
{
throw new IOException("Error creating/initializing the SSL Context", e);
}
}
static TrustManagerFactory buildTrustManagerFactory(EncryptionOptions options) throws IOException
{
try (InputStream tsf = Files.newInputStream(Paths.get(options.truststore)))
{
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
options.algorithm == null ? TrustManagerFactory.getDefaultAlgorithm() : options.algorithm);
KeyStore ts = KeyStore.getInstance(options.store_type);
ts.load(tsf, options.truststore_password.toCharArray());
tmf.init(ts);
return tmf;
}
catch (Exception e)
{
throw new IOException("failed to build trust manager store for secure connections", e);
}
}
static KeyManagerFactory buildKeyManagerFactory(EncryptionOptions options) throws IOException
{
try (InputStream ksf = Files.newInputStream(Paths.get(options.keystore)))
{
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
options.algorithm == null ? KeyManagerFactory.getDefaultAlgorithm() : options.algorithm);
KeyStore ks = KeyStore.getInstance(options.store_type);
ks.load(ksf, options.keystore_password.toCharArray());
if (!checkedExpiry)
{
for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements(); )
{
String alias = aliases.nextElement();
if (ks.getCertificate(alias).getType().equals("X.509"))
{
Date expires = ((X509Certificate) ks.getCertificate(alias)).getNotAfter();
if (expires.before(new Date()))
logger.warn("Certificate for {} expired on {}", alias, expires);
}
}
checkedExpiry = true;
}
kmf.init(ks, options.keystore_password.toCharArray());
return kmf;
}
catch (Exception e)
{
throw new IOException("failed to build trust manager store for secure connections", e);
}
}
public static String[] filterCipherSuites(String[] supported, String[] desired)
{
if (Arrays.equals(supported, desired))
return desired;
List<String> ldesired = Arrays.asList(desired);
ImmutableSet<String> ssupported = ImmutableSet.copyOf(supported);
String[] ret = Iterables.toArray(Iterables.filter(ldesired, Predicates.in(ssupported)), String.class);
if (desired.length > ret.length && logger.isWarnEnabled())
{
Iterable<String> missing = Iterables.filter(ldesired, Predicates.not(Predicates.in(Sets.newHashSet(ret))));
logger.warn("Filtering out {} as it isn't supported by the socket", Iterables.toString(missing));
}
return ret;
}
/**
* get a netty {@link SslContext} instance
*/
public static SslContext getSslContext(EncryptionOptions options, boolean buildTruststore, boolean forServer) throws IOException
{
return getSslContext(options, buildTruststore, forServer, OpenSsl.isAvailable());
}
/**
* Get a netty {@link SslContext} instance.
*/
@VisibleForTesting
static SslContext getSslContext(EncryptionOptions options, boolean buildTruststore, boolean forServer, boolean useOpenSsl) throws IOException
{
SslContext sslContext;
if (forServer && (sslContext = serverSslContext.get()) != null)
return sslContext;
if (!forServer && (sslContext = clientSslContext.get()) != null)
return sslContext;
/*
There is a case where the netty/openssl combo might not support using KeyManagerFactory. specifically,
I've seen this with the netty-tcnative dynamic openssl implementation. using the netty-tcnative static-boringssl
works fine with KeyManagerFactory. If we want to support all of the netty-tcnative options, we would need
to fall back to passing in a file reference for both a x509 and PKCS#8 private key file in PEM format (see
{@link SslContextBuilder#forServer(File, File, String)}). However, we are not supporting that now to keep
the config/yaml API simple.
*/
KeyManagerFactory kmf = null;
if (forServer || options.require_client_auth)
kmf = buildKeyManagerFactory(options);
SslContextBuilder builder;
if (forServer)
{
builder = SslContextBuilder.forServer(kmf);
builder.clientAuth(options.require_client_auth ? ClientAuth.REQUIRE : ClientAuth.NONE);
}
else
{
builder = SslContextBuilder.forClient().keyManager(kmf);
}
builder.sslProvider(useOpenSsl ? SslProvider.OPENSSL : SslProvider.JDK);
// only set the cipher suites if the opertor has explicity configured values for it; else, use the default
// for each ssl implemention (jdk or openssl)
if (options.cipher_suites != null && options.cipher_suites.length > 0)
builder.ciphers(Arrays.asList(options.cipher_suites), SupportedCipherSuiteFilter.INSTANCE);
if (buildTruststore)
builder.trustManager(buildTrustManagerFactory(options));
SslContext ctx = builder.build();
AtomicReference<SslContext> ref = forServer ? serverSslContext : clientSslContext;
if (ref.compareAndSet(null, ctx))
return ctx;
return ref.get();
}
/**
* Performs a lightweight check whether the certificate files have been refreshed.
*
* @throws IllegalStateException if {@link #initHotReloading(EncryptionOptions.ServerEncryptionOptions, EncryptionOptions, boolean)}
* is not called first
*/
public static void checkCertFilesForHotReloading()
{
if (!isHotReloadingInitialized)
throw new IllegalStateException("Hot reloading functionality has not been initialized.");
logger.trace("Checking whether certificates have been updated");
if (hotReloadableFiles.stream().anyMatch(f -> f.isServer() && f.shouldReload()))
{
logger.info("Server ssl certificates have been updated. Reseting the context for new peer connections.");
serverSslContext.set(null);
}
if (hotReloadableFiles.stream().anyMatch(f -> f.isClient() && f.shouldReload()))
{
logger.info("Client ssl certificates have been updated. Reseting the context for new client connections.");
clientSslContext.set(null);
}
}
/**
* Determines whether to hot reload certificates and schedules a periodic task for it.
*
* @param serverEncryptionOptions
* @param clientEncryptionOptions
*/
public static synchronized void initHotReloading(EncryptionOptions.ServerEncryptionOptions serverEncryptionOptions,
EncryptionOptions clientEncryptionOptions,
boolean force)
{
if (isHotReloadingInitialized && !force)
return;
logger.debug("Initializing hot reloading SSLContext");
List<HotReloadableFile> fileList = new ArrayList<>();
if (serverEncryptionOptions.enabled)
{
fileList.add(new HotReloadableFile(serverEncryptionOptions.keystore, HotReloadableFile.Type.SERVER));
fileList.add(new HotReloadableFile(serverEncryptionOptions.truststore, HotReloadableFile.Type.SERVER));
}
if (clientEncryptionOptions.enabled)
{
fileList.add(new HotReloadableFile(clientEncryptionOptions.keystore, HotReloadableFile.Type.CLIENT));
fileList.add(new HotReloadableFile(clientEncryptionOptions.truststore, HotReloadableFile.Type.CLIENT));
}
hotReloadableFiles = ImmutableList.copyOf(fileList);
if (!isHotReloadingInitialized)
{
ScheduledExecutors.scheduledTasks.scheduleWithFixedDelay(SSLFactory::checkCertFilesForHotReloading,
DEFAULT_HOT_RELOAD_INITIAL_DELAY_SEC,
DEFAULT_HOT_RELOAD_PERIOD_SEC, TimeUnit.SECONDS);
}
isHotReloadingInitialized = true;
}
}
| 38.708791 | 145 | 0.662952 |
4236c867c79ae7e36933046ab7a161ef1642e02b | 8,938 | import java.util.*;
import org.junit.Test;
import static org.junit.Assert.*;
// LC787: https://leetcode.com/problems/cheapest-flights-within-k-stops/
//
// There are n cities connected by m flights. Each fight starts from city u and
// arrives at v with a price w. Given all the cities and fights, together with
// starting city src and the destination dst, find the cheapest price from src
// to dst with up to k stops. If there is no such route, output -1.
public class CheapestFlightsWithinKStops {
// BFS + Queue + Hash Table
// time complexity: O(N ^ 2 * K), space complexity: O(N ^ 2)
// beats 53.52%(32 ms for 41 tests)
public int findCheapestPrice(int n, int[][] flights, int src, int dst,
int K) {
Map<Integer, Map<Integer, Integer> > graph = new HashMap<>();
for (int i = 0; i < n; i++) {
graph.put(i, new HashMap<>());
}
for (int[] f : flights) {
graph.get(f[0]).put(f[1], f[2]);
}
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[] { src, 0 });
int res = Integer.MAX_VALUE;
for (int k = K + 1; k >= 0; k--) {
for (int i = queue.size(); i > 0; i--) {
int[] cur = queue.poll();
int stop = cur[0];
if (stop == dst) {
res = Math.min(res, cur[1]);
continue;
}
for (Map.Entry<Integer, Integer> x : graph.get(stop).entrySet()) {
int newCost = cur[1] + x.getValue();
if (newCost < res) {
queue.offer(new int[] { x.getKey(), newCost });
}
}
}
}
return (res == Integer.MAX_VALUE) ? -1 : res;
}
// Solution of Choice
// BFS + Heap + Hash Table (Dijkstra's algorithm)
// time complexity: O(N ^ 2 * K), space complexity: O(N ^ 2)
// beats 60.07%(22 ms for 41 tests)
public int findCheapestPrice2(int n, int[][] flights, int src, int dst,
int K) {
Map<Integer, Map<Integer, Integer> > graph = new HashMap<>();
for (int i = 0; i < n; i++) {
graph.put(i, new HashMap<>());
}
for (int[] f : flights) {
graph.get(f[0]).put(f[1], f[2]);
}
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
public int compare(int[] a, int[] b) { return a[1] - b[1]; }
});
pq.offer(new int[] { src, 0, K + 1 });
while (!pq.isEmpty()) {
int[] cur = pq.poll();
int stop = cur[0];
int cost = cur[1];
if (stop == dst) return cost;
int more = cur[2];
if (more <= 0) continue;
Map<Integer, Integer> m = graph.get(stop);
for (int v : m.keySet()) {
pq.offer(new int[] { v, cost + m.get(v), more - 1 });
}
}
return -1;
}
// BFS + Heap + Hash Table (Dijkstra's algorithm)
// time complexity: O(N ^ 2 * K), space complexity: O(N ^ 2)
// beats 95.58%(7 ms for 41 tests)
public int findCheapestPrice3(int n, int[][] flights, int src, int dst,
int K) {
int[][] graph = new int[n][n];
for (int[] f : flights) {
graph[f[0]][f[1]] = f[2];
}
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[1] - b[1];
}
});
int[] cost = new int[n];
Arrays.fill(cost, Integer.MAX_VALUE);
cost[src] = 0;
int[] stop = new int[n];
Arrays.fill(stop, K + 1);
stop[src] = 0;
for (pq.offer(new int[] { src, 0, 0 }); !pq.isEmpty(); ) {
int[] cur = pq.poll();
if (cur[0] == dst) return cur[1];
if (cur[2] == K + 1) continue;
int[] nextCosts = graph[cur[0]];
for (int i = 0; i < n; i++) {
if (nextCosts[i] == 0) continue;
int newCost = cur[1] + nextCosts[i];
int newStops = cur[2] + 1;
if (newCost < cost[i]) {
pq.offer(new int[] { i, newCost, newStops });
cost[i] = newCost;
} else if (newStops < stop[i]) {
pq.offer(new int[] { i, newCost, newStops });
stop[i] = newStops;
}
}
}
return (cost[dst] == Integer.MAX_VALUE) ? -1 : cost[dst];
}
// Solution of Choice
// DFS + Recursion + Backtracking
// time complexity: O(N ^ 2 * K), space complexity: O(N ^ 2)
// beats 37.53%(61 ms for 41 tests)
public int findCheapestPrice4(int n, int[][] flights, int src, int dst,
int K) {
int[][] graph = new int[n][n];
for (int[] f : flights) {
graph[f[0]][f[1]] = f[2];
}
int[] res = new int[] { Integer.MAX_VALUE };
dfs(graph, src, dst, K + 1, 0, new boolean[n], res);
return (res[0] == Integer.MAX_VALUE) ? -1 : res[0];
}
private void dfs(int[][] graph, int src, int dst, int k, int curCost,
boolean[] visited, int[] res) {
if (src == dst) {
res[0] = curCost;
return;
}
if (k == 0) return;
visited[src] = true;
int i = 0;
for (int cost : graph[src]) {
if (visited[i++] || cost == 0) continue;
if (curCost + cost <= res[0]) {
dfs(graph, i - 1, dst, k - 1, curCost + cost, visited, res);
}
}
visited[src] = false; // Backtracking!
}
// Dynamic Programming
// time complexity: O(N ^ 2 * K), space complexity: O(N * K)
// beats 73.10%(12 ms for 41 tests)
public int findCheapestPrice5(int n, int[][] flights, int src, int dst,
int K) {
int[][] dp = new int[K + 2][n];
int max = Integer.MAX_VALUE / 2;
for (int[] d : dp) {
Arrays.fill(d, max);
}
dp[0][src] = 0;
for (int i = 1; i <= K + 1; i++) {
dp[i][src] = 0;
for (int[] f : flights) {
dp[i][f[1]] = Math.min(dp[i][f[1]], dp[i - 1][f[0]] + f[2]);
}
}
return (dp[K + 1][dst] >= max) ? -1 : dp[K + 1][dst];
}
// Solution of Choice
// Dynamic Programming
// time complexity: O(N ^ 2 * K), space complexity: O(N)
// beats 90.23%(8 ms for 41 tests)
public int findCheapestPrice6(int n, int[][] flights, int src, int dst,
int K) {
int[] dp = new int[n];
int max = Integer.MAX_VALUE / 2;
Arrays.fill(dp, max);
dp[src] = 0;
for (int i = 1; i <= K + 1; i++) {
int[] next = dp.clone();
for (int[] f : flights) {
next[f[1]] = Math.min(next[f[1]], dp[f[0]] + f[2]);
}
dp = next;
}
return (dp[dst] >= max) ? -1 : dp[dst];
}
void test(int n, int[][] flights, int src, int dst, int K, int expected) {
assertEquals(expected, findCheapestPrice(n, flights, src, dst, K));
assertEquals(expected, findCheapestPrice2(n, flights, src, dst, K));
assertEquals(expected, findCheapestPrice3(n, flights, src, dst, K));
assertEquals(expected, findCheapestPrice4(n, flights, src, dst, K));
assertEquals(expected, findCheapestPrice5(n, flights, src, dst, K));
assertEquals(expected, findCheapestPrice6(n, flights, src, dst, K));
}
@Test
public void test() {
test(4, new int[][] { { 0, 1, 1 }, { 0, 2, 5 }, { 1, 2, 1 }, { 2, 3, 1 } },
0, 3, 1, 6);
test(3, new int[][] { { 0, 1, 100 }, { 1, 2, 100 }, { 0, 2, 500 } }, 0,
2, 1, 200);
test(3, new int[][] { { 0, 1, 100 }, { 1, 2, 100 }, { 0, 2, 500 } }, 0,
2, 0, 500);
test(10, new int[][] { { 3, 4, 4 }, { 2, 5, 6 }, { 4, 7, 10 },
{ 9, 6, 5 }, { 7, 4, 4 }, { 6, 2, 10 },
{ 6, 8, 6 }, { 7, 9, 4 }, { 1, 5, 4 },
{ 1, 0, 4 }, { 9, 7, 3 }, { 7, 0, 5 },
{ 6, 5, 8 }, { 1, 7, 6 }, { 4, 0, 9 },
{ 5, 9, 1 }, { 8, 7, 3 }, { 1, 2, 6 },
{ 4, 1, 5 }, { 5, 2, 4 }, { 1, 9, 1 },
{ 7, 8, 10 }, { 0, 4, 2 }, { 7, 2, 8 } },
6, 0, 7, 14);
}
public static void main(String[] args) {
String clazz =
new Object() {}.getClass().getEnclosingClass().getSimpleName();
org.junit.runner.JUnitCore.main(clazz);
}
}
| 38.360515 | 83 | 0.440814 |
f29aafba261fa6410ce72ce8c8d883990de6bf18 | 1,044 | /*
* Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*
* This file has been automatically generated. Please do not edit it manually.
* To regenerate the file, use the script "pkg/analysis_server/tool/spec/generate_files".
*/
package org.dartlang.analysis.server.protocol;
/**
* An enumeration of the types of parameters.
*
* @coverage dart.server.generated.types
*/
public class ParameterKind {
/**
* An optional named parameter.
*/
public static final String OPTIONAL_NAMED = "OPTIONAL_NAMED";
/**
* An optional positional parameter.
*/
public static final String OPTIONAL_POSITIONAL = "OPTIONAL_POSITIONAL";
/**
* A required named parameter.
*/
public static final String REQUIRED_NAMED = "REQUIRED_NAMED";
/**
* A required positional parameter.
*/
public static final String REQUIRED_POSITIONAL = "REQUIRED_POSITIONAL";
}
| 26.769231 | 89 | 0.722222 |
cb20fb2ad890a7e03259ad782492e7d931105613 | 2,242 | package uk.gov.hmcts.reform.iacaseapi.domain.handlers.presubmit;
import static java.util.Objects.requireNonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import uk.gov.hmcts.reform.iacaseapi.domain.DateProvider;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.AsylumCase;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.AsylumCaseFieldDefinition;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.Event;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback.Callback;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback.PreSubmitCallbackResponse;
import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback.PreSubmitCallbackStage;
import uk.gov.hmcts.reform.iacaseapi.domain.handlers.PreSubmitCallbackHandler;
@Component
public class RequestCmaRequirementsPreparer implements PreSubmitCallbackHandler<AsylumCase> {
public static final int DUE_IN_WEEKS = 1;
private final DateProvider dateProvider;
@Autowired
public RequestCmaRequirementsPreparer(DateProvider dateProvider) {
this.dateProvider = dateProvider;
}
@Override
public boolean canHandle(PreSubmitCallbackStage callbackStage, Callback<AsylumCase> callback) {
requireNonNull(callbackStage, "callbackStage must not be null");
requireNonNull(callback, "callback must not be null");
return callbackStage == PreSubmitCallbackStage.ABOUT_TO_START
&& callback.getEvent() == Event.REQUEST_CMA_REQUIREMENTS;
}
@Override
public PreSubmitCallbackResponse<AsylumCase> handle(PreSubmitCallbackStage callbackStage, Callback<AsylumCase> callback) {
if (!canHandle(callbackStage, callback)) {
throw new IllegalStateException("Cannot handle callback");
}
AsylumCase asylumCase = callback.getCaseDetails().getCaseData();
String dueDate = dateProvider.now().plusWeeks(DUE_IN_WEEKS).toString();
asylumCase.write(AsylumCaseFieldDefinition.SEND_DIRECTION_DATE_DUE, dueDate);
asylumCase.write(AsylumCaseFieldDefinition.REQUEST_CMA_REQUIREMENTS_REASONS, "");
return new PreSubmitCallbackResponse<>(asylumCase);
}
}
| 43.115385 | 126 | 0.781891 |
dc81112ea751b92062830fba92be5d4529c1fc34 | 1,430 | package com.rewedigital.composer.helper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotSame;
public final class ValueObjectAssertions {
@SafeVarargs
public static <T> void assertIsValueObject(T first, T second, T... others) {
assertEqualObjectsAreEqual(first, second);
assertUnequalObjectsAreNotEqual(second, others);
assertEqualObjectsHaveEqualHashCode(first, second);
assertToStringOverwritten(first);
}
private static void assertEqualObjectsAreEqual(Object first, Object second) {
assertEquals(first, first);
assertEquals(first, second);
assertNotSame(first, second);
}
private static void assertUnequalObjectsAreNotEqual(Object second, Object... others) {
assertNotEquals(second, null);
assertNotEquals(second, new Object() {
});
for (Object other : others) {
assertNotEquals(second, other);
}
}
private static void assertEqualObjectsHaveEqualHashCode(Object first, Object second) {
assertEquals(first.hashCode(), first.hashCode());
assertEquals(first.hashCode(), second.hashCode());
}
private static void assertToStringOverwritten(Object obj) {
assertFalse(obj.toString().startsWith("java.lang.Object@"));
}
}
| 33.255814 | 90 | 0.704196 |
2157fa3e8aafa8f8452b27ecff7ae90404bdca9e | 9,628 | package velir.mock;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.AccessControlException;
import javax.jcr.AccessDeniedException;
import javax.jcr.Credentials;
import javax.jcr.InvalidItemStateException;
import javax.jcr.InvalidSerializedDataException;
import javax.jcr.Item;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.LoginException;
import javax.jcr.NamespaceException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.ReferentialIntegrityException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.retention.RetentionManager;
import javax.jcr.security.AccessControlManager;
import javax.jcr.version.VersionException;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.principal.PrincipalManager;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/**
* MockSession -
*
* @author Sam Griffin
* @version $Id: MockSession.java 7200 2013-12-19 21:25:26Z mmatthews $
*/
@SuppressWarnings("deprecation")
public class MockSession implements Session, JackrabbitSession{
private MockNode rootNode;
public MockSession() {
this.rootNode = new MockNode(this);
}
@Override
public Repository getRepository() {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public String getUserID() {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public String[] getAttributeNames() {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public Object getAttribute(String s) {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public Workspace getWorkspace() {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public Node getRootNode() throws RepositoryException {
return rootNode;
}
@Override
public Session impersonate(Credentials credentials) throws LoginException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public Node getNodeByUUID(String s) throws ItemNotFoundException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public Node getNodeByIdentifier(String s) throws ItemNotFoundException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public Item getItem(String s) throws PathNotFoundException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public Node getNode(String s) throws PathNotFoundException, RepositoryException {
s = s.replaceFirst("^/", "");
Node current = rootNode;
for (String nodeName : s.split("/")) {
current = current.getNode(nodeName);
}
return current;
}
@Override
public Property getProperty(String s) throws PathNotFoundException, RepositoryException {
String nodePath = s.replaceFirst("/[^/]+$", "");
String propertyName = s.replaceFirst("^.*/[^/]+$", "$1");
return getNode(nodePath).getProperty(propertyName);
}
@Override
public boolean itemExists(String s) throws RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public boolean nodeExists(String s) throws RepositoryException {
Node n;
try {
n = getNode(s);
} catch (Exception e) {
return false;
}
return n != null;
}
@Override
public boolean propertyExists(String s) throws RepositoryException {
Property p;
try {
p = getProperty(s);
} catch (Exception e) {
return false;
}
return p != null;
}
@Override
public void move(String s, String s2) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public void removeItem(String s) throws VersionException, LockException, ConstraintViolationException, AccessDeniedException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public void save() throws AccessDeniedException, ItemExistsException, ReferentialIntegrityException, ConstraintViolationException, InvalidItemStateException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException {
}
@Override
public void refresh(boolean b) throws RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public boolean hasPendingChanges() throws RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public ValueFactory getValueFactory() throws UnsupportedRepositoryOperationException, RepositoryException {
return new MockValueFactory();
}
@Override
public boolean hasPermission(String s, String s2) throws RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public void checkPermission(String s, String s2) throws AccessControlException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public boolean hasCapability(String s, Object o, Object[] objects) throws RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public ContentHandler getImportContentHandler(String s, int i) throws PathNotFoundException, ConstraintViolationException, VersionException, LockException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public void importXML(String s, InputStream inputStream, int i) throws IOException, PathNotFoundException, ItemExistsException, ConstraintViolationException, VersionException, InvalidSerializedDataException, LockException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public void exportSystemView(String s, ContentHandler contentHandler, boolean b, boolean b2) throws PathNotFoundException, SAXException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public void exportSystemView(String s, OutputStream outputStream, boolean b, boolean b2) throws IOException, PathNotFoundException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
//TODO: implement
}
@Override
public void exportDocumentView(String s, ContentHandler contentHandler, boolean b, boolean b2) throws PathNotFoundException, SAXException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
//TODO: implement
}
@Override
public void exportDocumentView(String s, OutputStream outputStream, boolean b, boolean b2) throws IOException, PathNotFoundException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
//TODO: implement
}
@Override
public void setNamespacePrefix(String s, String s2) throws NamespaceException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
//TODO: implement
}
@Override
public String[] getNamespacePrefixes() throws RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public String getNamespaceURI(String s) throws NamespaceException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public String getNamespacePrefix(String s) throws NamespaceException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public void logout() {
rootNode = null;
}
@Override
public boolean isLive() {
return rootNode != null;
}
@Override
public void addLockToken(String s) {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
//TODO: implement
}
@Override
public String[] getLockTokens() {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public void removeLockToken(String s) {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
//TODO: implement
}
@Override
public AccessControlManager getAccessControlManager() throws UnsupportedRepositoryOperationException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public RetentionManager getRetentionManager() throws UnsupportedRepositoryOperationException, RepositoryException {
throw new UnsupportedOperationException(MockNode.NOT_IMPLEMENTED);
}
@Override
public PrincipalManager getPrincipalManager() throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public UserManager getUserManager() throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}
| 32.972603 | 245 | 0.809929 |
94d8e8b04df93adc2557a9605d7829b5fbc8589e | 1,063 | package org.broadinstitute.dropseqrna.utils.editdistance;
import org.testng.annotations.Test;
import junit.framework.Assert;
public class BarcodeWithCountTest {
@SuppressWarnings("unlikely-arg-type")
@Test
public void testBarcodeWithCountTest() {
BarcodeWithCount b1 = new BarcodeWithCount("AAAA", 5);
BarcodeWithCount b2 = new BarcodeWithCount("AAAA", 2);
BarcodeWithCount b3 = new BarcodeWithCount("GGGG", 3);
BarcodeWithCount b4 = new BarcodeWithCount("GGGG", 7);
Assert.assertEquals("AAAA", b1.getBarcode());
Assert.assertSame(5, b1.getCount());
// equals uses barcode name and count.
Assert.assertTrue(b1.equals(b1));
Assert.assertFalse(b1.equals(b2));
Assert.assertFalse(b1.equals(b3));
// other dumb tests for coverage
Assert.assertFalse(b1.equals(null));
Assert.assertFalse(b1.equals(new String ("Foo")));
Assert.assertNotNull(b1.hashCode());
// compares by count alone.
BarcodeWithCount.CountComparator c = new BarcodeWithCount.CountComparator();
int r = c.compare(b1, b2);
Assert.assertTrue(r>0);
}
}
| 26.575 | 78 | 0.738476 |
c7e59cbb5523a7a5a8dfd68da813db9b69fdff7c | 8,978 | /* */ package edu.drexel.cis.dragon.ml.seqmodel.feature;
/* */
/* */ import edu.drexel.cis.dragon.ml.seqmodel.data.DataSequence;
/* */ import edu.drexel.cis.dragon.ml.seqmodel.data.Dataset;
/* */ import edu.drexel.cis.dragon.ml.seqmodel.model.ModelGraph;
/* */ import java.io.BufferedReader;
/* */ import java.io.FileOutputStream;
/* */ import java.io.FileReader;
/* */ import java.io.PrintWriter;
/* */ import java.util.Iterator;
/* */ import java.util.Vector;
/* */
/* */ public class BasicFeatureGenerator
/* */ implements FeatureGenerator
/* */ {
/* */ protected ModelGraph model;
/* */ protected Vector featureVector;
/* */ protected Iterator featureIter;
/* */ protected FeatureType currentFeatureType;
/* */ protected FeatureMap featureMap;
/* */ protected Feature featureToReturn;
/* */ protected DataSequence curSeq;
/* */ protected int curStartPos;
/* */ protected int curEndPos;
/* */ protected int totalFeatures;
/* */ protected boolean featureCollectingMode;
/* */ protected boolean supportSegment;
/* */
/* */ public BasicFeatureGenerator(ModelGraph model)
/* */ {
/* 42 */ this(model, false);
/* */ }
/* */
/* */ public BasicFeatureGenerator(ModelGraph model, boolean supportSegment) {
/* 46 */ this.model = model;
/* 47 */ this.totalFeatures = 0;
/* 48 */ this.supportSegment = supportSegment;
/* 49 */ this.featureVector = new Vector();
/* 50 */ this.featureToReturn = null;
/* 51 */ this.featureMap = new FeatureMap();
/* 52 */ this.featureCollectingMode = false;
/* */ }
/* */
/* */ public boolean supportSegment() {
/* 56 */ return this.supportSegment;
/* */ }
/* */
/* */ public boolean addFeatureType(FeatureType fType) {
/* 60 */ if (this.featureMap.isFrozen())
/* 61 */ return false;
/* 62 */ if ((supportSegment()) && (!fType.supportSegment())) {
/* 63 */ return false;
/* */ }
/* 65 */ fType.setTypeID(this.featureVector.size());
/* 66 */ this.featureVector.add(fType);
/* 67 */ return true;
/* */ }
/* */
/* */ public int getFeatureTypeNum() {
/* 71 */ return this.featureVector.size();
/* */ }
/* */
/* */ public FeatureType getFeatureTYpe(int index) {
/* 75 */ return (FeatureType)this.featureVector.get(index);
/* */ }
/* */
/* */ protected FeatureType getFeatureType(int i) {
/* 79 */ return (FeatureType)this.featureVector.elementAt(i);
/* */ }
/* */
/* */ public boolean train(Dataset trainData)
/* */ {
/* 87 */ for (int i = 0; i < this.featureVector.size(); i++) {
/* 88 */ FeatureType cur = getFeatureType(i);
/* 89 */ if (cur.needTraining()) {
/* 90 */ if (!cur.train(trainData))
/* 91 */ return false;
/* 92 */ cur.saveTrainingResult();
/* */ }
/* */ }
/* 95 */ collectFeatureIdentifiers(trainData);
/* 96 */ this.totalFeatures = this.featureMap.getFeatureNum();
/* 97 */ return true;
/* */ }
/* */
/* */ public boolean loadFeatureData()
/* */ {
/* 105 */ for (int i = 0; i < this.featureVector.size(); i++) {
/* 106 */ FeatureType cur = getFeatureType(i);
/* 107 */ if (cur.needTraining())
/* 108 */ cur.readTrainingResult();
/* */ }
/* 110 */ return true;
/* */ }
/* */
/* */ protected void collectFeatureIdentifiers(Dataset trainData)
/* */ {
DataSequence seq;
int segStart, segEnd;
featureCollectingMode = true;
for (trainData.startScan(); trainData.hasNext(); ) {
seq = trainData.next();
segStart=0;
while(segStart<seq.length()){
if(supportSegment)
segEnd=seq.getSegmentEnd(segStart);
else
segEnd=segStart;
for (startScanFeaturesAt(seq, segStart, segEnd); hasNext(); ) {
next();
}
segStart=segEnd+1;
}
}
featureCollectingMode = false;
featureMap.freezeFeatures();
/* */ }
/* */
/* */ protected void advance()
/* */ {
FeatureIdentifier id;
int featureIndex;
while (true) {
for (;((currentFeatureType == null) || !currentFeatureType.hasNext()) && featureIter.hasNext();) {
currentFeatureType = (FeatureType)featureIter.next();
}
if (!currentFeatureType.hasNext())
break;
while (currentFeatureType.hasNext()) {
featureToReturn=currentFeatureType.next();
id=featureToReturn.getID();
//gurantee feature id is unique as long as the id within the feature type is unique.
id.setId(id.getId()*getFeatureTypeNum()+currentFeatureType.getTypeID());
featureIndex=featureMap.getId(id);
if(featureIndex<0 && featureCollectingMode){
if(retainFeature(curSeq,featureToReturn))
featureIndex=featureMap.add(id);
}
if (featureIndex < 0){
featureToReturn=null;
continue;
}
featureToReturn.setIndex(featureIndex);
if(!isValidFeature(curSeq,curStartPos,curEndPos,featureToReturn)){
featureToReturn = null;
continue;
}
return;
}
}
featureToReturn=null;
/* */ }
/* */
/* */ protected boolean isValidFeature(DataSequence data, int curStartPos, int curEndPos, Feature featureToReturn) {
/* 174 */ if ((curStartPos > 0) && (curEndPos < data.length() - 1))
/* 175 */ return true;
/* 176 */ if ((curStartPos == 0) && (this.model.isStartState(featureToReturn.getLabel())) && (
/* 177 */ (data.length() > 1) || (this.model.isEndState(featureToReturn.getLabel()))))
/* 178 */ return true;
/* 179 */ if ((curEndPos == data.length() - 1) && (this.model.isEndState(featureToReturn.getLabel())))
/* 180 */ return true;
/* 181 */ return false;
/* */ }
/* */
/* */ protected boolean retainFeature(DataSequence seq, Feature f)
/* */ {
/* 186 */ return (seq.getLabel(this.curEndPos) == f.getLabel()) && (
/* 186 */ (this.curStartPos == 0) || (f.getPrevLabel() < 0) || (seq.getLabel(this.curStartPos - 1) == f.getPrevLabel()));
/* */ }
/* */
/* */ protected void initScanFeaturesAt(DataSequence d) {
/* 190 */ this.curSeq = d;
/* 191 */ this.currentFeatureType = null;
/* 192 */ this.featureIter = this.featureVector.iterator();
/* 193 */ advance();
/* */ }
/* */
/* */ public void startScanFeaturesAt(DataSequence d, int startPos, int endPos) {
/* 197 */ this.curStartPos = startPos;
/* 198 */ this.curEndPos = endPos;
/* 199 */ for (int i = 0; i < this.featureVector.size(); i++) {
/* 200 */ getFeatureType(i).startScanFeaturesAt(d, startPos, endPos);
/* */ }
/* 202 */ initScanFeaturesAt(d);
/* */ }
/* */
/* */ public boolean hasNext() {
/* 206 */ return this.featureToReturn != null;
/* */ }
/* */
/* */ public Feature next()
/* */ {
/* 212 */ Feature cur = this.featureToReturn.copy();
/* 213 */ advance();
/* 214 */ return cur;
/* */ }
/* */
/* */ public int getFeatureNum() {
/* 218 */ return this.totalFeatures;
/* */ }
/* */
/* */ public String getFeatureName(int featureIndex) {
/* 222 */ return this.featureMap.getName(featureIndex);
/* */ }
/* */
/* */ public boolean readFeatures(String fileName)
/* */ {
/* */ try
/* */ {
/* 230 */ BufferedReader in = new BufferedReader(new FileReader(fileName));
/* 231 */ this.totalFeatures = this.featureMap.read(in);
/* 232 */ return true;
/* */ }
/* */ catch (Exception e) {
/* 235 */ e.printStackTrace();
/* 236 */ }return false;
/* */ }
/* */
/* */ public boolean saveFeatures(String fileName)
/* */ {
/* */ try
/* */ {
/* 245 */ PrintWriter out = new PrintWriter(new FileOutputStream(fileName));
/* 246 */ this.featureMap.write(out);
/* 247 */ out.close();
/* 248 */ return true;
/* */ }
/* */ catch (Exception e) {
/* 251 */ e.printStackTrace();
/* 252 */ }return false;
/* */ }
/* */ }
/* Location: C:\dragontoolikt\dragontool.jar
* Qualified Name: dragon.ml.seqmodel.feature.BasicFeatureGenerator
* JD-Core Version: 0.6.2
*/ | 37.253112 | 128 | 0.523168 |
cc469ad29a6c1950100617fd8f0d08727b9b4099 | 503 | package com.sleepy.jpql;
import lombok.Data;
import java.util.List;
/**
* jpql返回结果类
*
* @author gehoubao
* @create 2020-02-27 23:34
**/
@Data
public class JpqlResultSet<T> {
private List<T> resultList;
private T result;
private long total;
public JpqlResultSet(List<T> resultList, long total) {
this.resultList = resultList;
this.total = total;
}
public JpqlResultSet(T result) {
this.result = result;
}
public JpqlResultSet() {
}
} | 16.766667 | 58 | 0.632207 |
8fd689b459a0ccf1178ee5266ca45668b1c3969e | 885 | package com.dianwoda.test.bassy.common.domain.dto.testcase;
import lombok.Data;
import java.util.Date;
/**
* @author zcp
* @date 2019/5/28 17:34
*/
@Data
public class ImportCaseInfoDTO {
/**
* 用例id
*/
private Integer id;
/**
* 所属产品
*/
private String product;
/**
* 所属模块
*/
private String module;
/**
* 测试用例标题
*/
private String title;
/**
* 测试用例类型
*/
private String type;
/**
* 测试用例优先级
*/
private Byte pri;
/**
* 测试用例前置条件
*/
private String precondition;
/**
* 测试用例步骤
*/
private String step;
/**
* 标签
*/
private String label;
/**
* 最后修改人
*/
private String lastEditedBy;
/**
* 最后修改时间
*/
private Date lastEditedDate;
/**
* 用例版本
*/
private Byte version;
}
| 11.959459 | 59 | 0.490395 |
cc2646f1d028d83cd12907666c95c3273c6ebc71 | 147 | package no.nels.tsd;
public final class TsdException extends Exception{
public TsdException(String message) {
super(message);
}
}
| 18.375 | 50 | 0.70068 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.