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
413222d981405c34c8cecd49f94e9822d6a174c6
10,982
package com.senior.cyber.tv.web.pages.show; import com.senior.cyber.frmk.common.base.WicketFactory; import com.senior.cyber.frmk.common.wicket.extensions.markup.html.repeater.data.table.filter.convertor.LongConvertor; import com.senior.cyber.frmk.common.wicket.extensions.markup.html.repeater.data.table.filter.convertor.StringConvertor; import com.senior.cyber.frmk.common.wicket.extensions.markup.html.tabs.ContentPanel; import com.senior.cyber.frmk.common.wicket.extensions.markup.html.tabs.Tab; import com.senior.cyber.frmk.common.wicket.layout.*; import com.senior.cyber.frmk.common.wicket.markup.html.form.DateTextField; import com.senior.cyber.frmk.common.wicket.markup.html.form.TimeTextField; import com.senior.cyber.frmk.common.wicket.markup.html.form.select2.Option; import com.senior.cyber.frmk.common.wicket.markup.html.form.select2.Select2SingleChoice; import com.senior.cyber.frmk.common.wicket.markup.html.panel.ContainerFeedbackBehavior; import com.senior.cyber.tv.dao.entity.Channel; import com.senior.cyber.tv.dao.entity.Show; import com.senior.cyber.tv.web.data.SingleChoiceProvider; import com.senior.cyber.tv.web.pages.DashboardPage; import com.senior.cyber.tv.web.repository.ChannelRepository; import com.senior.cyber.tv.web.repository.ShowRepository; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.wicket.MarkupContainer; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.extensions.markup.html.tabs.TabbedPanel; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.validation.validator.RangeValidator; import org.springframework.context.ApplicationContext; import java.util.Date; import java.util.Map; import java.util.Optional; public class ShowModifyPageInfoTab extends ContentPanel { protected long uuid; protected Form<Void> form; protected UIRow row1; protected UIColumn name_column; protected UIContainer name_container; protected TextField<String> name_field; protected String name_value; protected UIRow row2; protected UIColumn channel_column; protected UIContainer channel_container; protected Select2SingleChoice channel_field; protected SingleChoiceProvider<Long, String> channel_provider; protected Option channel_value; protected UIColumn schedule_column; protected UIContainer schedule_container; protected DateTextField schedule_field; protected Date schedule_value; protected UIRow row3; protected UIColumn start_at_column; protected UIContainer start_at_container; protected TimeTextField start_at_field; protected Date start_at_value; protected UIColumn duration_column; protected UIContainer duration_container; protected TextField<Integer> duration_field; protected Integer duration_value; protected Button saveButton; protected Button saveNewButton; protected Button deleteButton; protected BookmarkablePageLink<Void> cancelButton; public ShowModifyPageInfoTab(String id, String name, TabbedPanel<Tab> containerPanel, Map<String, Object> data) { super(id, name, containerPanel, data); } @Override protected void onInitData() { this.channel_provider = new SingleChoiceProvider<>(Long.class, new LongConvertor(), String.class, new StringConvertor(), "tbl_channel", "channel_id", "name"); PageParameters parameters = getPage().getPageParameters(); this.uuid = parameters.get("uuid").toLong(); ApplicationContext context = WicketFactory.getApplicationContext(); ShowRepository showRepository = context.getBean(ShowRepository.class); Optional<Show> optionalShow = showRepository.findById(this.uuid); Show show = optionalShow.orElseThrow(() -> new WicketRuntimeException("show is not found")); this.schedule_value = show.getSchedule(); this.start_at_value = show.getStartAt(); this.duration_value = show.getDuration(); this.name_value = show.getName(); this.channel_value = new Option(String.valueOf(show.getChannel().getId()), show.getChannel().getName()); } @Override protected void onInitHtml(MarkupContainer body) { this.form = new Form<>("form"); body.add(this.form); this.row1 = UIRow.newUIRow("row1", this.form); this.name_column = this.row1.newUIColumn("name_column", Size.Twelve_12); this.name_container = this.name_column.newUIContainer("name_container"); this.name_field = new TextField<>("name_field", new PropertyModel<>(this, "name_value")); this.name_field.setLabel(Model.of("Name")); this.name_field.add(new ContainerFeedbackBehavior()); this.name_field.setRequired(true); this.name_container.add(this.name_field); this.name_container.newFeedback("name_feedback", this.name_field); this.row1.lastUIColumn("last_column"); this.row2 = UIRow.newUIRow("row2", this.form); this.channel_column = this.row2.newUIColumn("channel_column", Size.Six_6); this.channel_container = this.channel_column.newUIContainer("channel_container"); this.channel_field = new Select2SingleChoice("channel_field", new PropertyModel<>(this, "channel_value"), this.channel_provider); this.channel_field.setLabel(Model.of("Channel")); this.channel_field.add(new ContainerFeedbackBehavior()); this.channel_field.setRequired(true); this.channel_container.add(this.channel_field); this.channel_container.newFeedback("channel_feedback", this.channel_field); this.schedule_column = this.row2.newUIColumn("schedule_column", Size.Six_6); this.schedule_container = this.schedule_column.newUIContainer("schedule_container"); this.schedule_field = new DateTextField("schedule_field", new PropertyModel<>(this, "schedule_value")); this.schedule_field.setLabel(Model.of("Schedule")); this.schedule_field.add(new ContainerFeedbackBehavior()); this.schedule_field.setRequired(true); this.schedule_container.add(this.schedule_field); this.schedule_container.newFeedback("schedule_feedback", this.schedule_field); this.row2.lastUIColumn("last_column"); this.row3 = UIRow.newUIRow("row3", this.form); this.start_at_column = this.row3.newUIColumn("start_at_column", Size.Six_6); this.start_at_container = this.start_at_column.newUIContainer("start_at_container"); this.start_at_field = new TimeTextField("start_at_field", new PropertyModel<>(this, "start_at_value")); this.start_at_field.setLabel(Model.of("Start At")); this.start_at_field.add(new ContainerFeedbackBehavior()); this.start_at_field.setRequired(true); this.start_at_container.add(this.start_at_field); this.start_at_container.newFeedback("start_at_feedback", this.start_at_field); this.duration_column = this.row3.newUIColumn("duration_column", Size.Six_6); this.duration_container = this.duration_column.newUIContainer("duration_container"); this.duration_field = new TextField<>("duration_field", new PropertyModel<>(this, "duration_value")); this.duration_field.setLabel(Model.of("Duration")); this.duration_field.add(RangeValidator.range(0, 240)); this.duration_field.add(new ContainerFeedbackBehavior()); this.duration_field.setRequired(true); this.duration_container.add(this.duration_field); this.duration_container.newFeedback("duration_feedback", this.duration_field); this.row3.lastUIColumn("last_column"); this.saveButton = new Button("saveButton") { @Override public void onSubmit() { saveButtonClick(); } }; this.form.add(this.saveButton); this.saveNewButton = new Button("saveNewButton") { @Override public void onSubmit() { saveNewButtonClick(); } }; this.form.add(this.saveNewButton); this.deleteButton = new Button("deleteButton") { @Override public void onSubmit() { deleteButtonClick(); } }; this.form.add(this.deleteButton); this.cancelButton = new BookmarkablePageLink<>("cancelButton", DashboardPage.class); this.form.add(this.cancelButton); } protected void saveNewButtonClick() { ApplicationContext context = WicketFactory.getApplicationContext(); ChannelRepository channelRepository = context.getBean(ChannelRepository.class); Optional<Channel> optionalChannel = channelRepository.findById(Long.valueOf(this.channel_value.getId())); Channel channel = optionalChannel.orElseThrow(() -> new WicketRuntimeException("channel is not found")); ShowRepository showRepository = context.getBean(ShowRepository.class); Show show = new Show(); show.setChannel(channel); show.setName(this.name_value); show.setSchedule(this.schedule_value); show.setStartAt(this.start_at_value); show.setDuration(this.duration_value); showRepository.save(show); ((MasterPage) getPage()).setMessage("Saved " + DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.format(new Date())); } protected void saveButtonClick() { ApplicationContext context = WicketFactory.getApplicationContext(); ChannelRepository channelRepository = context.getBean(ChannelRepository.class); Optional<Channel> optionalChannel = channelRepository.findById(Long.valueOf(this.channel_value.getId())); Channel channel = optionalChannel.orElseThrow(() -> new WicketRuntimeException("channel is not found")); ShowRepository showRepository = context.getBean(ShowRepository.class); Optional<Show> optionalShow = showRepository.findById(this.uuid); Show show = optionalShow.orElseThrow(() -> new WicketRuntimeException("show is not found")); show.setChannel(channel); show.setName(this.name_value); show.setSchedule(this.schedule_value); show.setStartAt(this.start_at_value); show.setDuration(this.duration_value); showRepository.save(show); setResponsePage(DashboardPage.class); } protected void deleteButtonClick() { ApplicationContext context = WicketFactory.getApplicationContext(); ShowRepository showRepository = context.getBean(ShowRepository.class); showRepository.deleteById(this.uuid); setResponsePage(DashboardPage.class); } }
44.461538
166
0.730923
8ac131d7195fca7515faa1387706f280982e4356
5,489
package cn.brody.financing.service.impl; import cn.brody.financing.mapper.FundBasicDao; import cn.brody.financing.mapper.FundPositionDao; import cn.brody.financing.mapper.FundTradeRecordDao; import cn.brody.financing.pojo.bo.AddOrUpdateFundBO; import cn.brody.financing.pojo.bo.DelFundBO; import cn.brody.financing.pojo.entity.FundBasicEntity; import cn.brody.financing.pojo.entity.FundPositionEntity; import cn.brody.financing.pojo.entity.FundTradeRecordEntity; import cn.brody.financing.pojo.vo.AnnualizedRateVO; import cn.brody.financing.service.FundBasicService; import cn.brody.financing.service.FundNetWorthService; import cn.brody.financing.support.financial.response.FundDetailResponse; import cn.brody.financing.support.financial.service.FinancialDataService; import cn.brody.financing.util.IrrUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.ObjectUtil; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.decampo.xirr.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @author chenyifu6 * @date 2021/10/26 */ @Slf4j @Service public class FundBasicServiceImpl implements FundBasicService { @Autowired private FinancialDataService financialDataService; @Autowired private FundBasicDao fundBasicDao; @Autowired private FundTradeRecordDao fundTradeRecordDao; @Autowired private FundPositionDao fundPositionDao; @Autowired private FundNetWorthService fundNetWorthService; @Override @Transactional(rollbackFor = Exception.class) public void addOrUpdateFund(AddOrUpdateFundBO addOrUpdateFundBO) { log.debug("开始添加或修改基金,基金代码={}", addOrUpdateFundBO.getCode()); FundDetailResponse fundDetailResponse = financialDataService. getFundDetail(addOrUpdateFundBO.getCode(), LocalDate.of(2020, 8, 31), null); FundBasicEntity fundBasicEntity = fundBasicDao.getByCode(addOrUpdateFundBO.getCode()); if (ObjectUtil.isNull(fundBasicEntity)) { fundBasicEntity = new FundBasicEntity(); fundBasicEntity.setName(fundDetailResponse.getName()); fundBasicEntity.setType(fundDetailResponse.getType()); fundBasicEntity.setCode(fundDetailResponse.getCode()); } fundBasicEntity.setBuyRate(fundDetailResponse.getBuyRate()); fundBasicEntity.setManager(fundDetailResponse.getManager()); fundBasicEntity.setFundScale(fundDetailResponse.getFundScale()); if (fundBasicDao.saveOrUpdate(fundBasicEntity)) { fundNetWorthService.addFundNetWorth(fundDetailResponse); log.debug("添加或修改基金成功,基金代码={}", fundBasicEntity); } } @Override @Transactional(rollbackFor = Exception.class) public void delFund(DelFundBO delFundBO) { log.debug("开始删除基金,基金代码={}", delFundBO.getCode()); FundBasicEntity fundBasicEntity = fundBasicDao.getByCode(delFundBO.getCode()); if (ObjectUtil.isNull(fundBasicEntity)) { log.error("基金不存在,删除失败,{}", delFundBO.getCode()); throw new NullPointerException("基金不存在,删除失败"); } if (fundBasicDao.removeById(fundBasicEntity)) { log.info("删除基金成功"); } fundNetWorthService.delFundNetWorth(delFundBO.getCode()); log.debug("结束删除基金,基金代码={}", delFundBO.getCode()); } @Override public List<AnnualizedRateVO> calculateAnnualizedRate() { List<FundBasicEntity> fundBasicEntityList = fundBasicDao.list(); if (CollectionUtil.isEmpty(fundBasicEntityList)) { return new ArrayList<>(); } List<AnnualizedRateVO> result = new ArrayList<>(); List<FundPositionEntity> positionEntityList = new ArrayList<>(); fundBasicEntityList.forEach(fundBasicEntity -> { // 查询所有的交易记录 List<FundTradeRecordEntity> fundTradeRecordEntityList = fundTradeRecordDao.listByFundCode(fundBasicEntity.getCode()); if (CollectionUtil.isEmpty(fundTradeRecordEntityList)) { return; } FundPositionEntity fundPositionEntity = fundPositionDao.getByFundCode(fundBasicEntity.getCode()); List<Transaction> transactionList = fundTradeRecordEntityList.stream().map(trade -> new Transaction(trade.getAmount(), trade.getConfirmDate())).collect(Collectors.toList()); if (BigDecimal.valueOf(fundPositionEntity.getPresentValue()).compareTo(BigDecimal.ZERO) != 0) { transactionList.add(new Transaction(fundPositionEntity.getPresentValue(), fundPositionEntity.getLastDate())); } log.info("开始计算收益率,{}", JSONObject.toJSONString(transactionList)); BigDecimal annualizedRate = BigDecimal.valueOf(IrrUtil.xirr(transactionList) * 100).setScale(2, RoundingMode.HALF_UP); fundPositionEntity.setAnnualizedRate(annualizedRate.doubleValue()); positionEntityList.add(fundPositionEntity); result.add(new AnnualizedRateVO(fundBasicEntity.getCode(), annualizedRate + "%", fundBasicEntity.getName())); }); fundPositionDao.saveOrUpdateBatch(positionEntityList); return result; } }
46.516949
185
0.73292
d3073bbe38f18c507863e927ec00cb8b332217dc
1,518
package bi.know.kettle.neo4j.steps.output; import bi.know.kettle.neo4j.core.GraphUsage; import bi.know.kettle.neo4j.model.GraphPropertyType; import bi.know.kettle.neo4j.shared.NeoConnection; import bi.know.kettle.neo4j.steps.BaseNeoStepData; import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.Transaction; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.metastore.api.IMetaStore; import java.util.List; import java.util.Map; import java.util.Set; public class Neo4JOutputData extends BaseNeoStepData implements StepDataInterface { public RowMetaInterface outputRowMeta; public String[] fieldNames; public NeoConnection neoConnection; public String url; public Driver driver; public Session session; public Transaction transaction; public long batchSize; public long outputCount; public int[] fromNodePropIndexes; public int[] fromNodeLabelIndexes; public int[] toNodePropIndexes; public int[] toNodeLabelIndexes; public int[] relPropIndexes; public int relationshipIndex; public GraphPropertyType[] fromNodePropTypes; public GraphPropertyType[] toNodePropTypes; public GraphPropertyType[] relPropTypes; public List<Map<String, Object>> fromUnwindList; public String fromLabelsClause; public List<Map<String, Object>> toUnwindList; public String toLabelsClause; public List<Map<String, Object>> relUnwindList; public IMetaStore metaStore; }
29.192308
83
0.801713
5f84196a10621b8328b0da7b65161552db5e63b8
455
package org.cnt.ts.beanannotation; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) @Target(TYPE) /** * @author lixinjie * @since 2019-08-02 */ public @interface Ann1 { String name() default "ann1"; String value() default "ann1"; String abc() default "abc"; }
19.782609
60
0.70989
74a5ae1363b4ca8f5c9e9da0b19c1bf250ff773d
2,064
/** * Yobi, Project Hosting SW * * Copyright 2013 NAVER Corp. * http://yobi.io * * @Author Keesun Baik * * 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 models; import play.db.ebean.Model; import javax.persistence.*; import java.util.Date; import java.util.List; /** * 프로젝트 방문 기록. * * @author Keeun Baik */ @Entity public class ProjectVisitation extends Model { private static final long serialVersionUID = 1L; public static final Finder <Long, ProjectVisitation> find = new Finder<>(Long.class, ProjectVisitation.class); @Id public Long id; @ManyToOne public Project project; @ManyToOne @JoinColumn(name = "recently_visited_projects_id") public RecentlyVisitedProjects recentlyVisitedProjects; @Temporal(TemporalType.TIMESTAMP) public Date visited; public static ProjectVisitation findBy(RecentlyVisitedProjects rvp, Project project) { return find.where() .eq("recentlyVisitedProjects", rvp) .eq("project", project) .findUnique(); } public static List<ProjectVisitation> findRecentlyVisitedProjects(RecentlyVisitedProjects rvp, int size) { return find.where() .eq("recentlyVisitedProjects", rvp) .orderBy("visited desc") .setMaxRows(size) .findList(); } public static List<ProjectVisitation> findByProject(Project project) { return find.where() .eq("project", project) .findList(); } }
27.157895
114
0.671027
2d45cc027761e102f4a49600c10935840f16489e
2,305
/** * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.testcase.factories; import org.evosuite.Properties; import org.evosuite.ga.ChromosomeFactory; import org.evosuite.testcase.DefaultTestCase; import org.evosuite.testcase.TestCase; import org.evosuite.testcase.TestChromosome; import org.evosuite.testcase.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FixedLengthTestChromosomeFactory implements ChromosomeFactory<TestChromosome> { private static final long serialVersionUID = -3860201346772188495L; /** Constant <code>logger</code> */ protected static final Logger logger = LoggerFactory.getLogger(FixedLengthTestChromosomeFactory.class); /** * Constructor */ public FixedLengthTestChromosomeFactory() { } /** * Create a random individual * * @param size */ private TestCase getRandomTestCase(int size) { TestCase test = new DefaultTestCase(); int num = 0; TestFactory testFactory = TestFactory.getInstance(); // Then add random stuff while (test.size() < size && num < Properties.MAX_ATTEMPTS) { testFactory.insertRandomStatement(test, test.size() - 1); num++; } //logger.debug("Randomized test case:" + test.toCode()); return test; } /** * {@inheritDoc} * * Generate a random chromosome */ @Override public TestChromosome getChromosome() { TestChromosome c = new TestChromosome(); c.setTestCase(getRandomTestCase(Properties.CHROMOSOME_LENGTH)); return c; } }
29.551282
105
0.718004
d855db168c953c25067ae7f2409781fca39a6235
6,287
/* * Copyright (c) 2010-2014. Axon Framework * * 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.axonframework.saga.repository.mongo; import com.mongodb.BasicDBObject; import com.mongodb.DBCursor; import com.mongodb.DBObject; import org.axonframework.common.Assert; import org.axonframework.saga.AssociationValue; import org.axonframework.saga.ResourceInjector; import org.axonframework.saga.Saga; import org.axonframework.saga.repository.AbstractSagaRepository; import org.axonframework.serializer.JavaSerializer; import org.axonframework.serializer.Serializer; import java.util.Set; import java.util.TreeSet; /** * Implementations of the SagaRepository that stores Sagas and their associations in a Mongo Database. Each Saga and * its associations is stored as a single document. * * @author Jettro Coenradie * @author Allard Buijze * @since 2.0 */ public class MongoSagaRepository extends AbstractSagaRepository { private final MongoTemplate mongoTemplate; private Serializer serializer; private ResourceInjector injector; /** * Initializes the Repository, using given <code>mongoTemplate</code> to access the collections containing the * stored Saga instances. * * @param mongoTemplate the template providing access to the collections */ public MongoSagaRepository(MongoTemplate mongoTemplate) { Assert.notNull(mongoTemplate, "mongoTemplate may not be null"); this.mongoTemplate = mongoTemplate; this.serializer = new JavaSerializer(); } @Override public Saga load(String sagaIdentifier) { DBObject dbSaga = mongoTemplate.sagaCollection().findOne(SagaEntry.queryByIdentifier(sagaIdentifier)); if (dbSaga == null) { return null; } SagaEntry sagaEntry = new SagaEntry(dbSaga); Saga loadedSaga = sagaEntry.getSaga(serializer); if (injector != null) { injector.injectResources(loadedSaga); } return loadedSaga; } @Override protected Set<String> findAssociatedSagaIdentifiers(Class<? extends Saga> type, AssociationValue associationValue) { final BasicDBObject value = associationValueQuery(type, associationValue); DBCursor dbCursor = mongoTemplate.sagaCollection().find(value, new BasicDBObject("sagaIdentifier", 1)); Set<String> found = new TreeSet<>(); while (dbCursor.hasNext()) { found.add((String) dbCursor.next().get("sagaIdentifier")); } return found; } private BasicDBObject associationValueQuery(Class<? extends Saga> type, AssociationValue associationValue) { final BasicDBObject value = new BasicDBObject(); value.put("sagaType", typeOf(type)); final BasicDBObject dbAssociation = new BasicDBObject(); dbAssociation.put("key", associationValue.getKey()); dbAssociation.put("value", associationValue.getValue()); value.put("associations", dbAssociation); return value; } @Override protected String typeOf(Class<? extends Saga> sagaClass) { return serializer.typeForClass(sagaClass).getName(); } @Override protected void deleteSaga(Saga saga) { mongoTemplate.sagaCollection().findAndRemove(SagaEntry.queryByIdentifier(saga.getSagaIdentifier())); } @Override protected void updateSaga(Saga saga) { SagaEntry sagaEntry = new SagaEntry(saga, serializer); mongoTemplate.sagaCollection().findAndModify( SagaEntry.queryByIdentifier(saga.getSagaIdentifier()), sagaEntry.asDBObject()); } @Override protected void storeSaga(Saga saga) { SagaEntry sagaEntry = new SagaEntry(saga, serializer); DBObject sagaObject = sagaEntry.asDBObject(); mongoTemplate.sagaCollection().save(sagaObject); } @Override protected void storeAssociationValue(AssociationValue associationValue, String sagaType, String sagaIdentifier) { mongoTemplate.sagaCollection().update( new BasicDBObject("sagaIdentifier", sagaIdentifier).append("sagaType", sagaType), new BasicDBObject("$push", new BasicDBObject("associations", new BasicDBObject("key", associationValue.getKey()) .append("value", associationValue.getValue())))); } @Override protected void removeAssociationValue(AssociationValue associationValue, String sagaType, String sagaIdentifier) { mongoTemplate.sagaCollection().update( new BasicDBObject("sagaIdentifier", sagaIdentifier).append("sagaType", sagaType), new BasicDBObject("$pull", new BasicDBObject("associations", new BasicDBObject("key", associationValue.getKey()) .append("value", associationValue.getValue())))); } /** * Provide the serializer to use if the default JavaSagaSerializer is not the best solution. * * @param serializer SagaSerializer to use for sag serialization. */ public void setSerializer(Serializer serializer) { this.serializer = serializer; } /** * Sets the ResourceInjector to use to inject Saga instances with any (temporary) resources they might need. These * are typically the resources that could not be persisted with the Saga. * * @param resourceInjector The resource injector */ public void setResourceInjector(ResourceInjector resourceInjector) { this.injector = resourceInjector; } }
39.049689
120
0.676793
30c0be319e69b3b1ea8ff702d26039f26125cd0a
6,975
package com.josephvarghese.piggame; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import java.util.Random; public class Home extends AppCompatActivity { Button roll,hold,newGame; TextView tagOne,tagTwo,totalOne,totalTwo,currentOne,currentTwo,winnerOne,winnerTwo; ImageView dice; MaterialDialog.Builder back; MaterialDialog backDialog; int user = 1; int current1 = 0,current2 = 0,total1 = 0,total2 = 0; int val; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); roll = (Button) findViewById(R.id.roll); hold = (Button) findViewById(R.id.hold); newGame = (Button)findViewById(R.id.newGame); tagOne = (TextView) findViewById(R.id.tagOne); tagTwo = (TextView) findViewById(R.id.tagTwo); totalOne = (TextView) findViewById(R.id.totalOne); totalTwo = (TextView) findViewById(R.id.totalTwo); currentOne = (TextView) findViewById(R.id.currentOne); currentTwo = (TextView) findViewById(R.id.currentTwo); winnerOne = (TextView)findViewById(R.id.winnerOne); winnerTwo = (TextView)findViewById(R.id.winnerTwo); dice = (ImageView)findViewById(R.id.dice); tagOne.setTextColor(getResources().getColor(R.color.colorAccent)); tagTwo.setTextColor(getResources().getColor(R.color.Grey)); winnerOne.setVisibility(View.INVISIBLE); winnerTwo.setVisibility(View.INVISIBLE); newGame.setVisibility(View.INVISIBLE); newGame.setClickable(false); displayScore(); back = new MaterialDialog.Builder(Home.this) .title("Exit") .content("Are you sure you want to exit?") .cancelable(false) .positiveText("Yes") .negativeText("No") .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { backDialog.dismiss(); finish(); // } }).onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { //backDialog.dismiss(); } }); backDialog = back.build(); final Random random = new Random(); roll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { val = random.nextInt(6) + 1; Log.d("Random Number ",Integer.toString(val)); //or do 1 + (int) (Math.random() * max) if(val == 1){ dice.setImageResource(getImageId(getApplicationContext(),"dice" + Integer.toString(val))); switchUser(); }else { dice.setImageResource(getImageId(getApplicationContext(),"dice" + Integer.toString(val))); addCurrent(val); } displayScore(); } }); hold.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { holdTotal(); checkWinner(); switchUser(); displayScore(); } }); newGame.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startNewGame(); } }); } public int getImageId(Context context,String imageName){ return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName()); } public void addCurrent(int val){ if(user == 1){ current1 += val; }else { current2 += val; } } public void holdTotal(){ if(user == 1){ total1 += current1; }else { total2 += current2; } } @SuppressLint("ResourceAsColor") public void switchUser(){ //needs to set the focusing part if(user == 1){ tagTwo.setTextColor(getResources().getColor(R.color.colorAccent)); tagOne.setTextColor(getResources().getColor(R.color.Grey)); current1 = 0; user = 2; }else{ tagOne.setTextColor(getResources().getColor(R.color.colorAccent)); tagTwo.setTextColor(getResources().getColor(R.color.Grey)); current2 = 0; user = 1; } } public void displayScore(){ currentOne.setText(Integer.toString(current1)); currentTwo.setText(Integer.toString(current2)); totalOne.setText(Integer.toString(total1)); totalTwo.setText(Integer.toString(total2)); } public void checkWinner(){ if(user == 1){ if(total1 >= 50){ winnerOne.setVisibility(View.VISIBLE); disablePlay(); } }else{ if(total2 >= 50){ winnerTwo.setVisibility(View.VISIBLE); disablePlay(); } } } public void startNewGame(){ dice.setImageResource(R.drawable.dice_show_first); newGame.setVisibility(View.INVISIBLE); newGame.setClickable(false); winnerOne.setVisibility(View.INVISIBLE); winnerTwo.setVisibility(View.INVISIBLE); total1 = total2 = current1 = current2 = 0; displayScore(); user = 1; tagOne.setTextColor(getResources().getColor(R.color.colorAccent)); tagTwo.setTextColor(getResources().getColor(R.color.Grey)); enablePlay(); } public void disablePlay(){ roll.setClickable(false); roll.setVisibility(View.INVISIBLE); hold.setClickable(false); hold.setVisibility(View.INVISIBLE); newGame.setVisibility(View.VISIBLE); newGame.setClickable(true); } public void enablePlay(){ roll.setClickable(true); roll.setVisibility(View.VISIBLE); hold.setClickable(true); hold.setVisibility(View.VISIBLE); } @Override public void onBackPressed() { backDialog.show(); } }
25.089928
110
0.578208
ea9db52f0a03af1761849407a34c142fc98d689f
8,521
package com.armedarms.idealmedia.fragments; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.armedarms.idealmedia.NavigationActivity; import com.armedarms.idealmedia.R; import com.armedarms.idealmedia.dialogs.DialogSelectDirectory; import com.armedarms.idealmedia.utils.ResUtils; public class SettingsDrawerFragment extends Fragment implements View.OnClickListener { private OnSettingsInteractionListener mListener; private TextView textPurchasePremium; private TextView textMediaPath; private TextView textMediaMethod; private View viewMediaPathPref; public SettingsDrawerFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_settings_drawer, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); viewMediaPathPref = view.findViewById(R.id.preference_media_path); view.setOnClickListener(this); view.findViewById(R.id.preference_purchase_premium).setOnClickListener(this); view.findViewById(R.id.preference_media_method).setOnClickListener(this); view.findViewById(R.id.preference_equalizer).setOnClickListener(this); String mediaPath = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(getString(R.string.key_mediapath), "/"); textMediaPath = view.findViewById(R.id.textMediaPath); textMediaPath.setText(mediaPath); boolean fullScan = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(getString(R.string.key_media_method_full), false); textMediaMethod = view.findViewById(R.id.textMediaMethod); textMediaMethod.setText(fullScan ? R.string.settings_media_method_full : R.string.settings_media_method_quick); viewMediaPathPref.setVisibility(fullScan ? View.VISIBLE : View.GONE); textPurchasePremium = view.findViewById(R.id.textPurchasePremium); int themeIndex = PreferenceManager.getDefaultSharedPreferences(getActivity()).getInt(getString(R.string.key_theme), 0); final Spinner spinnerThemes = view.findViewById(R.id.theme_list); ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_spinner_item, getResources().getTextArray(R.array.themes_array)) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView text = view.findViewById(android.R.id.text1); text.setTextSize(getResources().getDimension(R.dimen.preference_text_size) / getResources().getDisplayMetrics().density); text.setTextColor(ResUtils.color(getActivity(), R.attr.colorPreferenceCellSubtext)); return view; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); int resId = ResUtils.resolve(getActivity(), R.attr.colorPreferences); if (resId != 0) view.setBackgroundResource(resId); else view.setBackgroundColor(ResUtils.color(getActivity(), R.attr.colorPreferences)); TextView text = view.findViewById(android.R.id.text1); text.setTextSize(getResources().getDimension(R.dimen.preference_text_size) / getResources().getDisplayMetrics().density); text.setTextColor(ResUtils.color(getActivity(), R.attr.colorPreferenceCellText)); return view; } }; adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerThemes.setAdapter(adapter); if (themeIndex < adapter.getCount()) spinnerThemes.setSelection(themeIndex, false); spinnerThemes.post(new Runnable() { public void run() { spinnerThemes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { switchTheme(i); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } }); } public void update() { NavigationActivity activity = (NavigationActivity)getActivity(); if (activity.hasPremiumPurchase()) { textPurchasePremium.setText(R.string.settings_premium_you_are_premium); } else { textPurchasePremium.setText(R.string.settings_premium); } } private void switchTheme(int themeIndex) { if (mListener != null) mListener.switchTheme(themeIndex); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnSettingsInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onClick(View view) { int id = view.getId(); if (id == R.id.preference_media_path) { selectMediaPath(); } if (id == R.id.preference_media_method) { toggleMediaMethod(); } if (id == R.id.preference_equalizer) { equalizer(); } if (id == R.id.preference_purchase_premium) { purchasePremium(); } } private void purchasePremium() { if (mListener != null) mListener.purchasePremium(); } private void toggleMediaMethod() { boolean fullScan = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(getString(R.string.key_media_method_full), false); fullScan = !fullScan; PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putBoolean(getString(R.string.key_media_method_full), fullScan).apply(); textMediaMethod.setText(fullScan ? R.string.settings_media_method_full : R.string.settings_media_method_quick); viewMediaPathPref.setVisibility(fullScan ? View.VISIBLE : View.GONE); if (mListener != null) mListener.onMediaMethodChanged(fullScan); } private void equalizer() { mListener.onEqualizerPreference(); } private void selectMediaPath() { String mediaPath = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(getString(R.string.key_mediapath), ""); if ("".equals(mediaPath)) mediaPath = "/"; new DialogSelectDirectory( getActivity(), getFragmentManager(), new DialogSelectDirectory.Result() { @Override public void onChooseDirectory(String dir) { PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putString(getString(R.string.key_mediapath), dir).apply(); textMediaPath.setText(dir); if (mListener != null) mListener.onMediaPathChanged(dir); } @Override public void onCancelChooseDirectory() { } }, mediaPath); } public interface OnSettingsInteractionListener { void onMediaPathChanged(String mediaPath); void onMediaMethodChanged(boolean isFullScan); void onEqualizerPreference(); void switchTheme(int themeIndex); void purchasePremium(); } }
40.193396
181
0.657787
807f0cd0f941374097212350e5a0484c0e29319b
1,904
package net.floodlightcontroller.odin.master; import java.net.InetAddress; import net.floodlightcontroller.util.MACAddress; import org.codehaus.jackson.map.annotate.JsonSerialize; @JsonSerialize(using=OdinClientSerializer.class) public class OdinClient implements Comparable { private final MACAddress hwAddress; private InetAddress ipAddress; private Lvap lvap; // NOTE: Will need to add security token and temporal keys here later. // So make sure to pass OdinClient through interfaces of other classes // as opposed to the 4-LVAP properties now. public OdinClient (MACAddress hwAddress, InetAddress ipAddress, Lvap lvap) { this.hwAddress = hwAddress; this.ipAddress = ipAddress; this.lvap = lvap; } /** * STA's MAC address. We assume one per client here. * (Implies, no support for FMC yet) :) * * @return client's MAC address */ public MACAddress getMacAddress() { return this.hwAddress; } /** * Get the clien'ts IP address. * @return */ public InetAddress getIpAddress() { return ipAddress; } /** * Set the client's IP address * @param addr */ public void setIpAddress(InetAddress addr) { this.ipAddress = addr; } /** * Get the client's lvap object * @return lvap */ public Lvap getLvap() { return lvap; } /** * Set the client's lvap */ public void setLvap() { this.lvap = lvap; } @Override public boolean equals(Object obj) { if (!(obj instanceof OdinClient)) return false; if (obj == this) return true; OdinClient that = (OdinClient) obj; return (this.hwAddress.equals(that.hwAddress)); } @Override public int compareTo(Object o) { assert (o instanceof OdinClient); if (this.hwAddress.toLong() == ((OdinClient)o).hwAddress.toLong()) return 0; if (this.hwAddress.toLong() > ((OdinClient)o).hwAddress.toLong()) return 1; return -1; } }
18.851485
77
0.683824
21203ac5630bfd82e623e8c118842224eda08c05
1,081
package similarity.linzijun.com.converter.domain; import java.util.Date; /** * Created by linzijun on */ public class User { private String uuid; private long id; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } private String type; private String nick; private String gender; private Date birthday; }
15.897059
49
0.574468
11f3ed31b6721e979100f890384f5afad0792868
3,756
package com.giang.topdf.activity; import static com.giang.topdf.utils.Constant.ACTIVITY_CREATE; import static com.giang.topdf.utils.Constant.IMAGE_LIST_URI; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.Button; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.giang.topdf.R; import com.giang.topdf.adapter.PreviewAdapter; import com.giang.topdf.utils.Constant; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; public class PreviewActivity extends AppCompatActivity { Button mSave, mEdit; private ArrayList<Uri> mListImages; private PreviewAdapter mPreviewAdapter; private RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_preview); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(R.string.preview_images); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } mSave = findViewById(R.id.save_btn); mEdit = findViewById(R.id.edit_btn); mListImages = getIntent().getParcelableArrayListExtra(IMAGE_LIST_URI); Toast.makeText(this, mListImages.size() + getString(R.string.number_of_image_added), Toast.LENGTH_SHORT).show(); ActivityResultLauncher<Intent> mGetUriFromEditActivity = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Constant.RESULT_EDIT && result.getData() != null) { mListImages = result.getData().getParcelableArrayListExtra(IMAGE_LIST_URI); mPreviewAdapter.setData(mListImages); recyclerView.setAdapter(mPreviewAdapter); } } ); initRecycleView(mListImages); mSave.setOnClickListener(v -> { Intent intent = new Intent(this, SaveActivity.class); intent.putParcelableArrayListExtra(IMAGE_LIST_URI, mListImages); String mFileNameCurrentDateTime = getCurrentDateTime(); intent.putExtra(ACTIVITY_CREATE, true); intent.putExtra("fileName", mFileNameCurrentDateTime); startActivity(intent); }); mEdit.setOnClickListener(v -> { Intent intent = new Intent(this, EditActivity.class); intent.putParcelableArrayListExtra(IMAGE_LIST_URI, mListImages); mGetUriFromEditActivity.launch(intent); }); } @Override protected void onResume() { super.onResume(); mPreviewAdapter.notifyDataSetChanged(); } public boolean onSupportNavigateUp() { onBackPressed(); return true; } private void initRecycleView(ArrayList<Uri> mListImagesUri) { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(linearLayoutManager); mPreviewAdapter = new PreviewAdapter(this, mListImagesUri); recyclerView.setAdapter(mPreviewAdapter); } private String getCurrentDateTime() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()); return sdf.format(new Date()); } }
37.939394
120
0.703408
9202556a5205cd12d56605b3991529a1e25275c9
1,029
package com.github.marschall.memoryfilesystem; import java.nio.file.attribute.FileAttribute; final class StubFileAttribute<T> implements FileAttribute<T> { private final String name; private final T value; StubFileAttribute(String name, T value) { this.name = name; this.value = value; } @Override public String name() { return this.name; } @Override public T value() { return this.value; } @Override public String toString() { return this.name + ' ' + this.value; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StubFileAttribute)) { return false; } StubFileAttribute<?> other = (StubFileAttribute<?>) obj; return this.name.equals(other.name) && this.value.equals(other.value); } @Override public int hashCode() { int result = 17; result = 31 * result + this.name.hashCode(); result = 31 * result + this.value.hashCode(); return result; } }
19.788462
62
0.639456
ed4e7e4aa1f79e83ddb80021df8633da8203e744
1,528
package info.loenwind.autosave.handlers.endercore; import java.lang.reflect.Field; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.enderio.core.common.NBTAction; import com.enderio.core.common.fluid.SmartTank; import info.loenwind.autosave.Registry; import info.loenwind.autosave.exceptions.NoHandlerFoundException; import info.loenwind.autosave.handlers.IHandler; import net.minecraft.nbt.NBTTagCompound; public class HandleSmartTank implements IHandler<SmartTank> { public HandleSmartTank() { } @Override public boolean canHandle(Class<?> clazz) { return SmartTank.class.isAssignableFrom(clazz); } @Override public boolean store(@Nonnull Registry registry, @Nonnull Set<NBTAction> phase, @Nonnull NBTTagCompound nbt, @Nonnull String name, @Nonnull SmartTank object) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoHandlerFoundException { object.writeCommon(name, nbt); return true; } @Override public SmartTank read(@Nonnull Registry registry, @Nonnull Set<NBTAction> phase, @Nonnull NBTTagCompound nbt, @Nullable Field field, @Nonnull String name, @Nullable SmartTank object) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoHandlerFoundException { if (nbt.hasKey(name)) { if (object != null) { object.readCommon(name, nbt); } else { object = SmartTank.createFromNBT(name, nbt); } } return object; } }
31.833333
159
0.762435
4d2fcc30db490fbb145ef9cc61976062d27765d4
2,261
package org.eclipse.fx.drift.internal; import java.time.Duration; public class GPUSyncUtil { public static enum WaitSyncResult { AREADY_SIGNALED, TIMEOUT_EXPIRED, CONDITION_SATISFIED, WAIT_FAILED } public static interface GPUSync { public WaitSyncResult ClientWaitSync(Duration timeout); public void WaitSync(); public void Delete(); } public static class D3DSync implements GPUSync { // for now this is a noop @Override public WaitSyncResult ClientWaitSync(Duration timeout) { return WaitSyncResult.AREADY_SIGNALED; } @Override public void WaitSync() { } @Override public void Delete() { } } public static GPUSync createFence() { if (GraphicsPipelineUtil.isES2()) { return GLSync.CreateFence(); } else { return new D3DSync(); } } public static class GLSync implements GPUSync { private long sync; private GLSync() { sync = nCreateFence(); } private void checkSync() { if (sync == 0) { throw new RuntimeException("sync object was already deleted!"); } } public static GLSync CreateFence() { return new GLSync(); } public WaitSyncResult ClientWaitSync(Duration timeout) { checkSync(); int r = nClientWaitSync(sync, timeout.toNanos()); switch (r) { case GL_AREADY_SIGNALED: return WaitSyncResult.AREADY_SIGNALED; case GL_TIMEOUT_EXPIRED: return WaitSyncResult.TIMEOUT_EXPIRED; case GL_CONDITION_SATISFIED: return WaitSyncResult.CONDITION_SATISFIED; case GL_WAIT_FAILED: return WaitSyncResult.WAIT_FAILED; } System.err.println("glClientWaitSync: Unexpected result!!! " + r); return WaitSyncResult.WAIT_FAILED; } public void WaitSync() { checkSync(); nWaitSync(sync); } public void Delete() { checkSync(); nDeleteSync(sync); sync = 0; } } private static native long nCreateFence(); private static native void nDeleteSync(long sync); private static final int GL_AREADY_SIGNALED = 0x911A; private static final int GL_TIMEOUT_EXPIRED = 0x911B; private static final int GL_CONDITION_SATISFIED = 0x911C; private static final int GL_WAIT_FAILED = 0x911D; private static native int nClientWaitSync(long sync, long timeout); private static native void nWaitSync(long sync); }
22.61
74
0.721362
7deadffd2dd4574bb7fd5ff4d1934d6e4f6d4683
5,958
import java.util.Scanner; public class QuickSorter { public static void main(String[] args) { int[] a; if (args.length > 0) { a = parseIntArray(args); } else { Scanner in = new Scanner(System.in); System.out.println("Enter a comma-separated list of integers to sort, or type random:"); String line = in.nextLine(); if (line.trim().equalsIgnoreCase("random")) { a = new int[25]; for (int i = 0; i < a.length; i++) { a[i] = (int)(Math.random() * 100); } } else { a = parseIntArray(line.split(",")); } } System.out.println("You entered:"); writeArray(a); sort(a); System.out.println("The sorted array is: "); writeArray(a); System.out.println(); } private static int[] parseIntArray(String[] values) { int[] result = new int[values.length]; for (int i = 0; i < values.length; i++) { result[i] = Integer.parseInt(values[i].trim()); } return result; } public static void sort(int[] a) { sort(a, 0, a.length); } private static void sort(int[] a, int begin, int end) { int middle = partition(a, begin, end); // assertion: value at middle is in the right place, everything to it's left is smaller (or // equal), everything to its right is larger. int frontSize = middle - begin; if (frontSize > 4) { // usually we'd use a larger size, but if we still have more than 4 values to sort, recurse. sort(a, begin, middle); } else if (frontSize > 1) { insertionSort(a, begin, middle); // if we 2, 3, or 4 values, we'll use insertion sort to sort them. } int backSize = end - middle - 1; if (backSize > 4) { // usually we'd use a larger size, but if we still have more than 4 values to sort, recurse. sort(a, middle + 1, end); } else if (backSize > 1) { // if we 2, 3, or 4 values, we'll use insertion sort to sort them. insertionSort(a, middle + 1, end); } } private static int partition(int[] a, int begin, int end) { System.out.println("At the beginning of partition, our array is:"); writeArray(a, begin, end); // end is to the "right" of the last value in the array (i.e., end is array.length to start) int middle = (begin + end) / 2; System.out.println("Our begin is " + arrayValue(a, begin) + ", our middle is " + arrayValue(a, middle) + ", and our end is " + arrayValue(a, end - 1) + "."); System.out.println("Let's arrange our 3 values using median-of-three."); arrange(a, begin, middle, end - 1); // now we can be sure that a[begin] < a[middle] < a[end] System.out.println("After arranging begin, middle, and end our array is:"); writeArray(a, begin, end); int middleValue = a[middle]; System.out.println("Our middle value is " + arrayValue(a, middle) + ". " + "Swapping middle to near the end: "); swap(a, middle, end - 2); System.out.println("Now we move from the outsides in, and move values smaller than " + middleValue + " to the left side and larger values to the right side."); int leftSide = begin; // start at begin index int rightSide = end - 3; // start at left of "middle" value (remember, it's near the end now) while (leftSide <= rightSide) { // this advances leftSide until we find something that doesn't belong. while (leftSide <= rightSide && a[leftSide] <= middleValue) { leftSide++; } // this advances rightSide until we find something that doesn't belong. while (leftSide <= rightSide && a[rightSide] > middleValue) { rightSide--; } if (leftSide < rightSide) { // at this point, we know we have something on both sides that doesn't belong. swap them. swap(a, leftSide, rightSide); leftSide++; rightSide--; } } System.out.println("Last, we move the middle back:"); swap(a, leftSide, end - 2); System.out.println("The middle was put back at " + arrayValue(a, leftSide) + "; we know now it's in the right position."); System.out.println("(everything left) <= " + arrayValue(a, leftSide) + " < (everything right)"); System.out.println("After this call to partition, we have this array:"); writeArray(a, begin, end); System.out.println(); return leftSide; // remember, leftSide is where middle ends up. } private static void arrange(int[] a, int x, int y, int z) { int min = x; if (a[y] < a[min]) { min = y; } if (a[z] < a[min]) { min = z; } swap(a, x, min); int max = y; if (a[z] > a[max]) { max = z; } swap(a, z, max); } private static void swap(int[] a, int x, int y) { if (x != y) System.out.println("> swapping " + arrayValue(a, x) + " with " + arrayValue(a, y) + "."); int temp = a[x]; a[x] = a[y]; a[y] = temp; } private static void insertionSort(int[] a, int begin, int end) { System.out.println("Insertion sorting this array:"); writeArray(a, begin, end); for (int i = begin + 1; i < end; i++) { int k = i; while (k > begin && a[k] < a[k - 1]) { swap(a, k, k - 1); k--; } } System.out.println("to:"); writeArray(a, begin, end); System.out.println(); } private static void writeArray(int[] a) { writeArray(a, 0, a.length); } private static void writeArray(int[] a, int begin, int end) { System.out.print("| "); for (int i = 0; i < a.length; i++) { if (i < begin || i >= end) { System.out.print("x | "); } else { System.out.print(arrayValue(a, i) + " | "); } } System.out.println("\n"); } private static String arrayValue(int[] a, int index) { return "[" + index + "]" + a[index]; } }
32.380435
105
0.565962
2ff371623468b7f1e09108a54b38a43c7de06313
1,161
package edu.unah.poo.model; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="autor") public class Autor { @Id private int idAutor; private String nombre; private String direccion; @OneToMany(mappedBy="autor",fetch=FetchType.EAGER) private List<Libro> libro; public Autor() {} public Autor(int idAutor, String nombre, String direccion) { super(); this.idAutor = idAutor; this.nombre = nombre; this.direccion = direccion; } public Autor(int idAutor, String nombre) { super(); this.idAutor = idAutor; this.nombre = nombre; } public int getIdAutor() { return idAutor; } public void setIdAutor(int idAutor) { this.idAutor = idAutor; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } }
18.140625
62
0.679587
0f64b228839cc264f4ef8d2b54b8bce79d69e59a
2,104
package edu.study.ol.course.service.impl; import com.alibaba.dubbo.config.annotation.Service; import edu.study.ol.bean.EduCourse; import edu.study.ol.bean.SysFunction; import edu.study.ol.bean.SysSubject; import edu.study.ol.course.mapper.EduCourseMapper; import edu.study.ol.course.mapper.SysSubjectMapper; import edu.study.ol.service.CourseService; import org.springframework.beans.factory.annotation.Autowired; import tk.mybatis.mapper.common.Mapper; import java.util.*; @Service public class CourseServiceImpl implements CourseService { @Autowired private EduCourseMapper eduCourseMapper; @Autowired private SysSubjectMapper sysSubjectMapper; @Override public List<EduCourse> selectAllCourse() { List<EduCourse> courseList = eduCourseMapper.selectAll(); //封装为一个rootList return null; } @Override public List<SysSubject> selectAllSubject() { List<SysSubject> subjectsList = sysSubjectMapper.selectAll(); List<SysSubject> rootSubjectList = packageSubject(subjectsList); return rootSubjectList; } @Override public int updateSortById(SysSubject sysSubject) { int i = sysSubjectMapper.updateByPrimaryKeySelective(sysSubject); return i; } /** * 封装SysSubject为一个父对象的集合 * @param subjectsList * @return */ private List<SysSubject> packageSubject(List<SysSubject> subjectsList) { Collections.reverse(subjectsList); List<SysSubject> rootList = new ArrayList<>(); Map<Integer,SysSubject> allMap = new HashMap<>(); for (SysSubject subject : subjectsList) { allMap.put(subject.getSubjectId(),subject); } for (SysSubject sysSubject : subjectsList) { if (sysSubject.getParentId()==0){ rootList.add(sysSubject); }else { Integer parentId = sysSubject.getParentId(); SysSubject subjectParent = allMap.get(parentId); subjectParent.getChildList().add(sysSubject); } } return rootList; } }
30.492754
76
0.678232
68d1b7de6c30b0fac5961e59b36799460a1bce70
2,408
package com.android.appcore; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import java.util.Objects; /** * A simple {@link Fragment} subclass. */ public class AddFragment extends Fragment implements View.OnClickListener{ // private static AddFragment addFragment; private EditText todoInputEditText; private Button saveButton; private int position = -1; public AddFragment() { // Required empty public constructor } public static Fragment newInstance(Bundle bundle) { AddFragment addFragment = new AddFragment(); addFragment.setArguments(bundle); return addFragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_add, container, false); init(view); return view; } private void init(View view) { todoInputEditText = view.findViewById(R.id.todo_input_edit_text); saveButton = view.findViewById(R.id.save_button); saveButton.setOnClickListener(this); if(getArguments()!= null && getArguments().getSerializable(Todo.class.getSimpleName()) != null) { todoInputEditText.setText(((Todo)getArguments().getSerializable(Todo.class.getSimpleName())).getTodoName()); position = getArguments().getInt("position"); } else { todoInputEditText.setText(null); position = -1; } todoInputEditText.requestFocus(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.save_button: Bundle bundle = new Bundle(); Todo todo = new Todo(); todo.setTodoName(todoInputEditText.getText().toString()); bundle.putSerializable(Todo.class.getSimpleName(), todo); bundle.putInt("position", position); ListFragment.newInstance(bundle); getActivity().getSupportFragmentManager().popBackStack(); break; } } }
30.871795
120
0.650332
f5b4341b58564c9ee3f1113a65b6000b44343ace
8,483
/* * Copyright (c) 2015, Florent Hedin, Markus Meuwly, and the University of Basel * All rights reserved. * * The 3-clause BSD license is applied to this software. * see LICENSE.txt * */ package ch.unibas.charmmtools.generate.inputs; import ch.unibas.charmmtools.generate.CHARMM_InOut; import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; /** * * @author hedin */ public abstract class CHARMM_Input implements CHARMM_InOut { protected static final Logger logger = Logger.getLogger(CHARMM_Input.class); protected Writer writer = null; protected String title = ""; protected Date d = new Date(); /** * contains the acceptable types of coordinate files, by default only *.pdb (the extension may be *.ent but that's * the same type of file) */ protected final List<String> expectedFormats; /* * bomlev is the error level causing abortion of CHARMM * prnlev regulates the level of output from CHARMM * we set here those variable to 2 "decent" values */ protected int bomlev = 0; protected int prnlev = 2; protected String par = null, top = null, lpun = null, cor = null; // protected File inp; protected File out = null; protected String type = null; // protected CHARMM_Input(String _cor, String _top, String _par, String _type) // { // this.cor = _cor; // this.top = _top; // this.par = _par; // this.type = _type; // // this.expectedFormats = new ArrayList<>(); // this.expectedFormats.add("*.pdb"); // this.expectedFormats.add("*.ent"); // } public CHARMM_Input(String _cor, String _top, String _par, File _outf, String _type) { this.cor = _cor; this.top = _top; this.par = _par; this.out = _outf; this.type = _type; this.expectedFormats = new ArrayList<>(); this.expectedFormats.add("*.pdb"); this.expectedFormats.add("*.ent"); this.normalisePathAndCopyFiles(); } // protected CHARMM_Input(String _cor, String _top, String _par, String _lpun, String _type) // { // this.cor = _cor; // this.top = _top; // this.par = _par; // this.lpun = _lpun; // this.type = _type; // // this.expectedFormats = new ArrayList<>(); // this.expectedFormats.add("*.pdb"); // this.expectedFormats.add("*.ent"); // } protected CHARMM_Input(String _cor, String _top, String _par, String _lpun, File _outf, String _type) { this.cor = _cor; this.top = _top; this.par = _par; this.lpun = _lpun; this.out = _outf; this.type = _type; this.expectedFormats = new ArrayList<>(); this.expectedFormats.add("*.pdb"); this.expectedFormats.add("*.ent"); this.normalisePathAndCopyFiles(); } private void normalisePathAndCopyFiles() { File parentFile = out.getParentFile(); try { FileUtils.copyFileToDirectory(new File(cor), parentFile); FileUtils.copyFileToDirectory(new File(top), parentFile); FileUtils.copyFileToDirectory(new File(par), parentFile); if (lpun != null) { FileUtils.copyFileToDirectory(new File(lpun), parentFile); } } catch (IOException ex) { logger.error("Error while copying required files : " + ex); } cor = new File(cor).getName(); top = new File(top).getName(); par = new File(par).getName(); if (lpun != null) { lpun = new File(lpun).getName(); } } /** * Calls all the print_* sections for effectively creating an input file either in a String or directly to a file * depending on the constructor that was initially called * * @throws java.io.IOException */ protected abstract void build() throws IOException; /** * Creates the header part of charmm input file, i.e. containing a title and bomlev and prnlev parameters * * @throws IOException */ protected void print_title() throws IOException { this.title += "* CHARMM input file for " + cor + "\n"; this.title += "* generated on " + d.toString() + "\n"; this.title += "* by user " + System.getProperty("user.name") + " on machine " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version") + "\n"; this.title += "*\n"; //then print it writer.write(this.title + "\n"); //print error level and print level writer.write("bomlev " + this.bomlev + "\n"); writer.write("prnlev " + this.prnlev + "\n\n"); } /** * Creates the section where topology and parameter files are loaded * * @throws IOException */ protected void print_ioSection() throws IOException { //print commands for reading forcefield parameters and topology file writer.write("! read parameters and coordinates" + "\n"); writer.write("read rtf card name -" + "\n"); writer.write("\t" + top + "\n"); writer.write("read param card name -" + "\n"); writer.write("\t" + par + "\n\n"); } protected void print_corSection() throws IOException { writer.write("OPEN UNIT 10 CARD READ NAME -" + "\n"); writer.write("\t" + cor + "\n"); writer.write("READ SEQUENCE PDB UNIT 10" + "\n"); writer.write("GENERATE SOLU" + "\n"); writer.write("REWIND UNIT 10" + "\n"); writer.write("READ COOR PDB UNIT 10" + "\n"); writer.write("CLOSE UNIT 10" + "\n\n"); } protected void print_crystalSection() throws IOException { } /** * Creates the section where nonbonded parameters are defined Abstract because this may vary a lot between the * different types of simulations * * @throws IOException */ protected abstract void print_nbondsSection() throws IOException; protected void print_ShakeSection() throws IOException { writer.write("SHAKE BONH PARA SELE ALL END" + "\n\n"); } /** * Prints the part that calls the MTPL module Abstract because this may vary a lot between the different types of * simulations * * @throws IOException */ protected abstract void print_lpunfile() throws IOException; /** * Prints the part in charge of the minimisation procedure Abstract because this may vary a lot between the * different types of simulations * * @throws IOException */ protected abstract void print_MiniSection() throws IOException; /** * Prints the part in charge of the molecular dynamics procedure Abstract because this may vary a lot between the * different types of simulations * * @throws IOException */ protected abstract void print_DynaSection() throws IOException; protected void print_StopSection() throws IOException { writer.write("STOP" + "\n\n"); } /** * Returns a long String which is a CHARMM input file ready for use. * * @return The content of the built input file, for example for editing purposes */ @Override public String getText() { return writer.toString(); } /** * @return the par */ public String getPar() { return par; } /** * @return the top */ public String getTop() { return top; } /** * @return the lpun */ public String getLpun() { return lpun; } /** * @return the cor */ public String getCrd() { return cor; } /** * @return the out */ public File getOut() { return out; } /** * @return the inp */ // public File getInp() { // return inp; // } /** * @param inp the inp to set */ // public void setInp(File inp) { // this.inp = inp; // } // protected abstract void convertCoordinates(); /** * @return the type */ @Override public String getType() { return type; } @Override public String getWorkDir() { return out.getParent(); } }
28.56229
204
0.593068
f80f110d504b511b8f0b6e3962c985f2ca1be6b3
5,170
package net.floodlightcontroller.util; import java.util.Arrays; /** * The class representing MAC address. * * @author Sho Shimizu ([email protected]) */ public class MACAddress { public static final int MAC_ADDRESS_LENGTH = 6; private byte[] address = new byte[MAC_ADDRESS_LENGTH]; private MACAddress(byte[] address) { this.address = Arrays.copyOf(address, MAC_ADDRESS_LENGTH); } /** * Returns a MAC address instance representing the value of the specified {@code String}. * @param address the String representation of the MAC Address to be parsed. * @return a MAC Address instance representing the value of the specified {@code String}. * @throws IllegalArgumentException if the string cannot be parsed as a MAC address. */ public static MACAddress valueOf(String address) { String[] elements = address.split(":"); if (elements.length != MAC_ADDRESS_LENGTH) { throw new IllegalArgumentException( "Specified MAC Address must contain 12 hex digits" + " separated pairwise by :'s."); } byte[] addressInBytes = new byte[MAC_ADDRESS_LENGTH]; for (int i = 0; i < MAC_ADDRESS_LENGTH; i++) { String element = elements[i]; addressInBytes[i] = (byte)Integer.parseInt(element, 16); } return new MACAddress(addressInBytes); } /** * Returns a MAC address instance representing the specified {@code byte} array. * @param address the byte array to be parsed. * @return a MAC address instance representing the specified {@code byte} array. * @throws IllegalArgumentException if the byte array cannot be parsed as a MAC address. */ public static MACAddress valueOf(byte[] address) { if (address.length != MAC_ADDRESS_LENGTH) { throw new IllegalArgumentException("the length is not " + MAC_ADDRESS_LENGTH); } return new MACAddress(address); } /** * Returns a MAC address instance representing the specified {@code long} value. * The lower 48 bits of the long value are used to parse as a MAC address. * @param address the long value to be parsed. The lower 48 bits are used for a MAC address. * @return a MAC address instance representing the specified {@code long} value. * @throws IllegalArgumentException if the long value cannot be parsed as a MAC address. */ public static MACAddress valueOf(long address) { byte[] addressInBytes = new byte[] { (byte)((address >> 40) & 0xff), (byte)((address >> 32) & 0xff), (byte)((address >> 24) & 0xff), (byte)((address >> 16) & 0xff), (byte)((address >> 8 ) & 0xff), (byte)((address >> 0) & 0xff) }; return new MACAddress(addressInBytes); } /** * Returns the length of the {@code MACAddress}. * @return the length of the {@code MACAddress}. */ public int length() { return address.length; } /** * Returns the value of the {@code MACAddress} as a {@code byte} array. * @return the numeric value represented by this object after conversion to type {@code byte} array. */ public byte[] toBytes() { return Arrays.copyOf(address, address.length); } /** * Returns the value of the {@code MACAddress} as a {@code long}. * @return the numeric value represented by this object after conversion to type {@code long}. */ public long toLong() { long mac = 0; for (int i = 0; i < 6; i++) { long t = (address[i] & 0xffL) << ((5 - i) * 8); mac |= t; } return mac; } /** * Returns {@code true} if the MAC address is the broadcast address. * @return {@code true} if the MAC address is the broadcast address. */ public boolean isBroadcast() { for (byte b : address) { if (b != -1) // checks if equal to 0xff return false; } return true; } /** * Returns {@code true} if the MAC address is the multicast address. * @return {@code true} if the MAC address is the multicast address. */ public boolean isMulticast() { if (isBroadcast()) { return false; } return (address[0] & 0x01) != 0; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof MACAddress)) { return false; } MACAddress other = (MACAddress)o; return Arrays.equals(this.address, other.address); } @Override public int hashCode() { return Arrays.hashCode(this.address); } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (byte b: address) { if (builder.length() > 0) { builder.append(":"); } builder.append(String.format("%02X", b & 0xFF)); } return builder.toString(); } }
32.721519
104
0.586847
09e33094c88e80cb90294f33387c107a64f868c1
1,127
package com.vailsys.freeclimb.api.conference; import com.google.gson.annotations.SerializedName; /** * This enum represents the various possible predefined values of the * {@code playBeep} field instead a FreeClimb Conference instance. It indicates * whether the conference will play a beep when a participant enters or leaves * the conference. */ public enum PlayBeep { /** * This value represents the setting where the conference will beep when a * participant enters or leaves the conference. */ @SerializedName("always") ALWAYS, /** * This value represents the setting where the conference will not beep * regardless of a participant entering or leaving the conference. */ @SerializedName("never") NEVER, /** * This value represents the setting where the conference will sound a tone when * a participant enters the conference, but not on leaving. */ @SerializedName("entryOnly") ENTRY_ONLY, /** * This value represents the setting where the conference will sound a tone when * a participant leaves the conference, but not on entering. */ @SerializedName("exitOnly") EXIT_ONLY }
29.657895
81
0.748891
975c2e4f5216deebcaf6136501bb63827e16b97f
1,503
package com.compositesw.services.system.admin.archive; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getArchiveExportDataRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getArchiveExportDataRequest"> * &lt;complexContent> * &lt;extension base="{http://www.compositesw.com/services/system/admin/archive}exportArchiveRequest"> * &lt;sequence> * &lt;element name="maxBytes" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getArchiveExportDataRequest", propOrder = { "maxBytes" }) public class GetArchiveExportDataRequest extends ExportArchiveRequest { protected Integer maxBytes; /** * Gets the value of the maxBytes property. * * @return * possible object is * {@link Integer } * */ public Integer getMaxBytes() { return maxBytes; } /** * Sets the value of the maxBytes property. * * @param value * allowed object is * {@link Integer } * */ public void setMaxBytes(Integer value) { this.maxBytes = value; } }
23.857143
107
0.642715
3370bbabd620f6d476b2095d6903f4b88120111f
538
package com.algaworks; import javax.swing.JOptionPane; import com.algaworks.maladireta.MalaDireta; import com.algaworks.maladireta.csv.MalaDiretaCSV; public class RelacionamentoCliente { public static void main(String[] args) { MalaDireta malaDireta = new MalaDiretaCSV("contatos.csv"); String mensagem = JOptionPane.showInputDialog(null, "Digite a mensagem do e-mail:"); boolean status = malaDireta.enviarEmail(mensagem); JOptionPane.showConfirmDialog(null, "E-mails enviados: " + status); } }
26.9
89
0.737918
9908b0b09ef24277a7a2a3a796f2393a45245648
3,953
/* * _=_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_= * Repose * _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_- * Copyright (C) 2010 - 2015 Rackspace US, 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.openrepose.core.filter.logic.impl; import org.openrepose.commons.utils.servlet.http.MutableHttpServletRequest; import org.openrepose.commons.utils.servlet.http.MutableHttpServletResponse; import org.openrepose.core.filter.logic.FilterDirector; import org.openrepose.core.filter.logic.FilterLogicHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Responsible for calling the specific file logic based on filter actions */ public class FilterLogicHandlerDelegate { private static final Logger LOG = LoggerFactory.getLogger(FilterLogicHandlerDelegate.class); private final ServletRequest request; private final ServletResponse response; private final FilterChain chain; public FilterLogicHandlerDelegate(ServletRequest request, ServletResponse response, FilterChain chain) { this.request = request; this.response = response; this.chain = chain; } public void doFilter(FilterLogicHandler handler) throws IOException, ServletException { final MutableHttpServletRequest mutableHttpRequest = MutableHttpServletRequest.wrap((HttpServletRequest) request); final MutableHttpServletResponse mutableHttpResponse = MutableHttpServletResponse.wrap(mutableHttpRequest, (HttpServletResponse) response); if (handler == null) { mutableHttpResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Error creating filter chain, check your configuration files."); LOG.error("Failed to startup Repose with your configuration. Please check your configuration files and your artifacts directory. Unable to create filter chain."); } else { final FilterDirector requestFilterDirector = handler.handleRequest(mutableHttpRequest, mutableHttpResponse); switch (requestFilterDirector.getFilterAction()) { case NOT_SET: chain.doFilter(request, response); break; case PASS: requestFilterDirector.applyTo(mutableHttpRequest); chain.doFilter(mutableHttpRequest, mutableHttpResponse); break; case PROCESS_RESPONSE: requestFilterDirector.applyTo(mutableHttpRequest); chain.doFilter(mutableHttpRequest, mutableHttpResponse); final FilterDirector responseDirector = handler.handleResponse(mutableHttpRequest, mutableHttpResponse); responseDirector.applyTo(mutableHttpResponse); break; case RETURN: requestFilterDirector.applyTo(mutableHttpResponse); break; } } } }
44.41573
174
0.698204
fe16d9f977b6b5a679e839f3ffe1c2522d85e699
3,877
package com.rafslab.movie.dl.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityOptionsCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.appbar.AppBarLayout; import com.rafslab.movie.dl.R; import com.rafslab.movie.dl.adapter.SimpleAdapter; import com.rafslab.movie.dl.model.Account; import com.rafslab.movie.dl.ui.activity.HomeActivity; import com.rafslab.movie.dl.utils.BaseUtils; import java.util.ArrayList; import java.util.List; public class AccountFragment extends Fragment { private TextView sign; private RecyclerView accountList; private ImageView backgroundGradient; private AppBarLayout contextAppBar; Toolbar contextToolbar; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_account, container, false); sign = rootView.findViewById(R.id.login_register); accountList = rootView.findViewById(R.id.account_list); backgroundGradient = requireActivity().findViewById(R.id.background_gradient); contextAppBar = requireActivity().findViewById(R.id.app_bar); contextToolbar = requireActivity().findViewById(R.id.toolbar); return rootView; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); backgroundGradient.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.background)); contextAppBar.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.colorPrimary)); BaseUtils.getStatusBar(requireContext()).setStatusBarColor(ContextCompat.getColor(requireContext(), R.color.colorPrimary)); BaseUtils.getActionBar(requireContext()).hide(); List<Account> data = prepareList(); accountList.setLayoutManager(new LinearLayoutManager(requireContext())); accountList.setAdapter(new SimpleAdapter(requireContext(), data, true)); sign.setOnClickListener(v-> HomeActivity.showDialogUnderDevelopment(requireContext())); } private List<Account> prepareList(){ List<Account> accounts = new ArrayList<>(); Account data = new Account(R.drawable.ic_twotone_settings, "Settings"); accounts.add(data); data = new Account(R.drawable.ic_request, "Request Movies"); accounts.add(data); data = new Account(R.drawable.ic_baseline_bookmarks, "Bookmark"); accounts.add(data); data = new Account(R.drawable.ic_download, "Downloaded"); accounts.add(data); return accounts; } public void presentActivity(View view) { ActivityOptionsCompat options = ActivityOptionsCompat. makeSceneTransitionAnimation(requireActivity(), view, "transition"); int revealX = (int) (view.getX() + view.getWidth() / 2); int revealY = (int) (view.getY() + view.getHeight() / 2); Intent intent = new Intent(requireContext(), HomeActivity.class); intent.putExtra(HomeActivity.EXTRA_CIRCULAR_REVEAL_X, revealX); intent.putExtra(HomeActivity.EXTRA_CIRCULAR_REVEAL_Y, revealY); ActivityCompat.startActivity(requireContext(), intent, options.toBundle()); } }
44.563218
132
0.74568
97257f04ef1871ccfbe9907bbe37144ec2196ef5
6,463
package Renderer; import org.joml.*; import org.lwjgl.BufferUtils; import java.io.IOException; import java.nio.FloatBuffer; import java.nio.file.Files; import java.nio.file.Paths; import static org.lwjgl.opengl.GL11.GL_FALSE; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL20.glGetProgramInfoLog; /** * Shader - manage shader program for GPU */ public class Shader { private int shaderProgramID; private String vertexSrc; private String fragmentSrc; private String filepath; private boolean beingUsed = false; public Shader(String filepath) { this.filepath = filepath; String source = null; try { source = new String(Files.readAllBytes(Paths.get(filepath))); } catch (IOException e) { e.printStackTrace(); assert false : "Error could not open file for shader : '" + filepath +"'"; } //sections of shader code headed by #type fragment or #type vertex etc. String[] splitString = source.split("(#type)( )+([a-zA-Z]+)"); assert splitString.length >= 2 : "Error shader '" + filepath + "' is not a valid shader"; String[] shadertype = new String[splitString.length-1]; int count = 1; int startPos = 0; int endPos = 0; while (count < splitString.length) { startPos = source.indexOf("#type", endPos) + 6; endPos = source.indexOf("\r\n", startPos); shadertype[count-1] = source.substring(startPos, endPos).trim(); switch (shadertype[count-1]) { case "vertex": vertexSrc = splitString[count]; //System.out.println("vertex source = \n" + vertexSrc); break; case "fragment": fragmentSrc = splitString[count]; //System.out.println("fragment source = \n" + fragmentSrc); break; default: assert false : "Error shader '" + filepath + "' has invalid types"; } ++count; } } public void compile() { //=========================== // Compile and link shaders //=========================== // first load and compile the vertex shader int vertexID = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexID,vertexSrc); glCompileShader(vertexID); //check for errors int success = glGetShaderi(vertexID, GL_COMPILE_STATUS); if (success == GL_FALSE) { int len = glGetShaderi(vertexID, GL_INFO_LOG_LENGTH); System.out.println("ERROR: '" + filepath + "'\n\tvertex shader compile failed"); System.out.println(glGetShaderInfoLog(vertexID, len)); assert false : ""; } // second load and compile the fragment shader int fragmentID = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentID, fragmentSrc); glCompileShader(fragmentID); //check for errors success = glGetShaderi(fragmentID, GL_COMPILE_STATUS); if (success == GL_FALSE) { int len = glGetShaderi(fragmentID, GL_INFO_LOG_LENGTH); System.out.println("ERROR: '" + filepath + "'\n\tfragment shader compile failed"); System.out.println(glGetShaderInfoLog(fragmentID, len)); assert false : ""; } //link vertex and fragment shaders shaderProgramID = glCreateProgram(); glAttachShader(shaderProgramID, vertexID); glAttachShader(shaderProgramID, fragmentID); glLinkProgram(shaderProgramID); //check for link errors success = glGetProgrami(shaderProgramID, GL_LINK_STATUS); if (success == GL_FALSE) { int len = glGetProgrami(shaderProgramID, GL_INFO_LOG_LENGTH); System.out.println("ERROR: '" + filepath +"'\n\tlinking of shader failed"); System.out.println(glGetProgramInfoLog(shaderProgramID, len)); assert false : ""; } } public void use() { if (!beingUsed) { //bind shader program glUseProgram(shaderProgramID); beingUsed = true; } } public void detach() { glUseProgram(0); beingUsed = false; } // utility methods to send data to the shader program on the GPU public void uploadMat4f(String varName, Matrix4f mat4) { use(); int varLocation = glGetUniformLocation(shaderProgramID, varName); FloatBuffer matBuffer = BufferUtils.createFloatBuffer(16); mat4.get(matBuffer); glUniformMatrix4fv(varLocation,false, matBuffer); } public void uploadMat3f(String varName, Matrix3f mat3) { use(); int varLocation = glGetUniformLocation(shaderProgramID, varName); FloatBuffer matBuffer = BufferUtils.createFloatBuffer(9); mat3.get(matBuffer); glUniformMatrix3fv(varLocation,false, matBuffer); } public void uploadVec4f(String varName, Vector4f vec) { use(); int varLocation = glGetUniformLocation(shaderProgramID, varName); glUniform4f(varLocation, vec.x, vec.y, vec.z, vec.w); } public void uploadVec3f(String varName, Vector3f vec) { use(); int varLocation = glGetUniformLocation(shaderProgramID, varName); glUniform3f(varLocation, vec.x, vec.y, vec.z); } public void uploadVec2f(String varName, Vector2f vec) { use(); int varLocation = glGetUniformLocation(shaderProgramID, varName); glUniform2f(varLocation, vec.x, vec.y); } public void uploadFloat(String varName, float val) { use(); int varLocation = glGetUniformLocation(shaderProgramID, varName); glUniform1f(varLocation, val); } public void uploadInt(String varName, int val) { use(); int varLocation = glGetUniformLocation(shaderProgramID, varName); glUniform1i(varLocation, val); } public void uploadIntArray(String varName, int[] val) { use(); int varLocation = glGetUniformLocation(shaderProgramID, varName); glUniform1iv(varLocation, val); } public void uploadTexture(String varName, int slot) { use(); int varLocation = glGetUniformLocation(shaderProgramID, varName); glUniform1i(varLocation, slot); } }
35.125
97
0.610243
dc61f8a773eb7e8f0384852e3f564d1d4fd80e06
2,747
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package resultsystem; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import javax.swing.JOptionPane; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; /** * * @author chiku */ public class ExcelRead { public static void read(String filename, String standard) throws Exception { short a=0; short b=1; short c=2; short d=3; int i=0; Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", ""); Statement st=conn.createStatement(); String value1=" ", value2=" ",value3 =" ", value4 =" "; //String filename ="C:\\Users\\root\\Documents\\NetBeansProjects\\ResultSystem\\src\\resultsystem\\airline.xls"; if(filename != null && !filename.equals("")){ try{ FileInputStream fs =new FileInputStream(filename); HSSFWorkbook wb = new HSSFWorkbook(fs); for(int k = 0; k < wb.getNumberOfSheets(); k++){ int j=i+1; HSSFSheet sheet = wb.getSheetAt(k); int rows = sheet.getPhysicalNumberOfRows(); for(int r = 1; r < rows; r++){ HSSFRow row = sheet.getRow(r); int cells = row.getPhysicalNumberOfCells(); HSSFCell cell1 = row.getCell(a); value1 = Integer.toString((int) cell1.getNumericCellValue()); HSSFCell cell2 = row.getCell(b); value2 = cell2.getStringCellValue(); HSSFCell cell3 = row.getCell(c); value3 = cell3.getStringCellValue(); HSSFCell cell4 = row.getCell(d); //value4 = cell4.getStringCellValue(); System.out.println(value1+"\t"+value2+"\t"+value3+"\t"+value4); st.executeUpdate("insert into class_"+standard+"_details(roll,name,fname) values('"+value1+"','"+value2+"','"+value3+"')"); } i++; } JOptionPane.showMessageDialog(null, "Database of class "+standard+" created!"); } catch(Exception e){ //System.out.println(e); e.printStackTrace(); } } } }
32.702381
128
0.65708
b2267f2cf5f6c3da56ae928ba0280b68f9bf15e4
707
package ingredients; import beverage.Beverage; import ingredients.Ingredient; import ingredients.IngredientType; public abstract class Water extends Ingredient { /** * @param ingredientType to define the type of ingredient * @param quantity to define the quantity of a particular ingredient needed * @param wrappedBeverage to wrap a beverage by water * @throws IllegalArgumentException while calling Ingredient class constructor when quantity or wrappedBeverage is invalid */ protected Water(IngredientType ingredientType, int quantity, Beverage wrappedBeverage) throws IllegalArgumentException { super(ingredientType, quantity, wrappedBeverage); } }
37.210526
126
0.76662
5ead404bd54189e29524436195363358b94c0405
583
package service; import java.io.*; import javax.servlet.*; import org.springframework.beans.factory.annotation.*; import org.springframework.stereotype.*; import org.springframework.web.multipart.*; @Service public class ImageService { @Autowired ServletContext context; public String getPath(MultipartFile file, String id) throws IllegalStateException, IOException { String path = context.getRealPath("/") + "resources/images/profile/" + id + ".png"; String fileName = id+".png"; System.out.println(path); file.transferTo(new File(path)); return fileName; } }
23.32
97
0.746141
1e49736937cebe5e902a06bf338408546e3cb4ac
5,179
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.model; import com.model.User; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author milisava */ @Entity @Table(name = "aktivnost") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Aktivnost.findAll", query = "SELECT a FROM Aktivnost a") , @NamedQuery(name = "Aktivnost.findByIdAktivnosti", query = "SELECT a FROM Aktivnost a WHERE a.idAktivnosti = :idAktivnosti") , @NamedQuery(name = "Aktivnost.findByNaziv", query = "SELECT a FROM Aktivnost a WHERE a.naziv = :naziv") , @NamedQuery(name = "Aktivnost.findByOznaka", query = "SELECT a FROM Aktivnost a WHERE a.oznaka = :oznaka") , @NamedQuery(name = "Aktivnost.findByOpis", query = "SELECT a FROM Aktivnost a WHERE a.opis = :opis")}) public class Aktivnost implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idAktivnosti") private Integer idAktivnosti; @Basic(optional = false) @NotNull @Size(min = 1, max = 250) @Column(name = "naziv") private String naziv; @Basic(optional = false) @NotNull @Size(min = 1, max = 250) @Column(name = "oznaka") private String oznaka; @Basic(optional = false) @NotNull @Size(min = 1, max = 2000) @Column(name = "opis") private String opis; @OneToMany(cascade = CascadeType.ALL, mappedBy = "aktivnost", fetch = FetchType.LAZY) private List<AktivnostDokument> aktivnostDokumentList; @JoinColumn(name = "idProcesa", referencedColumnName = "idProcesa") @ManyToOne(optional = false, fetch = FetchType.LAZY) private Proces idProcesa; @JoinColumn(name = "userID", referencedColumnName = "userID") @ManyToOne(optional = false, fetch = FetchType.LAZY) private User userID; public Aktivnost() { } public Aktivnost(Integer idAktivnosti) { this.idAktivnosti = idAktivnosti; } public Aktivnost(Integer idAktivnosti, String naziv, String oznaka, String opis) { this.idAktivnosti = idAktivnosti; this.naziv = naziv; this.oznaka = oznaka; this.opis = opis; } public Integer getIdAktivnosti() { return idAktivnosti; } public void setIdAktivnosti(Integer idAktivnosti) { this.idAktivnosti = idAktivnosti; } public String getNaziv() { return naziv; } public void setNaziv(String naziv) { this.naziv = naziv; } public String getOznaka() { return oznaka; } public void setOznaka(String oznaka) { this.oznaka = oznaka; } public String getOpis() { return opis; } public void setOpis(String opis) { this.opis = opis; } @XmlTransient public List<AktivnostDokument> getAktivnostDokumentList() { return aktivnostDokumentList; } public void setAktivnostDokumentList(List<AktivnostDokument> aktivnostDokumentList) { this.aktivnostDokumentList = aktivnostDokumentList; } public Proces getIdProcesa() { return idProcesa; } public void setIdProcesa(Proces idProcesa) { this.idProcesa = idProcesa; } public User getUserID() { return userID; } public void setUserID(User userID) { this.userID = userID; } @Override public int hashCode() { int hash = 0; hash += (idAktivnosti != null ? idAktivnosti.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Aktivnost)) { return false; } Aktivnost other = (Aktivnost) object; if ((this.idAktivnosti == null && other.idAktivnosti != null) || (this.idAktivnosti != null && !this.idAktivnosti.equals(other.idAktivnosti))) { return false; } return true; } @Override public String toString() { return "com.model.Aktivnost[ idAktivnosti=" + idAktivnosti + " ]"; } }
30.110465
153
0.651091
6b765f5737ab281ebcabbf08fd68d889599b19ba
2,334
package top.top7.collection.list; /****** * Created by LEARNING on 2020/10/29 14:37. * ********************************************************************** * .-~~~~~~~~~-._ _.-~~~~~~~~~-. * __.' ~. .~ `.__ * .'// \./ \\`. * .'// | \\`. * .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`. * .'//.-" `-. | .-' "-.\\`. * .'//______.============-.. \ | / ..-============.______\\`. *.'______________________________\|/______________________________`. * * * Don't forget to be awesome! ********************************************************************** */ import java.util.ArrayList; import java.util.List; /** * list特点: 元素有序可重复,有下标,可存取 null * 若下标越界则会报异常(以size元素个数为准,不以底层具体实现的容量为准) * * List接口中特有的常用方法: * * 1. add(int index,E e);void * 2. set(int index,E e);E oldEle * 3. get(int index);E * 4. indexOf(Object o);int * 5. lastIndexOf(Object o);int * 6. remove(int index);E */ public class PList1 { public static void main(String[] args) { List<String> list = new ArrayList(); list.add("我是1"); list.add("我是2"); list.add("我是3"); list.add("我是4"); list.add("我是王五"); list.add("我是王五"); list.add("我是7"); list.add("我是8"); list.add("我是9"); list.add("我是10"); //1.根据下标向集合中添加元素,当前下标之后元素统一后移一位,该方法没有返回值 //index的值可以为最大下标+1,意为添加到末尾 list.add(2, "我是李四"); //2.根据下标设置元素的值,返回之前的值 String oldEle = list.set(2, "李四不见了"); System.out.println("我是谁:" + oldEle); //3.根据下标获取元素 String e2 = list.get(2); System.out.println("是谁在这里:" + e2); //4.获取元素第一次出现的位置,内部调用equals方法进行比较,自定义类需要重写equals方法 int findex = list.indexOf("我是王五"); System.out.println("王五在哪里:" + findex); //5.获取元素最后一次出现的位置 int lindex = list.lastIndexOf("我是王五"); System.out.println("最后一个王五在哪里:" + lindex); //6.根据下标移除元素,并返回该元素 String remove = list.remove(2); System.out.println("谁被删掉了:" + remove); for (String s : list) { System.out.println(s); } } }
28.814815
72
0.430591
b5b6c385aa829402187ee7c7c9a91a07c4e0fbe3
2,998
/* * Copyright © 2017 Mark Raynsford <[email protected]> https://www.io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.smfj.tests.processing; import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder; import com.github.marschall.memoryfilesystem.StringTransformers; import com.io7m.junreachable.UnreachableCodeException; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.attribute.DosFileAttributeView; import java.nio.file.attribute.PosixFileAttributeView; public final class SMFTestFilesystems { private SMFTestFilesystems() { throw new UnreachableCodeException(); } public static FileSystem makeEmptyUnixFilesystem() { try { final String user = "root"; final MemoryFileSystemBuilder base = MemoryFileSystemBuilder.newEmpty(); base.addRoot("/"); base.setCurrentWorkingDirectory("/"); base.setSeparator("/"); base.addUser(user); base.addGroup(user); base.addFileAttributeView(PosixFileAttributeView.class); base.setStoreTransformer(StringTransformers.IDENTIY); base.setCaseSensitive(true); base.addForbiddenCharacter((char) 0); base.addFileAttributeView(PosixFileAttributeView.class); return base.build("catalog"); } catch (final IOException e) { throw new UnreachableCodeException(e); } } public static FileSystem makeEmptyDOSFilesystem() { try { final String user = "Administrator"; final MemoryFileSystemBuilder base = MemoryFileSystemBuilder.newEmpty(); base.addRoot("C:\\"); base.setSeparator("\\"); base.addUser(user); base.addGroup(user); base.addFileAttributeView(DosFileAttributeView.class); base.setStoreTransformer(StringTransformers.IDENTIY); base.setCaseSensitive(false); base.addForbiddenCharacter('\\'); base.addForbiddenCharacter('/'); base.addForbiddenCharacter(':'); base.addForbiddenCharacter('*'); base.addForbiddenCharacter('?'); base.addForbiddenCharacter('"'); base.addForbiddenCharacter('<'); base.addForbiddenCharacter('>'); base.addForbiddenCharacter('|'); return base.build("catalog"); } catch (final IOException e) { throw new UnreachableCodeException(e); } } }
36.560976
78
0.726484
301a88c1188977341c045f11c7539cbce9d2472f
6,002
package com.yuan.superdemo.alarmservices; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.text.format.Time; import android.util.Log; import com.yuan.superdemo.R; /** * 测试 AlarmService 闹钟服务,模拟心跳 */ public class AlarmActivity extends AppCompatActivity { private final String TAG = "AlarmActivity"; private int PING_TIME_STAMP = 30 * 1000;//ping时间戳 private int PONG_TIME_STAMP = 10 * 1000;//pong时间戳 public static final String ACTION_HEADER = "SNACK"; public static final String PING_ALARM = ".PING_ALARM"; // ping服务器闹钟BroadcastReceiver的Action public static final String PONG_TIMEOUT_ALARM = ".PONG_TIMEOUT_ALARM"; // 判断连接超时的闹钟BroadcastReceiver的Action // intent private PendingIntent mPongTimeoutAlarmPendIntent; private PendingIntent mPingAlarmPendIntent; private Intent mPingAlarmIntent = new Intent(ACTION_HEADER+PING_ALARM); private Intent mPongTimeoutAlarmIntent = new Intent(ACTION_HEADER+PONG_TIMEOUT_ALARM); // BroadcastReceiver private BroadcastReceiver mPongTimeoutAlarmReceiver = new PongTimeoutAlarmReceiver(); private BroadcastReceiver mPingAlarmReceiver = new PingAlarmReceiver(); // handler作为模拟请求 private int HANDLER_REQUEST_CODE = 1000; private int HANDLER_RESPONSE_CODE = 1001; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == HANDLER_REQUEST_CODE){ handler.sendEmptyMessageDelayed(HANDLER_RESPONSE_CODE,1500); }else if (msg.what == HANDLER_RESPONSE_CODE){ Log.i(TAG,"请求成功,客户端心跳活跃状态,准备取消超时闹钟..."); cacelPongService(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm); initPendIntent(); registerService(); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mPingAlarmReceiver); unregisterReceiver(mPongTimeoutAlarmReceiver); } private void initPendIntent(){ // 闹钟服务intent mPingAlarmPendIntent = PendingIntent.getBroadcast( this, 0, mPingAlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); mPongTimeoutAlarmPendIntent = PendingIntent.getBroadcast( this, 0, mPongTimeoutAlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); registerReceiver(mPingAlarmReceiver, new IntentFilter( ACTION_HEADER + PING_ALARM));//ping服务器广播接收者 registerReceiver(mPongTimeoutAlarmReceiver, new IntentFilter( ACTION_HEADER + PONG_TIMEOUT_ALARM)); // 注册pong超时的广播接收器 } private void registerService(){ registerPingService(); registerPongService(); Log.i(TAG,getTime()); } // 注册两个闹钟服务,pong闹钟会比ping闹钟慢3秒作为检测时间 private void registerPingService(){ //开始时间 AlarmManager mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// api 19以上后 闹钟服务将不准确 mAlarmManager.setExact(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+PING_TIME_STAMP,mPingAlarmPendIntent); }else { mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), PING_TIME_STAMP, mPingAlarmPendIntent); } } private void registerPongService(){ AlarmManager mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mAlarmManager.set( AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + PING_TIME_STAMP + PONG_TIME_STAMP,mPongTimeoutAlarmPendIntent); } private void cacelPingService(){ AlarmManager mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mAlarmManager.cancel(mPingAlarmPendIntent); } private void cacelPongService(){ AlarmManager mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mAlarmManager.cancel(mPongTimeoutAlarmPendIntent); } /** * 发送ping请求的广播接收器 */ private class PingAlarmReceiver extends BroadcastReceiver { public void onReceive(Context ctx, Intent i) { Log.i(TAG,"闹钟执行 "+getTime()+" ,收到ping广播,开始发心跳..."); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { registerPingService(); } handler.sendEmptyMessage(HANDLER_REQUEST_CODE); } } /** * pong超时的广播接收器 */ private class PongTimeoutAlarmReceiver extends BroadcastReceiver { public void onReceive(Context ctx, Intent i) { Log.i(TAG,"闹钟执行 "+getTime()+" ,收到pong广播,客户端已经挂啦,准备释放资源,登出账号..."); cacelPingService(); cacelPongService(); } } private String getTime(){ Time time = new Time("GMT+8"); time.setToNow(); int year = time.year; int month = time.month; int day = time.monthDay; int minute = time.minute; int hour = time.hour; int sec = time.second; return "当前时间为:" + year + "年 " + month + "月 " + day + "日 " + hour + "时 " + minute + "分 " + sec + "秒"; } }
34.297143
144
0.645785
dbb3eb5e16a672087c44dce6e65922c09135c184
156
package cn.enilu.flash.common.bean.vo.offcialsite; import lombok.Data; @Data public class Author { private String name; private String avatar; }
14.181818
50
0.737179
295439f81548060888be876ddafd1045f1f60f48
990
package worker; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import manager.WareHouseManager; import util.Location; import util.WareHouse; public class Replenisher extends Worker implements Observer { public Replenisher(String name, WareHouse wareHouse) { super(name, wareHouse); } /* * do replenishing */ public void update(Location location) { super.setState(false); System.out.println(" here did replenishing." + location); System.out.println( "Before replenishing, stock has " + location.getFasciaManager().getAmount() + " Fascias."); location.getFasciaManager().replenishing(); WareHouseManager.getLogger().log(Level.INFO, "OUTPUT: " + this.getName() + " is replenishing."); // System.out.println(super.getName() + " did replenishing."); System.out.println("Now, stock has " + location.getFasciaManager().getAmount() + " Fascias."); } }
26.052632
101
0.676768
7b72132ac4047b6fb5980cffaa9242acfee6ffe7
11,823
/* * 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.sis.internal.filter; import java.util.Map; import java.util.IdentityHashMap; import java.util.Collection; import java.io.Serializable; import java.util.Collections; import java.util.function.Predicate; import java.util.logging.Logger; import org.opengis.util.CodeList; import org.opengis.util.LocalName; import org.opengis.util.ScopedName; import org.apache.sis.feature.DefaultAttributeType; import org.apache.sis.internal.feature.Resources; import org.apache.sis.internal.feature.Geometries; import org.apache.sis.internal.feature.GeometryWrapper; import org.apache.sis.util.iso.Names; import org.apache.sis.util.collection.DefaultTreeTable; import org.apache.sis.util.collection.TableColumn; import org.apache.sis.util.collection.TreeTable; import org.apache.sis.util.resources.Vocabulary; import org.apache.sis.util.logging.Logging; import org.apache.sis.internal.system.Loggers; // Branch-dependent imports import org.apache.sis.filter.Filter; import org.apache.sis.filter.Expression; /** * Base class of Apache SIS implementation of OGC expressions, comparators or filters. * {@code Node} instances are associated together in a tree, which can be formatted * by {@link #toString()}. * * @author Johann Sorel (Geomatys) * @author Martin Desruisseaux (Geomatys) * @version 1.1 * @since 1.1 * @module */ public abstract class Node implements Serializable { /** * For cross-version compatibility. */ private static final long serialVersionUID = -749201100175374658L; /** * Scope of all names defined by SIS convention. * * @see #createName(String) */ private static final LocalName SCOPE = Names.createLocalName("Apache", null, "sis"); /** * Creates a new expression, operator or filter. */ protected Node() { } /** * Creates an attribute type for values of the given type and name. * The attribute is mandatory, unbounded and has no default value. * * @param <T> compile-time value of {@code type}. * @param type type of values in the attribute. * @param name name of the attribute to create. * @return an attribute of the given type and name. * * @see Expression#getFunctionName() */ protected static <T> DefaultAttributeType<T> createType(final Class<T> type, final Object name) { return new DefaultAttributeType<>(Collections.singletonMap(DefaultAttributeType.NAME_KEY, name), type, 1, 1, null, (DefaultAttributeType<?>[]) null); } /** * Returns the mathematical symbol for this binary function. * For comparison operators, the symbol should be one of {@literal < > ≤ ≥ = ≠}. * For arithmetic operators, the symbol should be one of {@literal + − × ÷}. * * @return the mathematical symbol, or 0 if none. */ protected char symbol() { return (char) 0; } /** * Returns the name of the function or filter to be called. * For example, this might be {@code "sis:cos"} or {@code "sis:atan2"}. * The type depend on the implemented interface: * * <ul> * <li>{@link ScopedName} if this node implements {@link Expression}.</li> * <li>{@link CodeList} if this node implements {@link Filter}.</li> * </ul> * * <div class="note"><b>Note for implementers:</b> * implementations typically return a hard-coded value. If the returned value may vary for the same class, * then implementers should override also the {@link #equals(Object)} and {@link #hashCode()} methods.</div> * * @return the name of this function. */ private Object getDisplayName() { if (this instanceof Expression<?,?>) { return ((Expression<?,?>) this).getFunctionName(); } else if (this instanceof Filter<?>) { return ((Filter<?>) this).getOperatorType(); } else { return getClass().getSimpleName(); } } /** * Creates a name in the "SIS" scope. * This is a helper method for {@link #getFunctionName()} implementations. * * @param tip the expression name in SIS namespace. * @return an expression name in the SIS namespace. */ protected static ScopedName createName(final String tip) { return Names.createScopedName(SCOPE, null, tip); } /** * Returns an expression whose results is a geometry wrapper. * * @param <R> the type of resources (e.g. {@code Feature}) used as inputs. * @param <G> the geometry implementation type. * @param library the geometry library to use. * @param expression the expression providing source values. * @return an expression whose results is a geometry wrapper. * @throws IllegalArgumentException if the given expression is already a wrapper * but for another geometry implementation. */ @SuppressWarnings("unchecked") protected static <R,G> Expression<R, GeometryWrapper<G>> toGeometryWrapper( final Geometries<G> library, final Expression<R,?> expression) { if (expression instanceof GeometryConverter<?,?>) { if (library.equals(((GeometryConverter<?,?>) expression).library)) { return (GeometryConverter<R,G>) expression; } else { throw new IllegalArgumentException(); // TODO: provide a message. } } return new GeometryConverter<>(library, expression); } /** * If the given exception was wrapped by {@link #toGeometryWrapper(Geometries, Expression)}, * returns the original expression. Otherwise returns the given expression. * * @param <R> the type of resources (e.g. {@code Feature}) used as inputs. * @param <G> the geometry implementation type. * @param expression the expression to unwrap. * @return the unwrapped expression. */ protected static <R,G> Expression<? super R, ?> unwrap(final Expression<R, GeometryWrapper<G>> expression) { if (expression instanceof GeometryConverter<?,?>) { return ((GeometryConverter<R,?>) expression).expression; } else { return expression; } } /** * Returns a handler for the library of geometric objects used by the given expression. * The given expression should be the first parameter (as requested by SQLMM specification), * otherwise the error message will not be accurate. * * @param <G> the type of geometry created by the expression. * @param expression the expression for which to get the geometry library. * @return the geometry library (never {@code null}). */ protected static <G> Geometries<G> getGeometryLibrary(final Expression<?, GeometryWrapper<G>> expression) { if (expression instanceof GeometryConverter<?,?>) { return ((GeometryConverter<?,G>) expression).library; } throw new IllegalArgumentException(Resources.format(Resources.Keys.NotAGeometryAtFirstExpression)); } /** * Returns the children of this node, or an empty collection if none. This is used * for information purpose, for example in order to build a string representation. * * @return the children of this node, or an empty collection if none. */ protected abstract Collection<?> getChildren(); /** * Builds a tree representation of this node, including all children. This method expects an * initially empty node, which will be set to the {@linkplain #getFunctionName() name} of this node. * Then all children will be appended recursively, with a check against cyclic graph. * * @param root where to create a tree representation of this node. * @param visited nodes already visited. This method will write in this map. */ private void toTree(final TreeTable.Node root, final Map<Object,Boolean> visited) { root.setValue(TableColumn.VALUE, getDisplayName()); for (final Object child : getChildren()) { final TreeTable.Node node = root.newChild(); final String value; if (child instanceof Node) { if (visited.putIfAbsent(child, Boolean.TRUE) == null) { ((Node) child).toTree(node, visited); continue; } else { value = Vocabulary.format(Vocabulary.Keys.CycleOmitted); } } else { value = String.valueOf(child); } node.setValue(TableColumn.VALUE, value); } } /** * Returns a string representation of this node. This representation can be printed * to the {@linkplain System#out standard output stream} (for example) if it uses a * monospaced font and supports Unicode. * * @return a string representation of this filter. */ @Override public final String toString() { final DefaultTreeTable table = new DefaultTreeTable(TableColumn.VALUE); toTree(table.getRoot(), new IdentityHashMap<>()); return table.toString(); } /** * Returns a hash code value computed from the class and the children. */ @Override public int hashCode() { return getClass().hashCode() + 37 * getChildren().hashCode(); } /** * Returns {@code true} if the given object is an instance of the same class with the equal children. * * @param other the other object to compare with this node. * @return whether the two object are equal. */ @Override public boolean equals(final Object other) { if (other != null && other.getClass() == getClass()) { return getChildren().equals(((Node) other).getChildren()); } return false; } /** * Reports that an operation failed because of the given exception. * This method assumes that the warning occurred in a {@code test(…)} or {@code apply(…)} method. * * @param e the exception that occurred. * @param recoverable {@code true} if the caller has been able to fallback on a default value, * or {@code false} if the caller has to return {@code null}. * * @todo Consider defining a {@code Context} class providing, among other information, listeners where to report warnings. * * @see <a href="https://issues.apache.org/jira/browse/SIS-460">SIS-460</a> */ protected final void warning(final Exception e, final boolean recoverable) { final Logger logger = Logging.getLogger(Loggers.FILTER); final String method = (this instanceof Predicate) ? "test" : "apply"; if (recoverable) { Logging.recoverableException(logger, getClass(), method, e); } else { Logging.unexpectedException(logger, getClass(), method, e); } } }
40.628866
126
0.649835
91040ae992313d2d9a2204b058fce932594d2dcf
260
package com.heroengineer.hero_engineer_backend.section; import org.springframework.data.mongodb.repository.MongoRepository; /** * Repository for querying Section documents. */ public interface SectionRepository extends MongoRepository<Section, String> { }
26
77
0.823077
4d30394203aae44a28922b10814ee77e98c6a36d
1,319
package com.example.holiday.repository; import javax.persistence.*; @Entity @Table(name = "holidays") public class HolidayEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private long workerId; private long monthId; private int days; private int firstDay; private int lastDay; public HolidayEntity() { super(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getWorkerId() { return workerId; } public void setWorkerId(long workerId) { this.workerId = workerId; } public long getMonthId() { return monthId; } public void setMonthId(long monthId) { this.monthId = monthId; } public int getDays() { return days; } public void setDays(int days) { this.days = days; } public int getFirstDay() { return firstDay; } public void setFirstDay(int firstDay) { this.firstDay = firstDay; } public int getLastDay() { return lastDay; } public void setLastDay(int lastDay) { this.lastDay = lastDay; } public boolean checkIfInRange(int i) { return i <= lastDay && i >= firstDay; } }
17.586667
55
0.588324
e1f971641fd52e567e4160ab1e9566d43a117599
5,729
/******************************************************************************* * Apache License Version 2.0 * * Saul de Nova Caballero ******************************************************************************/ package com.terraingeneration; import com.terraingeneration.utilities.Color; import com.terraingeneration.utilities.Utilities; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; /** * The terrain generation main class * Created by Saul de Nova Caballero on 11/21/15. */ public class TerrainGeneration { // All the colors that the map uses private static Color plain = new Color((byte)0, (byte)64, (byte)0); private static Color forest = new Color((byte)133, (byte)182, (byte)116); private static Color sea = new Color((byte)0, (byte)0, (byte)55); private static Color coast = new Color((byte)0, (byte)53, (byte)106); private static Color mount = new Color((byte)167, (byte)157, (byte)147); private static Color mountain = new Color((byte)216, (byte)223, (byte)226); /** * Convert the value into the character * @param value the character value * @return the character */ private static char convertToChar(short value) { if (value >= 256) { return '^'; } else if (value >= 128) { return 'h'; } else if (value >= 0) { return 'p'; } else if (value >= -128) { return ','; } return '.'; } /** * Print the map as a char map to the file map.txt * @param map the map to print */ private static void printCharMap(String fileName, short[][] map) { try { PrintWriter writer = new PrintWriter(fileName, "UTF-8"); for (short[] row : map) { for (short elem : row) { writer.write(convertToChar(elem)); } writer.write('\n'); } writer.close(); } catch (FileNotFoundException | UnsupportedEncodingException e) { System.out.println(e.getLocalizedMessage()); } } /** * Linear interpolation * @param c1 color 1 * @param c2 color 2 * @param value interpolation value * @return the color */ private static Color lerp( Color c1, Color c2, float value) { byte[] v = new byte[3]; for (int i = 0; i < 3; i++) { if (c1.getV()[i] > c2.getV()[i]) { v[i] = (byte) (c2.getV()[i] + (byte) ((float)(c1.getV()[i] - c2.getV()[i]) * value)); } else { v[i] = (byte) (c1.getV()[i] + (byte) ((float)(c1.getV()[i] - c2.getV()[i]) * value)); } } return new Color(v); } /** * Convert a value to a color * @param value the value * @return the color */ private static Color convertToColor(short value) { value = (short)Utilities.clamp(value, -512, 512); if (value >= 256) { return lerp(mountain, mount, (value - 256) / 256); } else if (value >= 128) { return lerp(mount, forest, (value - 128) / 128); } else if (value >= 0) { return lerp(forest, plain, value / 128); } else if (value >= -128) { return lerp(plain, coast, (value + 128) / 128); } return lerp(coast, sea, (value + 512) / 384); } /** * Print the map into a bitmap named map.bmp * @param map the map structure */ private static void printBitMap(String fileName, int n, short[][] map) { try { BufferedImage image = new BufferedImage( n, n, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { Color color = convertToColor(map[x][y]); int rgb = (color.getR() & 0xff) << 16 | (color.getG() & 0xff) << 8 | (color.getB() & 0xff); image.setRGB(x, y, rgb); } } ImageIO.write(image, "bmp", new File(fileName)); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); } } /** * Main function * @param args the function arguments */ public static void main(String[] args) { long startTime, elapsedSequentialTime, elapsedParallelTime; short[][] map; int n = 4097; try { startTime = System.nanoTime(); map = DiamondSquare.generate(n, false); elapsedSequentialTime = System.nanoTime() - startTime; printCharMap("map.txt", map); printBitMap("map.bmp", n, map); System.out.println("Elapsed time: " + elapsedSequentialTime / 1e9); startTime = System.nanoTime(); map = DiamondSquare.generate(n, true); elapsedParallelTime = System.nanoTime() - startTime; printCharMap("map_parallel.txt", map); printBitMap("map_parallel.bmp", n, map); System.out.println("Elapsed parallel time: " + elapsedParallelTime / 1e9); System.out.println("Speedup: " + ((double)elapsedSequentialTime / (double)elapsedParallelTime)); } catch(IllegalArgumentException e) { System.out.println(e.getLocalizedMessage()); } } }
32.737143
86
0.494676
617879f7c22b20aa67239e7105841917b75aee7b
7,300
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.gemstone.gemfire.cache.lucene.internal.repository; import static org.junit.Assert.*; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.lucene.internal.directory.RegionDirectory; import com.gemstone.gemfire.cache.lucene.internal.filesystem.ChunkKey; import com.gemstone.gemfire.cache.lucene.internal.filesystem.File; import com.gemstone.gemfire.cache.lucene.internal.repository.serializer.HeterogenousLuceneSerializer; import com.gemstone.gemfire.cache.lucene.internal.repository.serializer.Type2; import com.gemstone.gemfire.test.junit.categories.IntegrationTest; /** * Test of the {@link IndexRepository} and everything below * it. This tests that we can save gemfire objects or PDXInstance * objects into a lucene index and search for those objects later. */ @Category(IntegrationTest.class) public class IndexRepositoryImplJUnitTest { private IndexRepositoryImpl repo; private HeterogenousLuceneSerializer mapper; private StandardAnalyzer analyzer = new StandardAnalyzer(); private IndexWriter writer; private Region region; @Before public void setUp() throws IOException { ConcurrentHashMap<String, File> fileRegion = new ConcurrentHashMap<String, File>(); ConcurrentHashMap<ChunkKey, byte[]> chunkRegion = new ConcurrentHashMap<ChunkKey, byte[]>(); RegionDirectory dir = new RegionDirectory(fileRegion, chunkRegion); IndexWriterConfig config = new IndexWriterConfig(analyzer); writer = new IndexWriter(dir, config); String[] indexedFields= new String[] {"s", "i", "l", "d", "f", "s2", "missing"}; mapper = new HeterogenousLuceneSerializer(indexedFields); region = Mockito.mock(Region.class); Mockito.when(region.isDestroyed()).thenReturn(false); repo = new IndexRepositoryImpl(region, writer, mapper); } @Test public void testAddDocs() throws IOException, ParseException { repo.create("key1", new Type2("bacon maple bar", 1, 2L, 3.0, 4.0f, "Grape Ape doughnut")); repo.create("key2", new Type2("McMinnville Cream doughnut", 1, 2L, 3.0, 4.0f, "Captain my Captain doughnut")); repo.create("key3", new Type2("Voodoo Doll doughnut", 1, 2L, 3.0, 4.0f, "Toasted coconut doughnut")); repo.create("key4", new Type2("Portland Cream doughnut", 1, 2L, 3.0, 4.0f, "Captain my Captain doughnut")); repo.commit(); checkQuery("Cream", "s", "key2", "key4"); checkQuery("NotARealWord", "s"); } @Test public void testEmptyRepo() throws IOException, ParseException { checkQuery("NotARealWord", "s"); } @Test public void testUpdateAndRemoveStringKeys() throws IOException, ParseException { updateAndRemove("key1", "key2", "key3", "key4"); } @Test public void testUpdateAndRemoveBinaryKeys() throws IOException, ParseException { ByteWrapper key1 = randomKey(); ByteWrapper key2 = randomKey(); ByteWrapper key3 = randomKey(); ByteWrapper key4 = randomKey(); updateAndRemove(key1, key2, key3, key4); } private void updateAndRemove(Object key1, Object key2, Object key3, Object key4) throws IOException, ParseException { repo.create(key1, new Type2("bacon maple bar", 1, 2L, 3.0, 4.0f, "Grape Ape doughnut")); repo.create(key2, new Type2("McMinnville Cream doughnut", 1, 2L, 3.0, 4.0f, "Captain my Captain doughnut")); repo.create(key3, new Type2("Voodoo Doll doughnut", 1, 2L, 3.0, 4.0f, "Toasted coconut doughnut")); repo.create(key4, new Type2("Portland Cream doughnut", 1, 2L, 3.0, 4.0f, "Captain my Captain doughnut")); repo.commit(); repo.update(key3, new Type2("Boston Cream Pie", 1, 2L, 3.0, 4.0f, "Toasted coconut doughnut")); repo.delete(key4); repo.commit(); // BooleanQuery q = new BooleanQuery(); // q.add(new TermQuery(SerializerUtil.toKeyTerm("key3")), Occur.MUST_NOT); // writer.deleteDocuments(q); // writer.commit(); //Make sure the updates and deletes were applied checkQuery("doughnut", "s", key2); checkQuery("Cream", "s", key2, key3); } private ByteWrapper randomKey() { Random rand = new Random(); int size = rand.nextInt(2048) + 50; byte[] key = new byte[size]; rand.nextBytes(key); return new ByteWrapper(key); } private void checkQuery(String queryTerm, String queryField, Object ... expectedKeys) throws IOException, ParseException { Set<Object> expectedSet = new HashSet<Object>(); expectedSet.addAll(Arrays.asList(expectedKeys)); QueryParser parser = new QueryParser(queryField, analyzer); KeyCollector collector = new KeyCollector(); repo.query(parser.parse(queryTerm), 100, collector); assertEquals(expectedSet, collector.results); } private static class KeyCollector implements IndexResultCollector { Set<Object> results = new HashSet<Object>(); @Override public void collect(Object key, float score) { results.add(key); } @Override public String getName() { return null; } @Override public int size() { return results.size(); } } /** * A wrapper around a byte array that implements equals, * for comparison checks. */ private static class ByteWrapper implements Serializable { private byte[] bytes; public ByteWrapper(byte[] bytes) { super(); this.bytes = bytes; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(bytes); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ByteWrapper other = (ByteWrapper) obj; if (!Arrays.equals(bytes, other.bytes)) return false; return true; } } }
34.92823
114
0.705616
201c4a704e984c6224a6bc042afc407b6f453b74
1,879
// Backtracking // The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. // Given an integer n, return the number of distinct solutions to the n-queens puzzle. // Example: // Input: 4 // Output: 2 // Explanation: There are two distinct solutions to the 4-queens puzzle as shown below. // [ // [".Q..", // Solution 1 // "...Q", // "Q...", // "..Q."], // ["..Q.", // Solution 2 // "Q...", // "...Q", // ".Q.."] // ] class Solution { public int totalNQueens(int n) { char[][] board = new char[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) board[i][j] = '.'; List<List<String>> res = new ArrayList<List<String>>(); dfs(board, 0, res); return res.size(); } private void dfs(char[][] board, int colIndex, List<List<String>> res) { if (colIndex == board.length) { res.add(construct(board)); return; } for (int i = 0; i < board.length; i++) { if (validate(board, i, colIndex)) { board[i][colIndex] = 'Q'; dfs(board, colIndex + 1, res); board[i][colIndex] = '.'; } } } private boolean validate(char[][] board, int x, int y) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < y; j++) { if (board[i][j] == 'Q' && (x + j == y + i || x + y == i + j || x == i)) return false; } } return true; } private List<String> construct(char[][] board) { List<String> res = new LinkedList<String>(); for (int i = 0; i < board.length; i++) { String s = new String(board[i]); res.add(s); } return res; } }
27.231884
121
0.461416
b5cb474ba148ed937bceb23f54871d6b47638d6b
4,898
/* * 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.accumulo.core.client; import static com.google.common.base.Preconditions.checkArgument; import java.util.concurrent.TimeUnit; import org.apache.accumulo.core.security.Authorizations; /** * * @since 1.6.0 */ public class ConditionalWriterConfig { private static final Long DEFAULT_TIMEOUT = Long.MAX_VALUE; private Long timeout = null; private static final Integer DEFAULT_MAX_WRITE_THREADS = 3; private Integer maxWriteThreads = null; private Authorizations auths = Authorizations.EMPTY; private Durability durability = Durability.DEFAULT; /** * A set of authorization labels that will be checked against the column visibility of each key in order to filter data. The authorizations passed in must be * a subset of the accumulo user's set of authorizations. If the accumulo user has authorizations (A1, A2) and authorizations (A2, A3) are passed, then an * exception will be thrown. * * <p> * Any condition that is not visible with this set of authorizations will fail. */ public ConditionalWriterConfig setAuthorizations(Authorizations auths) { checkArgument(auths != null, "auths is null"); this.auths = auths; return this; } /** * Sets the maximum amount of time an unresponsive server will be re-tried. When this timeout is exceeded, the {@link ConditionalWriter} should return the * mutation with an exception.<br /> * For no timeout, set to zero, or {@link Long#MAX_VALUE} with {@link TimeUnit#MILLISECONDS}. * * <p> * {@link TimeUnit#MICROSECONDS} or {@link TimeUnit#NANOSECONDS} will be truncated to the nearest {@link TimeUnit#MILLISECONDS}.<br /> * If this truncation would result in making the value zero when it was specified as non-zero, then a minimum value of one {@link TimeUnit#MILLISECONDS} will * be used. * * <p> * <b>Default:</b> {@link Long#MAX_VALUE} (no timeout) * * @param timeout * the timeout, in the unit specified by the value of {@code timeUnit} * @param timeUnit * determines how {@code timeout} will be interpreted * @throws IllegalArgumentException * if {@code timeout} is less than 0 * @return {@code this} to allow chaining of set methods */ public ConditionalWriterConfig setTimeout(long timeout, TimeUnit timeUnit) { if (timeout < 0) throw new IllegalArgumentException("Negative timeout not allowed " + timeout); if (timeout == 0) this.timeout = Long.MAX_VALUE; else // make small, positive values that truncate to 0 when converted use the minimum millis instead this.timeout = Math.max(1, timeUnit.toMillis(timeout)); return this; } /** * Sets the maximum number of threads to use for writing data to the tablet servers. * * <p> * <b>Default:</b> 3 * * @param maxWriteThreads * the maximum threads to use * @throws IllegalArgumentException * if {@code maxWriteThreads} is non-positive * @return {@code this} to allow chaining of set methods */ public ConditionalWriterConfig setMaxWriteThreads(int maxWriteThreads) { if (maxWriteThreads <= 0) throw new IllegalArgumentException("Max threads must be positive " + maxWriteThreads); this.maxWriteThreads = maxWriteThreads; return this; } /** * Sets the Durability for the mutation, if applied. * <p> * <b>Default:</b> Durability.DEFAULT: use the table's durability configuration. * * @return {@code this} to allow chaining of set methods * @since 1.7.0 */ public ConditionalWriterConfig setDurability(Durability durability) { this.durability = durability; return this; } public Authorizations getAuthorizations() { return auths; } public long getTimeout(TimeUnit timeUnit) { return timeUnit.convert(timeout != null ? timeout : DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); } public int getMaxWriteThreads() { return maxWriteThreads != null ? maxWriteThreads : DEFAULT_MAX_WRITE_THREADS; } public Durability getDurability() { return durability; } }
35.751825
159
0.711923
8901544ada09413edc884e7ebe2f85178167c94f
4,857
/* * ========================================================================== * Copyright (C) 2019-2021 HCL America, Inc. ( http://www.hcl.com/ ) * All rights reserved. * ========================================================================== * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. You may obtain a * copy of the License at <http://www.apache.org/licenses/LICENSE-2.0>. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ========================================================================== */ package com.hcl.domino.jnx.example.domino.webapp.admin.console; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.sse.Sse; import javax.ws.rs.sse.SseBroadcaster; import javax.ws.rs.sse.SseEventSink; import com.hcl.domino.DominoClient; import com.hcl.domino.DominoClientBuilder; import com.hcl.domino.admin.IConsoleLine; import com.hcl.domino.admin.ServerAdmin.ConsoleHandler; import com.hcl.domino.exception.CancelException; import com.hcl.domino.jnx.example.domino.webapp.admin.RestEasyServlet; import com.hcl.domino.mq.MessageQueue; import jakarta.json.bind.JsonbBuilder; @Path("console") public class ConsoleResource { private static class SseConsoleHandler implements ConsoleHandler, AutoCloseable { private final Sse sse; private final SseBroadcaster sseBroadcaster; private final long opened = System.currentTimeMillis(); private boolean shouldStop; private final DominoClient dominoClient; private final MessageQueue httpQueue; public SseConsoleHandler(final Sse sse, final SseBroadcaster sseBroadcaster) { this.sse = sse; this.sseBroadcaster = sseBroadcaster; this.dominoClient = DominoClientBuilder.newDominoClient().build(); this.httpQueue = this.dominoClient.getMessageQueues().open("MQ$HTTP", false); //$NON-NLS-1$ this.sseBroadcaster.onClose(sink -> this.close()); } @Override public void close() { this.shouldStop = true; this.httpQueue.close(); this.dominoClient.close(); } @Override public void messageReceived(final IConsoleLine line) { final UUID eventId = UUID.randomUUID(); final String json = JsonbBuilder.create().toJson(line); this.sseBroadcaster.broadcast(this.sse.newEventBuilder() .name("logline") //$NON-NLS-1$ .id(eventId.toString()) .mediaType(MediaType.APPLICATION_JSON_TYPE) .data(String.class, json) .reconnectDelay(250) .build()); } @Override public boolean shouldStop() { if (this.httpQueue.isQuitPending() || this.shouldStop || Thread.currentThread().isInterrupted()) { return true; } final boolean timedOut = System.currentTimeMillis() > this.opened + TimeUnit.HOURS.toMillis(1); if (timedOut) { return true; } return false; } } @GET @Produces(MediaType.SERVER_SENT_EVENTS) public void getConsoleOutput(@Context final SseEventSink sseEventSink, @Context final Sse sse, @QueryParam("serverName") final String serverName) throws InterruptedException, ExecutionException { RestEasyServlet.instance.executor.submit(() -> { try (SseBroadcaster broadcaster = sse.newBroadcaster(); SseConsoleHandler handler = new SseConsoleHandler(sse, broadcaster)) { broadcaster.register(sseEventSink); try (DominoClient dominoClient = DominoClientBuilder.newDominoClient().build()) { dominoClient.getServerAdmin().openServerConsole(serverName, handler); } catch (final CancelException e) { // Expected when shutting down } catch (final Throwable t) { t.printStackTrace(); } finally { sseEventSink.close(); } } }).get(); } @POST @Produces(MediaType.TEXT_PLAIN) public String sendCommand(@FormParam("serverName") final String serverName, @FormParam("command") final String command) throws InterruptedException, ExecutionException { return RestEasyServlet.instance.executor .submit(() -> RestEasyServlet.instance.dominoClient.getServerAdmin().sendConsoleCommand(serverName, command)).get(); } }
37.945313
132
0.676343
6abdb3fac61767b4ffe884efea0e3bc96b58c810
157
package demo.benchmarks.ModDiffEq.Add; public class oldV { public static double snippet(int a, int b) { int c = a + b; return c; } }
19.625
48
0.598726
374e8b7674c541c390fefe0192acb4353244de97
4,525
package com.ljs.ifootballmanager.ai.report; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.ljs.ifootballmanager.ai.Role; import com.ljs.ifootballmanager.ai.Tactic; import com.ljs.ifootballmanager.ai.formation.Formation; import com.ljs.ifootballmanager.ai.player.Player; import com.ljs.ifootballmanager.ai.player.Squad; import java.io.PrintWriter; /** @author lstephen */ public class SquadSummaryReport implements Report { private final Squad squad; private final Formation firstXI; private final Optional<Formation> secondXI; private final Optional<Formation> reservesXI; private SquadSummaryReport(Builder builder) { this.squad = builder.squad; this.firstXI = builder.firstXI; this.secondXI = builder.secondXI; this.reservesXI = builder.reservesXI; } private Long getMax(Role r, Tactic t, Iterable<Player> ps) { return Math.round(Player.byRating(r, t).max(ps).getRating(r, t)); } private Long getMin(Role r, Iterable<Player> ps) { return getMin(r, Tactic.NORMAL, ps); } private Long getMin(Role r, Tactic t, Iterable<Player> ps) { return Math.round(Player.byRating(r, t).min(ps).getRating(r, t)); } public void print(PrintWriter w) { Role[] roles = Role.values(); w.format("%28s ", ""); for (Role r : roles) { w.format("%5s ", r.name()); } w.println(); w.format("%28s ", "Count"); for (Role r : roles) { w.format("%5s ", squad.count(r)); } w.println(); w.format("%28s ", "Max"); for (Role r : roles) { w.format("%5s ", getMax(r, Tactic.NORMAL, squad.players())); } w.println(); w.format("%28s ", "1st XI (N)"); for (Role r : roles) { ImmutableSet<Player> ps = firstXI.players(r); w.format("%5s ", ps.isEmpty() ? "" : getMin(r, ps)); } w.println(); w.format("%28s ", "1st XI (" + firstXI.getTactic().getCode() + ")"); for (Role r : roles) { ImmutableSet<Player> ps = firstXI.players(r); w.format("%5s ", ps.isEmpty() ? "" : getMin(r, firstXI.getTactic(), ps)); } w.println(); if (secondXI.isPresent()) { w.format("%28s ", "2nd XI (N)"); for (Role r : roles) { ImmutableSet<Player> ps = secondXI.get().players(r); w.format("%5s ", ps.isEmpty() ? "" : getMin(r, ps)); } w.println(); w.format("%28s ", "2nd XI (" + secondXI.get().getTactic().getCode() + ")"); for (Role r : roles) { ImmutableSet<Player> ps = secondXI.get().players(r); w.format("%5s ", ps.isEmpty() ? "" : getMin(r, secondXI.get().getTactic(), ps)); } w.println(); } if (reservesXI.isPresent()) { w.format("%28s ", "Reserves (N)"); for (Role r : roles) { ImmutableSet<Player> ps = reservesXI.get().players(r); w.format("%5s ", ps.isEmpty() ? "" : getMin(r, ps)); } w.println(); w.format("%28s ", "Reserves (" + reservesXI.get().getTactic().getCode() + ")"); for (Role r : roles) { ImmutableSet<Player> ps = reservesXI.get().players(r); w.format("%5s ", ps.isEmpty() ? "" : getMin(r, reservesXI.get().getTactic(), ps)); } w.println(); } w.format("%28s%n", "Min"); for (Tactic t : Tactic.values()) { w.format("%28s ", t); for (Role r : roles) { ImmutableSet<Player> ps = squad.players(r, t); w.format("%5s ", ps.isEmpty() ? "" : getMin(r, t, ps)); } w.println(); } } public static Builder builder() { return Builder.create(); } private static SquadSummaryReport build(Builder builder) { return new SquadSummaryReport(builder); } public static class Builder { private Squad squad; private Formation firstXI; private Optional<Formation> secondXI = Optional.absent(); private Optional<Formation> reservesXI = Optional.absent(); private Builder() {} public Builder squad(Squad squad) { this.squad = squad; return this; } public Builder firstXI(Formation f) { this.firstXI = f; return this; } public Builder secondXI(Formation f) { secondXI = Optional.fromNullable(f); return this; } public Builder reservesXI(Formation f) { reservesXI = Optional.fromNullable(f); return this; } public SquadSummaryReport build() { return SquadSummaryReport.build(this); } private static Builder create() { return new Builder(); } } }
26.005747
90
0.598674
e39fda572e5166fc6b56e5f6dcba12d45f08b9fe
3,717
package uk.gov.gds.performance.collector.logging; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Arrays; import java.util.List; public class GenerateLogMessageDocumentation { public static void main(String... args) throws Exception { String head = args[0]; String[] tail = Arrays.copyOfRange(args, 1, args.length); new GenerateLogMessageDocumentation(head, tail).generate(); } private final File outputFile; private final List<String> classFoldersToDocument; GenerateLogMessageDocumentation(String outputFile, String... classFoldersToDocument) { this.outputFile = new File(outputFile); this.classFoldersToDocument = Arrays.asList(classFoldersToDocument); } public void generate() throws Exception { try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)))) { for(String it : classFoldersToDocument) { final Holder<Boolean> logMessageImplementationFound = new Holder<>(false); final Path classFolder = Paths.get(it); Files.walkFileTree(classFolder, new SimpleFileVisitor<Path>() { @SuppressWarnings("NullableProblems") @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!file.toString().endsWith(".class")) { return super.visitFile(file, attrs); } Path relativePath = classFolder.relativize(file); String className = toClassName(relativePath); try { Class<?> clazz = Class.forName(className); if (isValidClass(clazz)) { logMessageImplementationFound.set(true); documentLogMessageEnum(out, clazz); } } catch (ClassNotFoundException e) { //this is an inner class, or not a class, etc } return super.visitFile(file, attrs); } }); if (!logMessageImplementationFound.get()) { throw new RuntimeException("No LogMessage implementations found in " + classFolder.toString()); } } } } private String toClassName(Path relativePath) { String classNameWithDotClassExtension = relativePath.toString().replace('/', '.').replace('$', '.'); return classNameWithDotClassExtension.substring(0, (classNameWithDotClassExtension.length() - ".class".length())); } private void documentLogMessageEnum(PrintWriter out, Class<?> clazz) { out.print(clazz.getName()); out.println(":"); out.println("Code\t\tMessage"); out.println("==========\t=========="); for(Object o : clazz.getEnumConstants()) { LogMessage message = (LogMessage) o; out.printf("%s\t%s\n", message.getMessageCode(), message.getMessagePattern()); } out.println(); } private boolean isValidClass(Class<?> clazz) { return clazz.isEnum() && LogMessage.class.isAssignableFrom(clazz); } private static class Holder<T> { private T instance; private Holder(T instance) { this.instance = instance; } public void set(T value) { instance = value; } public T get() { return instance; } } }
37.17
122
0.569276
02d30ee6a51b846d2815fb7b91b8fba9685465d6
577
package cn.zelkova.lockprotocol; /** * 设置同步开门密码指令 * * @author lwq * Created by liwenqi on 2016/6/25. */ public class LockCommSyncPwd extends LockCommBase { /** * @param cmd 从服务器获得的设置开门密码命令 */ public LockCommSyncPwd(byte[] cmd) { super.mKLVList.add((byte) 0x01, cmd); } @Override public short getCmdId() { return 0x0A; } @Override public String getCmdName() { return "SyncPwd"; } @Override public boolean needSessionToken() { return false; } }
16.970588
52
0.559792
742ed21657881aa567bbc2cb528767f35cdaf4b4
1,568
/* * Copyright 2010-2013 Ning, Inc. * * Ning 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.asynchttpclient.providers.netty.request.body; import org.asynchttpclient.FluentCaseInsensitiveStringsMap; import org.asynchttpclient.multipart.MultipartBody; import org.asynchttpclient.multipart.MultipartUtils; import org.asynchttpclient.multipart.Part; import org.asynchttpclient.providers.netty.NettyAsyncHttpProviderConfig; import java.util.List; public class NettyMultipartBody extends NettyBodyBody { private final String contentType; public NettyMultipartBody(List<Part> parts, FluentCaseInsensitiveStringsMap headers, NettyAsyncHttpProviderConfig nettyConfig) { this(MultipartUtils.newMultipartBody(parts, headers), nettyConfig); } private NettyMultipartBody(MultipartBody body, NettyAsyncHttpProviderConfig nettyConfig) { super(body, nettyConfig); contentType = body.getContentType(); } @Override public String getContentType() { return contentType; } }
35.636364
132
0.769133
8afcd7b9c58af542d1d70d751ee7b0ab8270f7a8
356
package br.com.erudio; public class HelloDocker { private final String content; private final String environment; public HelloDocker(String content, String environment) { this.content = content; this.environment = environment; } public String getContent() { return content; } public String getEnvironment() { return environment; } }
16.952381
57
0.738764
1433f702c186a7e1d82b0dff90ce8aa93c47d82b
4,081
package org.pikater.shared.database.jpa.daos; import java.util.List; import javax.persistence.TypedQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.pikater.shared.database.jpa.EntityManagerInstancesCreator; import org.pikater.shared.database.jpa.JPAExternalAgent; import org.pikater.shared.database.jpa.JPAUser; import org.pikater.shared.database.views.base.ITableColumn; import org.pikater.shared.database.views.base.query.SortOrder; import org.pikater.shared.database.views.tableview.externalagents.ExternalAgentTableDBView; public class ExternalAgentDAO extends AbstractDAO<JPAExternalAgent> { public ExternalAgentDAO() { super(JPAExternalAgent.class); } @Override public String getEntityName() { return JPAExternalAgent.EntityName; } protected Path<Object> convertColumnToJPAParam(ITableColumn column) { Root<JPAExternalAgent> root = getRoot(); switch ((ExternalAgentTableDBView.Column) column) { case CREATED: case DESCRIPTION: case NAME: return root.get(column.toString().toLowerCase()); case AGENT_CLASS: return root.get("agentClass"); case OWNER: return root.get("owner").get("login"); default: return root.get("created"); } } public List<JPAExternalAgent> getAll(int offset, int maxResultCount, ITableColumn sortColumn, SortOrder sortOrder) { return getByCriteriaQuery(sortColumn, sortOrder, offset, maxResultCount); } private Predicate createByVisibilityPredicate(boolean agentVisibility) { return getCriteriaBuilder().equal(getRoot().get("visible"), agentVisibility); } public List<JPAExternalAgent> getByVisibility(int offset, int maxResultCount, ITableColumn sortColumn, SortOrder sortOrder, boolean agentVisibility) { return getByCriteriaQuery(createByVisibilityPredicate(agentVisibility), sortColumn, sortOrder, offset, maxResultCount); } public int getByVisibilityCount(boolean agentVisibility) { return getByCriteriaQueryCount(createByVisibilityPredicate(agentVisibility)); } private Predicate createByOwnerAndVisibilityPredicate(JPAUser owner, boolean agentVisibility) { return getCriteriaBuilder().and(getCriteriaBuilder().equal(getRoot().get("owner"), owner), getCriteriaBuilder().equal(getRoot().get("visible"), agentVisibility)); } public List<JPAExternalAgent> getByOwnerAndVisibility(JPAUser owner, int offset, int maxResultCount, ITableColumn sortColumn, SortOrder sortOrder, boolean agentVisibility) { return getByCriteriaQuery(createByOwnerAndVisibilityPredicate(owner, agentVisibility), sortColumn, sortOrder, offset, maxResultCount); } public int getByOwnerAndVisibilityCount(JPAUser owner, boolean agentVisibility) { return getByCriteriaQueryCount(createByOwnerAndVisibilityPredicate(owner, agentVisibility)); } public int getAllCount() { return ((Long) EntityManagerInstancesCreator.getEntityManagerInstance().createNamedQuery("ExternalAgent.getAll.count").getSingleResult()).intValue(); } public List<JPAExternalAgent> getAll(int offset, int maxResultSize) { TypedQuery<JPAExternalAgent> tq = EntityManagerInstancesCreator.getEntityManagerInstance().createNamedQuery("ExternalAgent.getAll", JPAExternalAgent.class); tq.setMaxResults(maxResultSize); tq.setFirstResult(offset); return tq.getResultList(); } public List<JPAExternalAgent> getByOwner(JPAUser user) { return getByTypedNamedQuery("ExternalAgent.getByOwner", "owner", user); } public int getByOwnerCount(JPAUser user) { return ((Long) EntityManagerInstancesCreator.getEntityManagerInstance().createNamedQuery("ExternalAgent.getByOwner.count").setParameter("owner", user).getSingleResult()).intValue(); } public JPAExternalAgent getByAgentClass(String agentClass) { return getSingleResultByTypedNamedQuery("ExternalAgent.getByAgentClass", "agentClass", agentClass); } public void deleteExternalAgentEntity(JPAExternalAgent externalAgent) { this.deleteExternalAgentByID(externalAgent.getId()); } public void deleteExternalAgentByID(int id) { this.deleteEntityByID(id); } }
39.240385
183
0.807645
90912d1e88d8fcc40e50093f86b9ed0b4035ae48
3,603
package unalcol.optimization.testbed.real.lsgo_benchmark; /* * Copyright (c) 2009 Thomas Weise for NICAL * http://www.it-weise.de/ * [email protected] * * GNU LESSER GENERAL PUBLIC LICENSE (Version 2.1, February 1999) */ /** * <p> * The D/m-group group Shifted and m-rotated Elliptic Function: F14. * </p> * <p> * This function is not <warning>not threadsafe</warning> because it uses * internal temporary variables. Therefore, you should always use each * instance of this function for one single {#link java.lang.Thread} only. * You may clone or serialize function instances to use multiple threads. * <p> * * @author Thomas Weise */ public final class F14 extends ShiftedPermutatedRotatedFunction { /** the serial version id */ private static final long serialVersionUID = 1; /** the maximum value */ public static final double MAX = 100d; /** the minimum value */ public static final double MIN = (-MAX); /** the lookup table */ private final double[] m_lookup; /** * Create a new D/m-group group Shifted and m-rotated Elliptic Function * * @param o * the shifted global optimum * @param p * the permutation vector * @param m * the rotation matrix */ public F14(final double[] o, final int[] p, final double[] m) { super(o, p, m, MIN, MAX); this.m_lookup = Kernel.createPowLookup(this.m_matDim); } /** * Create a default instance of F14. * * @param r * the randomizer to use */ public F14(final Randomizer r) { this(r.createShiftVector(Defaults.DEFAULT_DIM, MIN, MAX),// r.createPermVector(Defaults.DEFAULT_DIM),// r.createRotMatrix1D(Defaults.DEFAULT_M));// } /** * Create a default instance of F14. */ public F14() { this(Defaults.getRandomizer(F14.class)); } /** * Compute the value of the elliptic function. This function takes into * consideration only the first {{@link #getDimension()} elements of the * candidate vector. * * @param x * the candidate solution vector * @return the value of the function */ // @Override public final double compute(final double[] x) { final int max, gs, d; double s; int i, e; gs = this.m_matDim; d = this.m_dimension; max = (d / gs); s = 0d; e = 0; for (i = 0; i < max; i++) { s += Kernel.shiftedPermRotElliptic(x, this.m_o, this.m_p, this.m_m,// e, gs, this.m_tmp, this.m_lookup); // e += gs; } return (s /* * + Kernel.shiftedPermElliptic(x, this.m_o, this.m_p, e, * this.m_dimension - e) */); } /** * Obtain the full name of the benchmark function (according to * &quot;Benchmark Functions for the CEC�2010 Special Session and * Competition on Large-Scale Global Optimization&quot; Ke Tang, Xiaodong * Li, P. N. Suganthan, Zhenyu Yang, and Thomas Weise CEC'2010) * * @return the full name of the benchmark function */ // @Override public final String getFullName() { return "D/m-group group Shifted and m-rotated Elliptic Function";//$NON-NLS-1$ } /** * Obtain the short name of the benchmark function (according to * &quot;Benchmark Functions for the CEC�2010 Special Session and * Competition on Large-Scale Global Optimization&quot; Ke Tang, Xiaodong * Li, P. N. Suganthan, Zhenyu Yang, and Thomas Weise CEC'2010) * * @return the short name of the benchmark function */ // @Override public final String getShortName() { return "F14"; //$NON-NLS-1$ } }
27.715385
82
0.635859
1bba7e574398b9bd3868e78307576f84ff3780bb
649
package tutby; import com.qaprosoft.carina.core.gui.AbstractPage; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.FindBy; import tutby.components.SearchResult; import java.util.List; public class SearchResultsPage extends AbstractPage { @FindBy(xpath = "//*[@class=\"b-results-list\"]/li") private List<SearchResult> searchResults; public SearchResultsPage(WebDriver driver) { super(driver); } public SearchResultsPage(AbstractPage abstractPage) { super(abstractPage.getDriver()); } public List<SearchResult> getSearchResults() { return searchResults; } }
22.37931
57
0.718028
f4cf14a4e53733122a839fa80227fc437beb1d69
486
/* (c) https://github.com/MontiCore/monticore */ package de.monticore.types; import de.monticore.generating.templateengine.reporting.commons.Layouter; import de.monticore.types.mcarraytypes._ast.ASTMCArrayType; /** * NodeIdentHelper for MCArrayTypes, mainly used for Reporting */ public class MCArrayTypesNodeIdentHelper extends MCBasicTypesNodeIdentHelper { public String getIdent(ASTMCArrayType a){ return format(a.printTypeWithoutBrackets(), Layouter.nodeName(a)); } }
28.588235
78
0.794239
6a87ce204ae98b97c3587876a015b65aeb66b38d
20,407
/* * 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.hop.pipeline.transforms.multimerge; import org.apache.hop.core.Const; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.row.IRowMeta; import org.apache.hop.core.util.Utils; import org.apache.hop.core.variables.IVariables; import org.apache.hop.i18n.BaseMessages; import org.apache.hop.pipeline.PipelineMeta; import org.apache.hop.pipeline.transform.BaseTransformMeta; import org.apache.hop.pipeline.transform.ITransformDialog; import org.apache.hop.pipeline.transform.ITransformIOMeta; import org.apache.hop.pipeline.transform.TransformMeta; import org.apache.hop.pipeline.transform.stream.IStream; import org.apache.hop.pipeline.transform.stream.IStream.StreamType; import org.apache.hop.pipeline.transform.stream.Stream; import org.apache.hop.pipeline.transform.stream.StreamIcon; import org.apache.hop.ui.core.dialog.BaseDialog; import org.apache.hop.ui.core.dialog.MessageDialogWithToggle; import org.apache.hop.ui.core.gui.GuiResource; import org.apache.hop.ui.core.widget.ColumnInfo; import org.apache.hop.ui.core.widget.TableView; import org.apache.hop.ui.pipeline.transform.BaseTransformDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.*; import java.util.List; import java.util.*; public class MultiMergeJoinDialog extends BaseTransformDialog implements ITransformDialog { private static final Class<?> PKG = MultiMergeJoinMeta.class; // For Translator public static final String STRING_SORT_WARNING_PARAMETER = "MultiMergeJoinSortWarning"; private final CCombo[] wInputTransformArray; private CCombo joinTypeCombo; private final Text[] keyValTextBox; private Map<String, Integer> inputFields; private IRowMeta prev; private ColumnInfo[] ciKeys; private final int margin = props.getMargin(); private final int middle = props.getMiddlePct(); private final MultiMergeJoinMeta joinMeta; public MultiMergeJoinDialog( Shell parent, IVariables variables, Object in, PipelineMeta tr, String sname) { super(parent, variables, (BaseTransformMeta) in, tr, sname); joinMeta = (MultiMergeJoinMeta) in; String[] inputTransformNames = getInputTransformNames(); wInputTransformArray = new CCombo[inputTransformNames.length]; keyValTextBox = new Text[inputTransformNames.length]; } private String[] getInputTransformNames() { String[] inputTransformNames = joinMeta.getInputTransforms(); ArrayList<String> nameList = new ArrayList<>(); if (inputTransformNames != null) { Collections.addAll(nameList, inputTransformNames); } String[] prevTransformNames = pipelineMeta.getPrevTransformNames(transformName); if (prevTransformNames != null) { String prevTransformName; for (String name : prevTransformNames) { prevTransformName = name; if (nameList.contains(prevTransformName)) { continue; } nameList.add(prevTransformName); } } return nameList.toArray(new String[nameList.size()]); } /* * (non-Javadoc) * * @see org.apache.hop.pipeline.transform.ITransformDialog#open() */ @Override public String open() { Shell parent = getParent(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX); props.setLook(shell); setShellImage(shell, joinMeta); final ModifyListener lsMod = e -> joinMeta.setChanged(); backupChanged = joinMeta.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "MultiMergeJoinDialog.Shell.Label")); wlTransformName = new Label(shell, SWT.RIGHT); wlTransformName.setText( BaseMessages.getString(PKG, "MultiMergeJoinDialog.TransformName.Label")); props.setLook(wlTransformName); fdlTransformName = new FormData(); fdlTransformName.left = new FormAttachment(0, 0); fdlTransformName.right = new FormAttachment(middle, -margin); fdlTransformName.top = new FormAttachment(0, margin); wlTransformName.setLayoutData(fdlTransformName); wTransformName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wTransformName.setText(transformName); props.setLook(wTransformName); wTransformName.addModifyListener(lsMod); fdTransformName = new FormData(); fdTransformName.left = new FormAttachment(wlTransformName, margin); fdTransformName.top = new FormAttachment(wlTransformName, 0, SWT.CENTER); fdTransformName.right = new FormAttachment(100, 0); wTransformName.setLayoutData(fdTransformName); // create widgets for input stream and join key selections createInputStreamWidgets(lsMod); // create widgets for Join type createJoinTypeWidget(lsMod); // Some buttons wOk = new Button(shell, SWT.PUSH); wOk.setText(BaseMessages.getString(PKG, "System.Button.OK")); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); setButtonPositions(new Button[] {wOk, wCancel}, margin, null); // Add listeners wCancel.addListener(SWT.Selection, e -> cancel()); wOk.addListener(SWT.Selection, e -> ok()); // get the data getData(); joinMeta.setChanged(backupChanged); BaseDialog.defaultShellHandling(shell, c -> ok(), c -> cancel()); return transformName; } /** * Create widgets for join type selection * * @param lsMod */ private void createJoinTypeWidget(final ModifyListener lsMod) { Label joinTypeLabel = new Label(shell, SWT.RIGHT); joinTypeLabel.setText(BaseMessages.getString(PKG, "MultiMergeJoinDialog.Type.Label")); props.setLook(joinTypeLabel); FormData fdlType = new FormData(); fdlType.left = new FormAttachment(0, 0); fdlType.right = new FormAttachment(middle, -margin); if (wInputTransformArray.length > 0) { fdlType.top = new FormAttachment(wInputTransformArray[wInputTransformArray.length - 1], margin * 3); } else { fdlType.top = new FormAttachment(wTransformName, margin * 3); } joinTypeLabel.setLayoutData(fdlType); joinTypeCombo = new CCombo(shell, SWT.BORDER); props.setLook(joinTypeCombo); joinTypeCombo.setItems(MultiMergeJoinMeta.joinTypes); joinTypeCombo.addModifyListener(lsMod); FormData fdType = new FormData(); fdType.top = new FormAttachment(joinTypeLabel, 0, SWT.CENTER); fdType.left = new FormAttachment(joinTypeLabel, margin); fdType.right = new FormAttachment(60, 0); joinTypeCombo.setLayoutData(fdType); } /** * create widgets for input stream and join keys * * @param lsMod */ private void createInputStreamWidgets(final ModifyListener lsMod) { // Get the previous transforms ... String[] inputTransforms = getInputTransformNames(); for (int index = 0; index < inputTransforms.length; index++) { Label wlTransform; FormData fdlTransform; FormData fdTransform1; wlTransform = new Label(shell, SWT.RIGHT); wlTransform.setText( BaseMessages.getString(PKG, "MultiMergeJoinMeta.InputTransform") + (index + 1)); props.setLook(wlTransform); fdlTransform = new FormData(); fdlTransform.left = new FormAttachment(0, 0); fdlTransform.right = new FormAttachment(middle, -margin); if (index == 0) { fdlTransform.top = new FormAttachment(wTransformName, margin * 3); } else { fdlTransform.top = new FormAttachment(wInputTransformArray[index - 1], margin * 3); } wlTransform.setLayoutData(fdlTransform); wInputTransformArray[index] = new CCombo(shell, SWT.BORDER); props.setLook(wInputTransformArray[index]); wInputTransformArray[index].setItems(inputTransforms); wInputTransformArray[index].addModifyListener(lsMod); fdTransform1 = new FormData(); fdTransform1.left = new FormAttachment(wlTransform, margin); fdTransform1.top = new FormAttachment(wlTransform, 0, SWT.CENTER); fdTransform1.right = new FormAttachment(60); wInputTransformArray[index].setLayoutData(fdTransform1); Label keyLabel = new Label(shell, SWT.LEFT); keyLabel.setText(BaseMessages.getString(PKG, "MultiMergeJoinMeta.JoinKeys")); props.setLook(keyLabel); FormData keyTransform = new FormData(); keyTransform.left = new FormAttachment(wInputTransformArray[index], margin * 2); keyTransform.top = new FormAttachment(wlTransform, 0, SWT.CENTER); keyLabel.setLayoutData(keyTransform); keyValTextBox[index] = new Text(shell, SWT.READ_ONLY | SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(keyValTextBox[index]); keyValTextBox[index].setText(""); keyValTextBox[index].addModifyListener(lsMod); FormData keyData = new FormData(); keyData.left = new FormAttachment(keyLabel, margin); keyData.top = new FormAttachment(wlTransform, 0, SWT.CENTER); keyValTextBox[index].setLayoutData(keyData); Button button = new Button(shell, SWT.PUSH); button.setText(BaseMessages.getString(PKG, "MultiMergeJoinMeta.SelectKeys")); // add listener button.addListener( SWT.Selection, new ConfigureKeyButtonListener(this, keyValTextBox[index], index, lsMod)); FormData buttonData = new FormData(); buttonData.right = new FormAttachment(100, -margin); buttonData.top = new FormAttachment(wlTransform, 0, SWT.CENTER); button.setLayoutData(buttonData); keyData.right = new FormAttachment(button, -margin); } } /** * "Configure join key" shell * * @param keyValTextBox * @param lsMod */ private void configureKeys( final Text keyValTextBox, final int inputStreamIndex, ModifyListener lsMod) { inputFields = new HashMap<>(); final Shell subShell = new Shell(shell, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX); final FormLayout formLayout = new FormLayout(); formLayout.marginWidth = 5; formLayout.marginHeight = 5; subShell.setLayout(formLayout); subShell.setMinimumSize(300, 300); subShell.setSize(400, 300); subShell.setText(BaseMessages.getString(PKG, "MultiMergeJoinMeta.JoinKeys")); subShell.setImage(GuiResource.getInstance().getImageHop()); Label wlKeys = new Label(subShell, SWT.NONE); wlKeys.setText(BaseMessages.getString(PKG, "MultiMergeJoinDialog.Keys")); FormData fdlKeys = new FormData(); fdlKeys.left = new FormAttachment(0, 0); fdlKeys.right = new FormAttachment(50, -margin); fdlKeys.top = new FormAttachment(0, margin); wlKeys.setLayoutData(fdlKeys); String[] keys = keyValTextBox.getText().split(","); int nrKeyRows = (keys != null ? keys.length : 1); ciKeys = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString(PKG, "MultiMergeJoinDialog.ColumnInfo.KeyField"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] {""}, false), }; final TableView wKeys = new TableView( variables, subShell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL, ciKeys, nrKeyRows, lsMod, props); FormData fdKeys = new FormData(); fdKeys.top = new FormAttachment(wlKeys, margin); fdKeys.left = new FormAttachment(0, 0); fdKeys.bottom = new FormAttachment(100, -70); fdKeys.right = new FormAttachment(100, -margin); wKeys.setLayoutData(fdKeys); // // Search the fields in the background final Runnable runnable = () -> { try { CCombo wInputTransform = wInputTransformArray[inputStreamIndex]; String transformName = wInputTransform.getText(); TransformMeta transformMeta = pipelineMeta.findTransform(transformName); if (transformMeta != null) { prev = pipelineMeta.getTransformFields(variables, transformMeta); if (prev != null) { // Remember these fields... for (int i = 0; i < prev.size(); i++) { inputFields.put(prev.getValueMeta(i).getName(), Integer.valueOf(i)); } setComboBoxes(); } } } catch (HopException e) { logError(BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message")); } }; Display.getDefault().asyncExec(runnable); Button getKeyButton = new Button(subShell, SWT.PUSH); getKeyButton.setText(BaseMessages.getString(PKG, "MultiMergeJoinDialog.KeyFields.Button")); FormData fdbKeys = new FormData(); fdbKeys.top = new FormAttachment(wKeys, margin); fdbKeys.left = new FormAttachment(0, 0); fdbKeys.right = new FormAttachment(100, -margin); getKeyButton.setLayoutData(fdbKeys); getKeyButton.addListener(SWT.Selection, e -> { BaseTransformDialog.getFieldsFromPrevious( prev, wKeys, 1, new int[] {1}, new int[] {}, -1, -1, null); }); Listener onOk = (e) -> { int nrKeys = wKeys.nrNonEmpty(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < nrKeys; i++) { TableItem item = wKeys.getNonEmpty(i); sb.append(item.getText(1)); if (nrKeys > 1 && i != nrKeys - 1) { sb.append(","); } } keyValTextBox.setText(sb.toString()); subShell.close(); }; // Some buttons Button okButton = new Button(subShell, SWT.PUSH); okButton.setText(BaseMessages.getString(PKG, "System.Button.OK")); okButton.addListener(SWT.Selection, onOk); Button cancelButton = new Button(subShell, SWT.PUSH); cancelButton.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); cancelButton.addListener(SWT.Selection, e -> subShell.close()); this.setButtonPositions(new Button[] {okButton, cancelButton}, margin, null); for (int i = 0; i < keys.length; i++) { TableItem item = wKeys.table.getItem(i); if (keys[i] != null) { item.setText(1, keys[i]); } } BaseDialog.defaultShellHandling(subShell, x-> onOk.handleEvent(null), x -> {}); } protected void setComboBoxes() { // Something was changed in the row. // final Map<String, Integer> fields = new HashMap<>(); // Add the currentMeta fields... fields.putAll(inputFields); Set<String> keySet = fields.keySet(); List<String> entries = new ArrayList<>(keySet); String[] fieldNames = entries.toArray(new String[entries.size()]); Const.sortStrings(fieldNames); ciKeys[0].setComboValues(fieldNames); } /** Copy information from the meta-data input to the dialog fields. */ public void getData() { String[] inputTransformNames = joinMeta.getInputTransforms(); if (inputTransformNames != null) { String inputTransformName; String[] keyFields = joinMeta.getKeyFields(); String keyField; for (int i = 0; i < inputTransformNames.length; i++) { inputTransformName = Const.NVL(inputTransformNames[i], ""); wInputTransformArray[i].setText(inputTransformName); keyField = Const.NVL(i < keyFields.length ? keyFields[i] : null, ""); keyValTextBox[i].setText(keyField); } String joinType = joinMeta.getJoinType(); if (joinType != null && joinType.length() > 0) { joinTypeCombo.setText(joinType); } else { joinTypeCombo.setText(MultiMergeJoinMeta.joinTypes[0]); } } wTransformName.selectAll(); wTransformName.setFocus(); } private void cancel() { transformName = null; joinMeta.setChanged(backupChanged); dispose(); } /** * Get the meta data * * @param meta */ private void getMeta(MultiMergeJoinMeta meta) { ITransformIOMeta transformIOMeta = meta.getTransformIOMeta(); List<IStream> infoStreams = transformIOMeta.getInfoStreams(); IStream stream; String streamDescription; ArrayList<String> inputTransformNameList = new ArrayList<>(); ArrayList<String> keyList = new ArrayList<>(); CCombo wInputTransform; String inputTransformName; for (int i = 0; i < wInputTransformArray.length; i++) { wInputTransform = wInputTransformArray[i]; inputTransformName = wInputTransform.getText(); if (Utils.isEmpty(inputTransformName)) { continue; } inputTransformNameList.add(inputTransformName); keyList.add(keyValTextBox[i].getText()); if (infoStreams.size() < inputTransformNameList.size()) { streamDescription = BaseMessages.getString(PKG, "MultiMergeJoin.InfoStream.Description"); stream = new Stream(StreamType.INFO, null, streamDescription, StreamIcon.INFO, null); transformIOMeta.addStream(stream); } } int inputTransformCount = inputTransformNameList.size(); meta.allocateInputTransforms(inputTransformCount); meta.allocateKeys(inputTransformCount); String[] inputTransforms = meta.getInputTransforms(); String[] keyFields = meta.getKeyFields(); infoStreams = transformIOMeta.getInfoStreams(); for (int i = 0; i < inputTransformCount; i++) { inputTransformName = inputTransformNameList.get(i); inputTransforms[i] = inputTransformName; stream = infoStreams.get(i); stream.setTransformMeta(pipelineMeta.findTransform(inputTransformName)); keyFields[i] = keyList.get(i); } meta.setJoinType(joinTypeCombo.getText()); } private void ok() { if (Utils.isEmpty(wTransformName.getText())) { return; } getMeta(joinMeta); // Show a warning (optional) if ("Y".equalsIgnoreCase(props.getCustomParameter(STRING_SORT_WARNING_PARAMETER, "Y"))) { MessageDialogWithToggle md = new MessageDialogWithToggle( shell, BaseMessages.getString(PKG, "MultiMergeJoinDialog.InputNeedSort.DialogTitle"), BaseMessages.getString( PKG, "MultiMergeJoinDialog.InputNeedSort.DialogMessage", Const.CR) + Const.CR, SWT.ICON_WARNING, new String[] { BaseMessages.getString(PKG, "MultiMergeJoinDialog.InputNeedSort.Option1") }, BaseMessages.getString(PKG, "MultiMergeJoinDialog.InputNeedSort.Option2"), "N".equalsIgnoreCase(props.getCustomParameter(STRING_SORT_WARNING_PARAMETER, "Y"))); md.open(); props.setCustomParameter(STRING_SORT_WARNING_PARAMETER, md.getToggleState() ? "N" : "Y"); } transformName = wTransformName.getText(); // return value dispose(); } /** Listener for Configure Keys button */ private static class ConfigureKeyButtonListener implements Listener { MultiMergeJoinDialog dialog; Text textBox; int inputStreamIndex; ModifyListener listener; public ConfigureKeyButtonListener( MultiMergeJoinDialog dialog, Text textBox, int streamIndex, ModifyListener lsMod) { this.dialog = dialog; this.textBox = textBox; this.listener = lsMod; this.inputStreamIndex = streamIndex; } @Override public void handleEvent(Event event) { dialog.configureKeys(textBox, inputStreamIndex, listener); } } }
37.375458
99
0.688342
af5137f783b897befa4b515c5964c85e5452c06c
16,071
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.priam.backup; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.inject.Inject; import com.google.inject.Provider; import com.netflix.priam.backup.AbstractBackupPath.BackupFileType; import com.netflix.priam.config.IConfiguration; import com.netflix.priam.notification.BackupEvent; import com.netflix.priam.notification.EventGenerator; import com.netflix.priam.notification.EventObserver; import com.netflix.priam.scheduler.BlockingSubmitThreadPoolExecutor; import com.netflix.priam.utils.BoundedExponentialRetryCallable; import java.io.File; import java.io.FileNotFoundException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.*; import org.apache.commons.collections4.iterators.FilterIterator; import org.apache.commons.collections4.iterators.TransformIterator; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is responsible for managing parallelism and orchestrating the upload and download, but * the subclasses actually implement the details of uploading a file. * * <p>Created by aagrawal on 8/30/18. */ public abstract class AbstractFileSystem implements IBackupFileSystem, EventGenerator<BackupEvent> { private static final Logger logger = LoggerFactory.getLogger(AbstractFileSystem.class); protected final Provider<AbstractBackupPath> pathProvider; private final CopyOnWriteArrayList<EventObserver<BackupEvent>> observers = new CopyOnWriteArrayList<>(); private final IConfiguration configuration; // protected final BackupMetrics backupMetrics; private final Set<Path> tasksQueued; private final ThreadPoolExecutor fileUploadExecutor; private final ThreadPoolExecutor fileDownloadExecutor; // This is going to be a write-thru cache containing the most frequently used items from remote // file system. This is to ensure that we don't make too many API calls to remote file system. private final Cache<Path, Boolean> objectCache; @Inject public AbstractFileSystem( IConfiguration configuration, // BackupMetrics backupMetrics, // BackupNotificationMgr backupNotificationMgr, Provider<AbstractBackupPath> pathProvider) { this.configuration = configuration; // this.backupMetrics = backupMetrics; this.pathProvider = pathProvider; // Add notifications. // this.addObserver(backupNotificationMgr); this.objectCache = CacheBuilder.newBuilder().maximumSize(configuration.getBackupQueueSize()).build(); tasksQueued = new ConcurrentHashMap<>().newKeySet(); /* Note: We are using different queue for upload and download as with Backup V2.0 we might download all the meta files for "sync" feature which might compete with backups for scheduling. Also, we may want to have different TIMEOUT for each kind of operation (upload/download) based on our file system choices. */ BlockingQueue<Runnable> uploadQueue = new ArrayBlockingQueue<>(configuration.getBackupQueueSize()); /*PolledMeter.using(backupMetrics.getRegistry()) .withName(backupMetrics.uploadQueueSize) .monitorSize(uploadQueue); */ this.fileUploadExecutor = new BlockingSubmitThreadPoolExecutor( configuration.getBackupThreads(), uploadQueue, configuration.getUploadTimeout()); BlockingQueue<Runnable> downloadQueue = new ArrayBlockingQueue<>(configuration.getDownloadQueueSize()); /*PolledMeter.using(backupMetrics.getRegistry()) .withName(backupMetrics.downloadQueueSize) .monitorSize(downloadQueue); */ this.fileDownloadExecutor = new BlockingSubmitThreadPoolExecutor( configuration.getRestoreThreads(), downloadQueue, configuration.getDownloadTimeout()); } @Override public Future<Path> asyncDownloadFile( final Path remotePath, final Path localPath, final int retry) throws BackupRestoreException, RejectedExecutionException { return fileDownloadExecutor.submit( () -> { downloadFile(remotePath, localPath, retry); return remotePath; }); } @Override public void downloadFile(final Path remotePath, final Path localPath, final int retry) throws BackupRestoreException { // TODO: Should we download the file if localPath already exists? if (remotePath == null || localPath == null) return; localPath.toFile().getParentFile().mkdirs(); logger.info("Downloading file: {} to location: {}", remotePath, localPath); try { new BoundedExponentialRetryCallable<Void>(500, 10000, retry) { @Override public Void retriableCall() throws Exception { downloadFileImpl(remotePath, localPath); return null; } }.call(); // Note we only downloaded the bytes which are represented on file system (they are // compressed and maybe encrypted). // File size after decompression or decryption might be more/less. // backupMetrics.recordDownloadRate(getFileSize(remotePath)); // backupMetrics.incrementValidDownloads(); logger.info("Successfully downloaded file: {} to location: {}", remotePath, localPath); } catch (Exception e) { // backupMetrics.incrementInvalidDownloads(); logger.error("Error while downloading file: {} to location: {}", remotePath, localPath); throw new BackupRestoreException(e.getMessage()); } } protected abstract void downloadFileImpl(final Path remotePath, final Path localPath) throws BackupRestoreException; @Override public Future<Path> asyncUploadFile( final Path localPath, final Path remotePath, final AbstractBackupPath path, final int retry, final boolean deleteAfterSuccessfulUpload) throws FileNotFoundException, RejectedExecutionException, BackupRestoreException { return fileUploadExecutor.submit( () -> { uploadFile(localPath, remotePath, path, retry, deleteAfterSuccessfulUpload); return localPath; }); } @Override public void uploadFile( final Path localPath, final Path remotePath, final AbstractBackupPath path, final int retry, final boolean deleteAfterSuccessfulUpload) throws FileNotFoundException, BackupRestoreException { if (localPath == null || remotePath == null || !localPath.toFile().exists() || localPath.toFile().isDirectory()) throw new FileNotFoundException( "File do not exist or is a directory. localPath: " + localPath + ", remotePath: " + remotePath); if (tasksQueued.add(localPath)) { logger.info("Uploading file: {} to location: {}", localPath, remotePath); try { long uploadedFileSize; // Upload file if it not present at remote location. if (path.getType() != BackupFileType.SST_V2 || !checkObjectExists(remotePath)) { notifyEventStart(new BackupEvent(path)); uploadedFileSize = new BoundedExponentialRetryCallable<Long>(500, 10000, retry) { @Override public Long retriableCall() throws Exception { return uploadFileImpl(localPath, remotePath); } }.call(); // Add to cache after successful upload. // We only add SST_V2 as other file types are usually not checked, so no point // evicting our SST_V2 results. if (path.getType() == BackupFileType.SST_V2) addObjectCache(remotePath); // backupMetrics.recordUploadRate(uploadedFileSize); // backupMetrics.incrementValidUploads(); path.setCompressedFileSize(uploadedFileSize); notifyEventSuccess(new BackupEvent(path)); } else { // file is already uploaded to remote file system. logger.info("File: {} already present on remoteFileSystem.", remotePath); } logger.info( "Successfully uploaded file: {} to location: {}", localPath, remotePath); if (deleteAfterSuccessfulUpload && !FileUtils.deleteQuietly(localPath.toFile())) logger.warn( String.format( "Failed to delete local file %s.", localPath.toFile().getAbsolutePath())); } catch (Exception e) { // backupMetrics.incrementInvalidUploads(); notifyEventFailure(new BackupEvent(path)); logger.error( "Error while uploading file: {} to location: {}. Exception: Msg: [{}], Trace: {}", localPath, remotePath, e.getMessage(), e.getStackTrace()); throw new BackupRestoreException(e.getMessage()); } finally { // Remove the task from the list so if we try to upload file ever again, we can. tasksQueued.remove(localPath); } } else logger.info("Already in queue, no-op. File: {}", localPath); } private void addObjectCache(Path remotePath) { objectCache.put(remotePath, Boolean.TRUE); } @Override public boolean checkObjectExists(Path remotePath) { // Check in cache, if remote file exists. Boolean cacheResult = objectCache.getIfPresent(remotePath); // Cache hit. Return the value. if (cacheResult != null) return cacheResult; // Cache miss - Check remote file system if object exist. boolean remoteFileExist = doesRemoteFileExist(remotePath); if (remoteFileExist) addObjectCache(remotePath); return remoteFileExist; } @Override public void deleteRemoteFiles(List<Path> remotePaths) throws BackupRestoreException { if (remotePaths == null) return; // Note that we are trying to implement write-thru cache here so it is good idea to // invalidate the cache first. This is important so that if there is any issue (because file // was deleted), it is caught by our snapshot job we can re-upload the file. This will also // help in ensuring that our validation job fails if there are any error caused due to TTL // of a file. objectCache.invalidateAll(remotePaths); deleteFiles(remotePaths); } protected abstract void deleteFiles(List<Path> remotePaths) throws BackupRestoreException; protected abstract boolean doesRemoteFileExist(Path remotePath); protected abstract long uploadFileImpl(final Path localPath, final Path remotePath) throws BackupRestoreException; @Override public String getShard() { return getPrefix().getName(0).toString(); } @Override public Path getPrefix() { Path prefix = Paths.get(configuration.getBackupPrefix()); if (StringUtils.isNotBlank(configuration.getRestorePrefix())) { prefix = Paths.get(configuration.getRestorePrefix()); } return prefix; } @Override public Iterator<AbstractBackupPath> listPrefixes(Date date) { String prefix = pathProvider.get().clusterPrefix(getPrefix().toString()); Iterator<String> fileIterator = listFileSystem(prefix, File.pathSeparator, null); //noinspection unchecked return new TransformIterator( fileIterator, remotePath -> { AbstractBackupPath abstractBackupPath = pathProvider.get(); abstractBackupPath.parsePartialPrefix(remotePath.toString()); return abstractBackupPath; }); } @Override public Iterator<AbstractBackupPath> list(String path, Date start, Date till) { String prefix = pathProvider.get().remotePrefix(start, till, path); Iterator<String> fileIterator = listFileSystem(prefix, null, null); @SuppressWarnings("unchecked") TransformIterator<String, AbstractBackupPath> transformIterator = new TransformIterator( fileIterator, remotePath -> { AbstractBackupPath abstractBackupPath = pathProvider.get(); abstractBackupPath.parseRemote(remotePath.toString()); return abstractBackupPath; }); return new FilterIterator<>( transformIterator, abstractBackupPath -> (abstractBackupPath.getTime().after(start) && abstractBackupPath.getTime().before(till)) || abstractBackupPath.getTime().equals(start)); } @Override public final void addObserver(EventObserver<BackupEvent> observer) { if (observer == null) throw new NullPointerException("observer must not be null."); observers.addIfAbsent(observer); } @Override public void removeObserver(EventObserver<BackupEvent> observer) { if (observer == null) throw new NullPointerException("observer must not be null."); observers.remove(observer); } @Override public void notifyEventStart(BackupEvent event) { observers.forEach(eventObserver -> eventObserver.updateEventStart(event)); } @Override public void notifyEventSuccess(BackupEvent event) { observers.forEach(eventObserver -> eventObserver.updateEventSuccess(event)); } @Override public void notifyEventFailure(BackupEvent event) { observers.forEach(eventObserver -> eventObserver.updateEventFailure(event)); } @Override public void notifyEventStop(BackupEvent event) { observers.forEach(eventObserver -> eventObserver.updateEventStop(event)); } @Override public int getUploadTasksQueued() { return tasksQueued.size(); } @Override public int getDownloadTasksQueued() { return fileDownloadExecutor.getQueue().size(); } @Override public void clearCache() { objectCache.invalidateAll(); } }
41.634715
130
0.629395
54fc04c849ff5cee8e0a31d5b8d9301c99e2eb29
847
//,temp,StompTelnetTest.java,53,70,temp,StompTelnetTest.java,34,51 //,2 public class xxx { @Test(timeout = 60000) public void testCRLF() throws Exception { for (TransportConnector connector : brokerService.getTransportConnectors()) { LOG.info("try: " + connector.getConnectUri()); int port = connector.getConnectUri().getPort(); StompConnection stompConnection = new StompConnection(); stompConnection.open(createSocket(port)); String frame = "CONNECT\r\n\r\n" + Stomp.NULL; stompConnection.sendFrame(frame); frame = stompConnection.receiveFrame(); LOG.info("response from: " + connector.getConnectUri() + ", " + frame); assertTrue(frame.startsWith("CONNECTED")); stompConnection.close(); } } };
36.826087
85
0.621015
4614cbce8c9134eb6c2815433aea19ab3caa0b63
3,896
package org.fortiss.smg.prophet.impl; import java.util.Date; import org.fortiss.smg.prophet.components.smgCalendar.SmgCalendarUtils; /** * This file contains the configuration of the forecast subsystem * * @author Orest Tarasiuk * @thesisOT * */ public class Config { /* * Location */ /** * location to be used for the openweathermap.org API forecast * * @thesisOT */ public static final String locationCity = "Munich,de"; /* * Calendar */ /** * ISC URL, indicates the room that is to be analyzed * * @thesisOT */ public static final String icsUrlStr = "https://merkur.fortiss.org/home/dijkstra/calendar"; /** * calendar refresh interval; default: 0.5 h * * @thesisOT */ public static final int calendarRefreshIntervalMs = 1000 * 60 * 30; /** * max room utilization; default: 10.0 h * * @thesisOT */ public static final long maxRoomDuration = 10 * 60; /* * Consumption */ /** * maximum allowed discrepancy between the utilization and TES based * forecast, in Wh; used as a sanity check * * @thesisOT */ public static final double consumptionMaxDiscrepancyWh = 50000; // weights for forecasting the consumption /** * impact of room utilization * * @thesisOT */ public static final double consumptionWeightUtil = 10; /** * impact of TES long-term forecast * * @thesisOT */ public static final double consumptionWeightTes = 5; /* * Energy Pricing */ // weights for forecasting energy prices /** * impact of solar generation potential (supply) * * @thesisOT */ public static final double enerpricingWeightSolar = 10; /** * impact of wind generation potential (supply) * * @thesisOT */ public static final double enerpricingWeightWind = 5; /** * impact of AC necessity (demand) * * @thesisOT */ public static final double enerpricingWeightAc = 20; /* * Weather */ // weights for forecasting the solar energy generation potential /** * impact of the length of the day (sunrise-sunset) * * @thesisOT */ public static final double solarPotentialLengthWeight = 2; /** * impact of the cloud density * * @thesisOT */ public static final double solarPotentialSunnyWeight = 2; /** * impact of the temperature * * @thesisOT */ public static final double solarPotentialWarmWeight = 1; // refresh interval /** * weather data refresh interval; default: 1.0 h * * @thesisOT */ public static final int weatherRefreshIntervalMs = 1000 * 60 * 60; /* * Date */ /** * default date to be used for the forecasts * * @thesisOT */ public static final Date imminentForecastDate = SmgCalendarUtils .getNextDay(SmgCalendarUtils.getToday()); /* * Battery */ // prices influence when to (dis)charge the battery /** * the highest price considered to be low, in EUR * * @thesisOT */ public static final double priceThresholdLow = 0.20; /** * the lowest price considered to be high, in EUR * * @thesisOT */ public static final double priceThresholdHigh = 0.22; /* * Solar panel */ // TODO: This is supposed to be the maximum generation capacity, not the // current generation; the field solarlogQ?GeneratorWerte is likely wrong /** * the database field that contains the maximum generation capacity of the * solar panel * * @thesisOT */ public static final String dbSolarGenerationCapacityField = "solarlogQ?GeneratorWerte"; }
23.329341
95
0.602156
3c236249c94759b7c7ffeba821b7197a625543bd
1,487
/** * */ package org.devel.javafx.navigation.prototype.view; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.KeyEvent; import javafx.scene.layout.VBox; import org.devel.javafx.navigation.prototype.viewmodel.SearchRouteViewModel; import de.saxsys.jfx.mvvm.base.view.View; /** * @author stefan.illgen * */ public class SearchRouteView extends View<SearchRouteViewModel> { @FXML private MapView mapViewController; @FXML private Label finishLbl; @FXML private TextField finishTf; @FXML private Button searchBtn; @FXML private VBox searchRouteVBox; @FXML private Label startLbl; @FXML private TextField startTf; @FXML void finishChanged(KeyEvent event) { mapViewController.calcRoute(); } @FXML void startChanged(KeyEvent event) { mapViewController.calcRoute(); } @Override public void initialize(URL arg0, ResourceBundle arg1) { // init VM getViewModel().initialize(); // set route props mapViewController.bindRoute(startTf.textProperty(), finishTf.textProperty()); // bind V 2 VM after Web Engine has been loaded by maps view startTf.textProperty() .bindBidirectional(getViewModel().startProperty()); finishTf.textProperty().bindBidirectional( getViewModel().finishProperty()); } public MapView getMapView() { return mapViewController; } }
19.064103
81
0.753867
41067c24e8d10cc3ab342fdba6a332771da1bdb8
357
package com.greymass.esr.models; public class AccountName { private String gName; public AccountName(String name) { gName = name; } public void setName(String name) { gName = name; } public String getName() { return gName; } @Override public String toString() { return gName; } }
15.521739
38
0.582633
1d86466fc4a5b20cf6fe74830b64a4698dbe0435
254
package org.e792a8.acme.ui; import org.e792a8.acme.core.workspace.IDirectory; public interface IDirectoryActionObserver { public void open(IDirectory directory); public void close(IDirectory directory); public void handleException(Exception e); }
21.166667
49
0.807087
fece5cdb79d84908fc2cfa1f07f7e3b70951c8a5
12,076
/** * */ package com.issue.entity; import java.time.LocalDate; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import com.issue.enums.FeatureScope; import com.issue.iface.SprintDao; import com.issue.utils.Stories; /** * The Class TeamImpl. * * @author benito */ public class Team { /** The team name. */ private final String teamName; /** The sprint label. */ private final String sprintLabel; /** The team members. */ private Set<String> teamMembers; /** The team members count. */ private int teamMemberCount; /** The finished story points. */ private Map<FeatureScope, Integer> finishedStoryPoints; /** The not finished story points summary. */ private int notFinishedStoryPointsSum; /** The on begin planned story points summary. */ private int onBeginPlannedStoryPointsSum = 0; /** The on end planned story points summary. */ private int onEndPlannedStoryPointsSum = 0; /** The to do story points sum. */ private int toDoStoryPointsSum = 0; /** The in progress story points sum. */ private int inProgressStoryPointsSum = 0; /** The finished story points summary. */ private int finishedStoryPointsSum = 0; /** The delta story points. */ private double deltaStoryPoints = 0; /** The planned story points closed. */ private double plannedStoryPointsClosed = 0; /** The not closed high prior stories count. */ private int notClosedHighPriorStoriesCount = 0; /** The closed high prior stories count. */ private int closedHighPriorStoriesCount = 0; /** The closed high prior stories success rate. */ private double closedHighPriorStoriesSuccessRate = 0; /** The finished stories SP sum. */ private int finishedStoriesSPSum = 0; /** The finished bugs SP sum. */ private int finishedBugsSPSum = 0; /** The time estimation. */ private long timeEstimation = 0L; /** The time planned. */ private long timePlanned = 0L; /** The time spent. */ private long timeSpent = 0L; /** The sprint start. */ private LocalDate sprintStart = LocalDate.of(1970, 1, 1); /** The sprint end. */ private LocalDate sprintEnd = LocalDate.of(1970, 1, 1); /** The refined story points. */ private SprintDao<String, Sprint> refinedStoryPoints; /** The goals. */ private List<String> goals; /** * Instantiates a new team impl. * * @param teamName the team name * @param sprintLabel the sprint label */ public Team(final String teamName, final String sprintLabel) { this.teamName = Optional.ofNullable(teamName).orElseThrow(); this.sprintLabel = Optional.ofNullable(sprintLabel).orElseThrow(); } /** * Gets the team name. * * @return the team name */ public String getTeamName() { return teamName; } /** * Gets the sprint label. * * @return the sprint label */ public String getSprintLabel() { return sprintLabel; } /** * Adds the team members. * * @param members the members */ public void addTeamMembers(Set<String> members) { // Initialize new empty set if (Optional.ofNullable(teamMembers).isEmpty()) this.teamMembers = new HashSet<>(); // Add new team members this.teamMembers.addAll(members); // Increment team member counter this.teamMemberCount = teamMembers.stream().filter(t -> !t.isBlank()).collect(Collectors.counting()).intValue(); } /** * Gets the team member count. * * @return the teamMemberCount */ public int getTeamMemberCount() { return teamMemberCount; } /** * Gets the finished story points. * * @return the finished story points */ public Optional<Map<FeatureScope, Integer>> getFinishedStoryPoints() { return Optional.ofNullable(finishedStoryPoints); } /** * Sets the finished story points. * * @param finishedStoryPoints the finishedStoryPoints to set */ public void setFinishedStoryPoints(Map<FeatureScope, Integer> finishedStoryPoints) { // Set map of finished story points this.finishedStoryPoints = finishedStoryPoints; // Set summary of finished story points this.finishedStoryPointsSum = Stories.summarizeStoryPoints(this.finishedStoryPoints); } /** * Gets the finished story points summary. * * @return the finishedStoryPointsSum */ public int getFinishedStoryPointsSum() { return finishedStoryPointsSum; } /** * Gets the not finished story points summary. * * @return the notFinishedStoryPointsSum */ public int getNotFinishedStoryPointsSum() { return notFinishedStoryPointsSum; } /** * Sets the not finished story points summary. * * @param notFinishedStoryPointsSum the notFinishedStoryPointsSum to set */ public void setNotFinishedStoryPointsSum(int notFinishedStoryPointsSum) { this.notFinishedStoryPointsSum = notFinishedStoryPointsSum; } /** * Gets the on begin planned story points summary. * * @return the onBeginPlannedStoryPointsSum */ public int getOnBeginPlannedStoryPointsSum() { return onBeginPlannedStoryPointsSum; } /** * Sets the on begin planned story points summary. * * @param onBeginPlannedStoryPointsSum the onBeginPlannedStoryPointsSum to set */ public void setOnBeginPlannedStoryPointsSum(int onBeginPlannedStoryPointsSum) { // Set summary on sprint start planned story points this.onBeginPlannedStoryPointsSum = onBeginPlannedStoryPointsSum; } /** * Gets the on end planned story points summary. * * @return the onEndPlannedStoryPointsSum */ public int getOnEndPlannedStoryPointsSum() { return onEndPlannedStoryPointsSum; } /** * Sets the on end planned story points count. * * @param onEndPlannedStoryPointsSum the onEndPlannedStoryPointsCount to set */ public void setOnEndPlannedStoryPointsSum(int onEndPlannedStoryPointsSum) { // Set summary on sprint close planned story points this.onEndPlannedStoryPointsSum = onEndPlannedStoryPointsSum; } /** * Gets the to do story points sum. * * @return the toDoStoryPointsSum */ public int getToDoStoryPointsSum() { return toDoStoryPointsSum; } /** * Sets the to do story points sum. * * @param toDoStoryPointsSum the toDoStoryPointsSum to set */ public void setToDoStoryPointsSum(int toDoStoryPointsSum) { this.toDoStoryPointsSum = toDoStoryPointsSum; } /** * Gets the in progress story points sum. * * @return the inProgressStoryPointsSum */ public int getInProgressStoryPointsSum() { return inProgressStoryPointsSum; } /** * Sets the in progress story points sum. * * @param inProgressStoryPointsSum the inProgressStoryPointsSum to set */ public void setInProgressStoryPointsSum(int inProgressStoryPointsSum) { this.inProgressStoryPointsSum = inProgressStoryPointsSum; } /** * Gets the delta story points. * * @return the deltaStoryPoints */ public double getDeltaStoryPoints() { return deltaStoryPoints; } /** * Sets the delta story points. * * @param deltaStoryPoints the deltaStoryPoints to set */ public void setDeltaStoryPoints(double deltaStoryPoints) { this.deltaStoryPoints = deltaStoryPoints; } /** * Gets the planned story points closed. * * @return the plannedStoryPointsClosed */ public double getPlannedStoryPointsClosed() { return plannedStoryPointsClosed; } /** * Sets the planned story points closed. * * @param plannedStoryPointsClosed the plannedStoryPointsClosed to set */ public void setPlannedStoryPointsClosed(double plannedStoryPointsClosed) { this.plannedStoryPointsClosed = plannedStoryPointsClosed; } /** * Gets the not closed high prior stories count. * * @return the notClosedHighPriorStoriesCount */ public int getNotClosedHighPriorStoriesCount() { return notClosedHighPriorStoriesCount; } /** * Sets the not closed high prior stories count. * * @param notClosedHighPriorStoriesCount the notClosedHighPriorStoriesCount to * set */ public void setNotClosedHighPriorStoriesCount(int notClosedHighPriorStoriesCount) { this.notClosedHighPriorStoriesCount = notClosedHighPriorStoriesCount; } /** * Gets the closed high prior stories count. * * @return the closedHighPriorStoriesCount */ public int getClosedHighPriorStoriesCount() { return closedHighPriorStoriesCount; } /** * Sets the closed high prior stories count. * * @param closedHighPriorStoriesCount the closedHighPriorStoriesCount to set */ public void setClosedHighPriorStoriesCount(int closedHighPriorStoriesCount) { this.closedHighPriorStoriesCount = closedHighPriorStoriesCount; } /** * Gets the closed high prior stories success rate. * * @return the closedHighPriorStoriesSuccessRate */ public double getClosedHighPriorStoriesSuccessRate() { return closedHighPriorStoriesSuccessRate; } /** * Sets the closed high prior stories success rate. * * @param closedHighPriorStoriesSuccessRate the closedHighPriorStoriesSuccessRate to set */ public void setClosedHighPriorStoriesSuccessRate(double closedHighPriorStoriesSuccessRate) { this.closedHighPriorStoriesSuccessRate = closedHighPriorStoriesSuccessRate; } /** * Gets the finished stories SP sum. * * @return the finishedStoriesSPSum */ public int getFinishedStoriesSPSum() { return finishedStoriesSPSum; } /** * Sets the finished stories SP sum. * * @param finishedStoriesSPSum the finishedStoriesSPSum to set */ public void setFinishedStoriesSPSum(int finishedStoriesSPSum) { this.finishedStoriesSPSum = finishedStoriesSPSum; } /** * Gets the finished bugs SP sum. * * @return the finishedBugsSPSum */ public int getFinishedBugsSPSum() { return finishedBugsSPSum; } /** * Sets the finished bugs SP sum. * * @param finishedBugsSPSum the finishedBugsSPSum to set */ public void setFinishedBugsSPSum(int finishedBugsSPSum) { this.finishedBugsSPSum = finishedBugsSPSum; } /** * Gets the time estimation. * * @return the timeEstimation */ public long getTimeEstimation() { return timeEstimation; } /** * Sets the time estimation. * * @param timeEstimation the timeEstimation to set */ public void setTimeEstimation(long timeEstimation) { this.timeEstimation = timeEstimation; } /** * Gets the time planned. * * @return the timePlanned */ public long getTimePlanned() { return timePlanned; } /** * Sets the time planned. * * @param timePlanned the timePlanned to set */ public void setTimePlanned(long timePlanned) { this.timePlanned = timePlanned; } /** * Gets the time spent. * * @return the timeSpent */ public long getTimeSpent() { return timeSpent; } /** * Sets the time spent. * * @param timeSpent the timeSpent to set */ public void setTimeSpent(long timeSpent) { this.timeSpent = timeSpent; } /** * Gets the sprint start. * * @return the sprintStart */ public LocalDate getSprintStart() { return sprintStart; } /** * Sets the sprint start. * * @param sprintStart the sprintStart to set */ public void setSprintStart(LocalDate sprintStart) { this.sprintStart = sprintStart; } /** * Gets the sprint end. * * @return the sprintEnd */ public LocalDate getSprintEnd() { return sprintEnd; } /** * Sets the sprint end. * * @param sprintEnd the sprintEnd to set */ public void setSprintEnd(LocalDate sprintEnd) { this.sprintEnd = sprintEnd; } /** * Gets the refined story points. * * @return the refinedStoryPoints */ public SprintDao<String, Sprint> getRefinedStoryPoints() { return refinedStoryPoints; } /** * Sets the refined story points. * * @param refinedStoryPoints the refinedStoryPoints to set */ public void setRefinedStoryPoints(SprintDao<String, Sprint> refinedStoryPoints) { this.refinedStoryPoints = refinedStoryPoints; } /** * Gets the goals. * * @return the goals */ public List<String> getGoals() { return goals; } /** * Sets the goals. * * @param goals the goals to set */ public void setGoals(List<String> goals) { this.goals = goals; } }
22.741996
114
0.721348
7c0129fb32593213728adf9f79dee05888c1a3a1
19,992
/** * Autogenerated by Thrift Compiler (0.7.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING */ package org.apache.cassandra.thrift; /* * * 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. * */ import org.apache.commons.lang.builder.HashCodeBuilder; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CqlResult implements org.apache.thrift.TBase<CqlResult, CqlResult._Fields>, java.io.Serializable, Cloneable { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CqlResult"); private static final org.apache.thrift.protocol.TField TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("type", org.apache.thrift.protocol.TType.I32, (short)1); private static final org.apache.thrift.protocol.TField ROWS_FIELD_DESC = new org.apache.thrift.protocol.TField("rows", org.apache.thrift.protocol.TType.LIST, (short)2); private static final org.apache.thrift.protocol.TField NUM_FIELD_DESC = new org.apache.thrift.protocol.TField("num", org.apache.thrift.protocol.TType.I32, (short)3); private static final org.apache.thrift.protocol.TField SCHEMA_FIELD_DESC = new org.apache.thrift.protocol.TField("schema", org.apache.thrift.protocol.TType.STRUCT, (short)4); /** * * @see CqlResultType */ public CqlResultType type; // required public List<CqlRow> rows; // required public int num; // required public CqlMetadata schema; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { /** * * @see CqlResultType */ TYPE((short)1, "type"), ROWS((short)2, "rows"), NUM((short)3, "num"), SCHEMA((short)4, "schema"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // TYPE return TYPE; case 2: // ROWS return ROWS; case 3: // NUM return NUM; case 4: // SCHEMA return SCHEMA; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __NUM_ISSET_ID = 0; private BitSet __isset_bit_vector = new BitSet(1); public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.TYPE, new org.apache.thrift.meta_data.FieldMetaData("type", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, CqlResultType.class))); tmpMap.put(_Fields.ROWS, new org.apache.thrift.meta_data.FieldMetaData("rows", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CqlRow.class)))); tmpMap.put(_Fields.NUM, new org.apache.thrift.meta_data.FieldMetaData("num", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.SCHEMA, new org.apache.thrift.meta_data.FieldMetaData("schema", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CqlMetadata.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CqlResult.class, metaDataMap); } public CqlResult() { } public CqlResult( CqlResultType type) { this(); this.type = type; } /** * Performs a deep copy on <i>other</i>. */ public CqlResult(CqlResult other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); if (other.isSetType()) { this.type = other.type; } if (other.isSetRows()) { List<CqlRow> __this__rows = new ArrayList<CqlRow>(); for (CqlRow other_element : other.rows) { __this__rows.add(new CqlRow(other_element)); } this.rows = __this__rows; } this.num = other.num; if (other.isSetSchema()) { this.schema = new CqlMetadata(other.schema); } } public CqlResult deepCopy() { return new CqlResult(this); } @Override public void clear() { this.type = null; this.rows = null; setNumIsSet(false); this.num = 0; this.schema = null; } /** * * @see CqlResultType */ public CqlResultType getType() { return this.type; } /** * * @see CqlResultType */ public CqlResult setType(CqlResultType type) { this.type = type; return this; } public void unsetType() { this.type = null; } /** Returns true if field type is set (has been assigned a value) and false otherwise */ public boolean isSetType() { return this.type != null; } public void setTypeIsSet(boolean value) { if (!value) { this.type = null; } } public int getRowsSize() { return (this.rows == null) ? 0 : this.rows.size(); } public java.util.Iterator<CqlRow> getRowsIterator() { return (this.rows == null) ? null : this.rows.iterator(); } public void addToRows(CqlRow elem) { if (this.rows == null) { this.rows = new ArrayList<CqlRow>(); } this.rows.add(elem); } public List<CqlRow> getRows() { return this.rows; } public CqlResult setRows(List<CqlRow> rows) { this.rows = rows; return this; } public void unsetRows() { this.rows = null; } /** Returns true if field rows is set (has been assigned a value) and false otherwise */ public boolean isSetRows() { return this.rows != null; } public void setRowsIsSet(boolean value) { if (!value) { this.rows = null; } } public int getNum() { return this.num; } public CqlResult setNum(int num) { this.num = num; setNumIsSet(true); return this; } public void unsetNum() { __isset_bit_vector.clear(__NUM_ISSET_ID); } /** Returns true if field num is set (has been assigned a value) and false otherwise */ public boolean isSetNum() { return __isset_bit_vector.get(__NUM_ISSET_ID); } public void setNumIsSet(boolean value) { __isset_bit_vector.set(__NUM_ISSET_ID, value); } public CqlMetadata getSchema() { return this.schema; } public CqlResult setSchema(CqlMetadata schema) { this.schema = schema; return this; } public void unsetSchema() { this.schema = null; } /** Returns true if field schema is set (has been assigned a value) and false otherwise */ public boolean isSetSchema() { return this.schema != null; } public void setSchemaIsSet(boolean value) { if (!value) { this.schema = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case TYPE: if (value == null) { unsetType(); } else { setType((CqlResultType)value); } break; case ROWS: if (value == null) { unsetRows(); } else { setRows((List<CqlRow>)value); } break; case NUM: if (value == null) { unsetNum(); } else { setNum((Integer)value); } break; case SCHEMA: if (value == null) { unsetSchema(); } else { setSchema((CqlMetadata)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case TYPE: return getType(); case ROWS: return getRows(); case NUM: return Integer.valueOf(getNum()); case SCHEMA: return getSchema(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case TYPE: return isSetType(); case ROWS: return isSetRows(); case NUM: return isSetNum(); case SCHEMA: return isSetSchema(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof CqlResult) return this.equals((CqlResult)that); return false; } public boolean equals(CqlResult that) { if (that == null) return false; boolean this_present_type = true && this.isSetType(); boolean that_present_type = true && that.isSetType(); if (this_present_type || that_present_type) { if (!(this_present_type && that_present_type)) return false; if (!this.type.equals(that.type)) return false; } boolean this_present_rows = true && this.isSetRows(); boolean that_present_rows = true && that.isSetRows(); if (this_present_rows || that_present_rows) { if (!(this_present_rows && that_present_rows)) return false; if (!this.rows.equals(that.rows)) return false; } boolean this_present_num = true && this.isSetNum(); boolean that_present_num = true && that.isSetNum(); if (this_present_num || that_present_num) { if (!(this_present_num && that_present_num)) return false; if (this.num != that.num) return false; } boolean this_present_schema = true && this.isSetSchema(); boolean that_present_schema = true && that.isSetSchema(); if (this_present_schema || that_present_schema) { if (!(this_present_schema && that_present_schema)) return false; if (!this.schema.equals(that.schema)) return false; } return true; } @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); boolean present_type = true && (isSetType()); builder.append(present_type); if (present_type) builder.append(type.getValue()); boolean present_rows = true && (isSetRows()); builder.append(present_rows); if (present_rows) builder.append(rows); boolean present_num = true && (isSetNum()); builder.append(present_num); if (present_num) builder.append(num); boolean present_schema = true && (isSetSchema()); builder.append(present_schema); if (present_schema) builder.append(schema); return builder.toHashCode(); } public int compareTo(CqlResult other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; CqlResult typedOther = (CqlResult)other; lastComparison = Boolean.valueOf(isSetType()).compareTo(typedOther.isSetType()); if (lastComparison != 0) { return lastComparison; } if (isSetType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.type, typedOther.type); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetRows()).compareTo(typedOther.isSetRows()); if (lastComparison != 0) { return lastComparison; } if (isSetRows()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.rows, typedOther.rows); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetNum()).compareTo(typedOther.isSetNum()); if (lastComparison != 0) { return lastComparison; } if (isSetNum()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.num, typedOther.num); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetSchema()).compareTo(typedOther.isSetSchema()); if (lastComparison != 0) { return lastComparison; } if (isSetSchema()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.schema, typedOther.schema); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField field; iprot.readStructBegin(); while (true) { field = iprot.readFieldBegin(); if (field.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (field.id) { case 1: // TYPE if (field.type == org.apache.thrift.protocol.TType.I32) { this.type = CqlResultType.findByValue(iprot.readI32()); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); } break; case 2: // ROWS if (field.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list83 = iprot.readListBegin(); this.rows = new ArrayList<CqlRow>(_list83.size); for (int _i84 = 0; _i84 < _list83.size; ++_i84) { CqlRow _elem85; // required _elem85 = new CqlRow(); _elem85.read(iprot); this.rows.add(_elem85); } iprot.readListEnd(); } } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); } break; case 3: // NUM if (field.type == org.apache.thrift.protocol.TType.I32) { this.num = iprot.readI32(); setNumIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); } break; case 4: // SCHEMA if (field.type == org.apache.thrift.protocol.TType.STRUCT) { this.schema = new CqlMetadata(); this.schema.read(iprot); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { validate(); oprot.writeStructBegin(STRUCT_DESC); if (this.type != null) { oprot.writeFieldBegin(TYPE_FIELD_DESC); oprot.writeI32(this.type.getValue()); oprot.writeFieldEnd(); } if (this.rows != null) { if (isSetRows()) { oprot.writeFieldBegin(ROWS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, this.rows.size())); for (CqlRow _iter86 : this.rows) { _iter86.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } } if (isSetNum()) { oprot.writeFieldBegin(NUM_FIELD_DESC); oprot.writeI32(this.num); oprot.writeFieldEnd(); } if (this.schema != null) { if (isSetSchema()) { oprot.writeFieldBegin(SCHEMA_FIELD_DESC); this.schema.write(oprot); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } @Override public String toString() { StringBuilder sb = new StringBuilder("CqlResult("); boolean first = true; sb.append("type:"); if (this.type == null) { sb.append("null"); } else { sb.append(this.type); } first = false; if (isSetRows()) { if (!first) sb.append(", "); sb.append("rows:"); if (this.rows == null) { sb.append("null"); } else { sb.append(this.rows); } first = false; } if (isSetNum()) { if (!first) sb.append(", "); sb.append("num:"); sb.append(this.num); first = false; } if (isSetSchema()) { if (!first) sb.append(", "); sb.append("schema:"); if (this.schema == null) { sb.append("null"); } else { sb.append(this.schema); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (type == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'type' was not present! Struct: " + toString()); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bit_vector = new BitSet(1); read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } }
28.806916
176
0.639056
d98e37a7f7f5c17c2bb5b4dc2d43edafaea79594
1,407
package com.er5bus.restaurant.models; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.UniqueConstraint; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.ToString; import lombok.Getter; import lombok.Setter; @Entity @Table( name = "Client", uniqueConstraints={ @UniqueConstraint(columnNames = {"first_name", "last_name"}) } ) @Getter@Setter @Data @ToString(exclude = {"tickets"}) public class ClientEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(length = 50, name = "first_name", nullable = true) private String firstName; @Column(length = 50, name = "last_name", nullable = true) private String lastName; private LocalDate dateOfBirth; @Column(length = 200, name = "address", nullable = true) private String address; @Column(length = 10, name = "phone", nullable = true) private String phone; @OneToMany(mappedBy = "client", cascade = CascadeType.REMOVE) @JsonIgnore List<TicketEntity> tickets; }
23.847458
64
0.766169
b18639706ef97401af5ebf0639e6e689dc088d07
2,143
package org.gramar.platform; import static org.junit.Assert.fail; import java.io.Reader; import org.gramar.IFileStore; import org.gramar.IGramarApplicationStatus; import org.gramar.IGramarPlatform; import org.gramar.IModel; import org.gramar.exception.GramarException; import org.gramar.filestore.ConsoleFileStore; import org.gramar.filestore.MemoryFileStore; import org.gramar.filestore.ZipFileStore; import org.gramar.model.DocumentHelper; import org.gramar.resource.UpdateFile; import org.gramar.util.GramarHelper; import org.junit.Test; public class SimplePatternPlatformTest { @Test public void test01() throws Exception { try { IGramarPlatform platform = new SimpleGramarPlatform(); IFileStore store = new ConsoleFileStore(); IModel model = DocumentHelper.modelFromResource("/models/simple01.xml"); platform.apply(model, "com.fredco.alpha.pattern", store); } catch (GramarException e) { fail(e.toString()); } } @Test public void test02() throws Exception { try { IGramarPlatform platform = new SimpleGramarPlatform(); MemoryFileStore store = new MemoryFileStore(); String path = "/someproject/dir1/dir2/output_ABC_c_DEF.txt"; Reader reader = GramarHelper.fromResource("/files/output_c.txt"); store.setFileContent(path, reader); IModel model = DocumentHelper.modelFromResource("/models/simple01.xml"); platform.apply(model, "com.fredco.alpha.pattern", store); String contents = GramarHelper.asString(store.getFileContent(path)); System.out.println(contents); } catch (GramarException e) { fail(e.toString()); } } @Test public void test03() throws Exception { try { IGramarPlatform platform = new SimpleGramarPlatform(); MemoryFileStore store = new MemoryFileStore(); IModel model = DocumentHelper.modelFromResource("/models/simple01.xml"); IGramarApplicationStatus result = platform.apply(model, "com.fredco.alpha.pattern", store); String contents = result.mainProductionResult(); System.out.println(contents); } catch (GramarException e) { fail(e.toString()); } } }
24.352273
94
0.732618
d16c728fc717e967892a1c666fcaa53cd1c42bcb
2,917
package com.tayfint.meethub.model; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @Entity @Table(name="app_application") @EntityListeners(AuditingEntityListener.class) public class Application extends BaseEntity { public Application(Meeting meeting, User user) { super(); this.statusCd = "0"; this.meeting = meeting; this.user = user; } @CreatedBy @Column(nullable = false, updatable = false) private String createdBy; @CreatedDate @Column(nullable = false, updatable = false) private LocalDateTime created; @LastModifiedBy @Column(nullable = false) private String modifiedBy; @LastModifiedDate @Column(nullable = false) private LocalDateTime modified; @Column(nullable = true) private LocalDateTime approved; @Column(name = "approved_by", length = 50) private String approvedBy; @Column(name = "STATUS_CD", length = 1) private String statusCd; @Column(name = "notes", length = 1000) private String notes; @ManyToOne @JoinColumn(name = "MEETING_ID") private Meeting meeting; @ManyToOne @JoinColumn(name = "USER_ID") private User user; public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public LocalDateTime getCreated() { return created; } public void setCreated(LocalDateTime created) { this.created = created; } public String getModifiedBy() { return modifiedBy; } public void setModifiedBy(String modifiedBy) { this.modifiedBy = modifiedBy; } public LocalDateTime getModified() { return modified; } public void setModified(LocalDateTime modified) { this.modified = modified; } public LocalDateTime getApproved() { return approved; } public void setApproved(LocalDateTime approved) { this.approved = approved; } public String getStatusCd() { return statusCd; } public void setStatusCd(String statusCd) { this.statusCd = statusCd; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public Meeting getMeeting() { return meeting; } public void setMeeting(Meeting meeting) { this.meeting = meeting; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getApprovedBy() { return approvedBy; } public void setApprovedBy(String approvedBy) { this.approvedBy = approvedBy; } }
19.709459
74
0.748029
493ccc9cb3b5ed7898857103e6e560d36a65b627
1,114
package LeetCode; /* 给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。 若可行,输出任意可行的结果。若不可行,返回空字符串。 示例 1: 输入: S = "aab" 输出: "aba" 示例 2: 输入: S = "aaab" 输出: "" 注意: S 只包含小写字母并且长度在[1, 500]区间内。 */ public class Solution767 { public String reorganizeString(String S) { StringBuilder res = new StringBuilder(); int[] words = new int[26]; for (int i = 0; i < S.length(); i ++){ words[S.charAt(i) - 'a'] ++; } for (int temp: words){ if (temp > (S.length() + 1) / 2){ return res.toString(); } } int max, last = -1; int maxIndex = -1; for (int i = 0; i < S.length(); i ++){ max = -1; for (int j = 0; j < 26 ; j ++){ if (last != j){ if (words[j] > max){ max = words[j]; maxIndex = j; } } } last = maxIndex; words[maxIndex] --; res.append((char) ('a' + maxIndex)); } return res.toString(); } }
20.62963
48
0.409336
6e7a006834071240fab68af5acd13fa7b61b37af
1,297
package com.dalma.fibrew.orm.entity; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table; import java.io.Serializable; import java.math.BigDecimal; /** * The persistent class for the IMP_ORDINI_RIGHE database table. * */ @Getter @Setter @Entity @Table(name="IMP_ORDINI_RIGHE") @NamedQuery(name="ImpOrdiniRighe.findAll", query="SELECT i FROM ImpOrdiniRighe i") public class ImpOrdiniRighe implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="RIG_ORDINE") private Long rigOrdine; // id to connect with IMP_ORDINI @Column(name="RIG_ARTICOLO") private String rigArticolo; // material ERP id @Column(name="RIG_ERRORE") private String rigErrore; // error inserted by Modula if anything goes wrong @Column(name="RIG_HOSTCAUS") private String rigHostcaus; // work station ERP id @Column(name="RIG_OF") private BigDecimal rigOf; // work order erp id @Column(name="RIG_QTAR") private BigDecimal rigQtar; // material's quantity @Column(name="RIG_STATUS") private String rigStatus; // Modula's import status @Column(name="RIG_SUB1") private String rigSub1; // material's batch }
24.471698
82
0.767926
9661283c23bf0c45b4ddee103ff0d18562d78706
1,182
/* * Copyright 2017-2020 EPAM Systems, Inc. (https://www.epam.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epam.pipeline.test.creator.pipeline; import com.epam.pipeline.entity.pipeline.PipelineRun; import static com.epam.pipeline.test.creator.CommonCreatorConstants.TEST_STRING; public final class PipelineCreatorUtils { private PipelineCreatorUtils() { } public static PipelineRun getPipelineRun(Long id, String owner) { final PipelineRun pipelineRun = new PipelineRun(); pipelineRun.setId(id); pipelineRun.setOwner(owner); pipelineRun.setName(TEST_STRING); return pipelineRun; } }
31.945946
80
0.732657
b3bff4fe5f7176e935867370a96510fd93a22f28
4,527
package cn.myperf4j.base.metric; import cn.myperf4j.base.util.NumUtils; /** * Created by LinShunkang on 2018/8/19 * <p> * 注意:以下成员变量的单位都是 KB */ public class JvmMemoryMetrics extends Metrics { private static final long serialVersionUID = -1501873958253505089L; private final long heapUsed; private final long heapMax; private final long nonHeapUsed; private final long nonHeapMax; private final long permGenUsed; private final long permGenMax; private final long metaspaceUsed; private final long metaspaceMax; private final long codeCacheUsed; private final long codeCacheMax; private final long oldGenUsed; private final long oldGenMax; private final long edenUsed; private final long edenMax; private final long survivorUsed; private final long survivorMax; public JvmMemoryMetrics(long heapUsed, long heapMax, long nonHeapUsed, long nonHeapMax, long permGenUsed, long permGenMax, long metaspaceUsed, long metaspaceMax, long codeCacheUsed, long codeCacheMax, long oldGenUsed, long oldGenMax, long edenUsed, long edenMax, long survivorUsed, long survivorMax) { this.heapUsed = heapUsed; this.heapMax = heapMax; this.nonHeapUsed = nonHeapUsed; this.nonHeapMax = nonHeapMax; this.permGenUsed = permGenUsed; this.permGenMax = permGenMax; this.metaspaceUsed = metaspaceUsed; this.metaspaceMax = metaspaceMax; this.codeCacheUsed = codeCacheUsed; this.codeCacheMax = codeCacheMax; this.oldGenUsed = oldGenUsed; this.oldGenMax = oldGenMax; this.edenUsed = edenUsed; this.edenMax = edenMax; this.survivorUsed = survivorUsed; this.survivorMax = survivorMax; } public long getHeapUsed() { return heapUsed; } public double getHeapUsedPercent() { return NumUtils.getPercent(heapUsed, heapMax); } public long getNonHeapUsed() { return nonHeapUsed; } public double getNonHeapUsedPercent() { return NumUtils.getPercent(nonHeapUsed, nonHeapMax); } public long getPermGenUsed() { return permGenUsed; } public double getPermGenUsedPercent() { return NumUtils.getPercent(permGenUsed, permGenMax); } public long getMetaspaceUsed() { return metaspaceUsed; } public double getMetaspaceUsedPercent() { return NumUtils.getPercent(metaspaceUsed, metaspaceMax); } public long getCodeCacheUsed() { return codeCacheUsed; } public double getCodeCacheUsedPercent() { return NumUtils.getPercent(codeCacheUsed, codeCacheMax); } public long getOldGenUsed() { return oldGenUsed; } public double getOldGenUsedPercent() { return NumUtils.getPercent(oldGenUsed, oldGenMax); } public long getEdenUsed() { return edenUsed; } public double getEdenUsedPercent() { return NumUtils.getPercent(edenUsed, edenMax); } public long getSurvivorUsed() { return survivorUsed; } public double getSurvivorUsedPercent() { return NumUtils.getPercent(survivorUsed, survivorMax); } @Override public String toString() { return "JvmMemoryMetrics{" + "heapUsed=" + heapUsed + ", heapMax=" + heapMax + ", nonHeapUsed=" + nonHeapUsed + ", nonHeapMax=" + nonHeapMax + ", permGenUsed=" + permGenUsed + ", permGenMax=" + permGenMax + ", metaspaceUsed=" + metaspaceUsed + ", metaspaceMax=" + metaspaceMax + ", codeCacheUsed=" + codeCacheUsed + ", codeCacheMax=" + codeCacheMax + ", oldGenUsed=" + oldGenUsed + ", oldGenMax=" + oldGenMax + ", edenUsed=" + edenUsed + ", edenMax=" + edenMax + ", survivorUsed=" + survivorUsed + ", survivorMax=" + survivorMax + "} " + super.toString(); } }
28.651899
71
0.57389
76f5f9503d158d068a1a10c16e33c87979138a37
309
// HIERARCHY /* A static method must not hide an instance method, * but a new method with the same name may be defined. */ public class Main extends foo{ public Main(){} public static int bar(String s){ return 123; } public static int test(){ return Main.bar("Hello World!"); } }
16.263158
57
0.647249
a59fb354cd725c8abfc13b88a19f6c73fab1e10e
1,799
/* * 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.aliyuncs.cloudwifi_pop.transform.v20191118; import com.aliyuncs.cloudwifi_pop.model.v20191118.DeleteApgroupSsidConfigResponse; import com.aliyuncs.cloudwifi_pop.model.v20191118.DeleteApgroupSsidConfigResponse.Data; import com.aliyuncs.transform.UnmarshallerContext; public class DeleteApgroupSsidConfigResponseUnmarshaller { public static DeleteApgroupSsidConfigResponse unmarshall(DeleteApgroupSsidConfigResponse deleteApgroupSsidConfigResponse, UnmarshallerContext _ctx) { deleteApgroupSsidConfigResponse.setRequestId(_ctx.stringValue("DeleteApgroupSsidConfigResponse.RequestId")); deleteApgroupSsidConfigResponse.setIsSuccess(_ctx.booleanValue("DeleteApgroupSsidConfigResponse.IsSuccess")); deleteApgroupSsidConfigResponse.setErrorCode(_ctx.integerValue("DeleteApgroupSsidConfigResponse.ErrorCode")); deleteApgroupSsidConfigResponse.setErrorMessage(_ctx.stringValue("DeleteApgroupSsidConfigResponse.ErrorMessage")); Data data = new Data(); data.setTaskId(_ctx.stringValue("DeleteApgroupSsidConfigResponse.Data.TaskId")); data.setId(_ctx.longValue("DeleteApgroupSsidConfigResponse.Data.Id")); deleteApgroupSsidConfigResponse.setData(data); return deleteApgroupSsidConfigResponse; } }
47.342105
150
0.821568
83b32c5ef1a0822fc38400b720d9ff0d45347b17
425
package net.energy.queue; /** * 任务直销结果,包含是否完成信息,以及方法执行的返回值 * * @author wuqh * * @param <T> */ public class TaskResult<T> { private T result; private boolean done; public T getResult() { return result; } public void setResult(T result) { this.result = result; } public boolean isDone() { return done; } public void setDone(boolean done) { this.done = done; } }
13.28125
37
0.597647
17156f8fb60b97a63535253ff7f0ffcec9d17b96
3,117
package com.appland.appmap.record; import com.alibaba.fastjson.JSON; import com.appland.appmap.output.v1.Event; import org.apache.commons.lang3.StringUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotNull; public class RecorderTest { @Before public void before() throws Exception { final Recorder.Metadata metadata = new Recorder.Metadata(); Recorder.getInstance().start(metadata); } @After public void after() throws Exception { if ( Recorder.getInstance().hasActiveSession()) { Recorder.getInstance().stop(); } } private static final int EVENT_COUNT = 3; private Recorder recordEvents() { final Recorder recorder = Recorder.getInstance(); final Long threadId = Thread.currentThread().getId(); final Event[] events = new Event[] { new Event(), new Event(), new Event(), }; for (int i = 0; i < events.length; i++) { final Event event = events[i]; event .setEvent("call") .setDefinedClass("SomeClass") .setMethodId("SomeMethod") .setStatic(false) .setLineNumber(315) .setThreadId(threadId); recorder.add(event); assertEquals(event, recorder.getLastEvent()); } return recorder; } @Test public void testCheckpoint() throws IOException { Recorder recorder = recordEvents(); final Recording recording = recorder.checkpoint(); Path targetPath = FileSystems.getDefault().getPath("build", "tmp", "snapshot.appmap.json"); recording.moveTo(targetPath.toString()); // Assert that it's parseable InputStream is = new FileInputStream(targetPath.toString()); Map appmap = JSON.parseObject(is, Map.class); assertEquals("[classMap, metadata, version, events]", appmap.keySet().toString()); } @Test public void testUnwriteableOutputFile() throws IOException { Recorder recorder = recordEvents(); final Recording recording = recorder.stop(); Exception exception = null; try { recording.moveTo("/no-such-directory"); } catch (RuntimeException e) { exception = e; } assertNotNull(exception); assertTrue(exception.toString().indexOf("java.lang.RuntimeException: ") == 0); } @Test public void testAllEventsWritten() throws IOException { Recorder recorder = recordEvents(); final Long threadId = Thread.currentThread().getId(); final Recording recording = recorder.stop(); StringWriter sw = new StringWriter(); recording.readFully(true, sw); String appmapJson = sw.toString(); final String expectedJson = "\"thread_id\":" + threadId; final int numMatches = StringUtils.countMatches(appmapJson, expectedJson); assertEquals(numMatches, EVENT_COUNT); } }
28.861111
95
0.688803
d45c414e5483df20afe6109946ce9206bea93fd0
408
package edu.csuft.andromeda; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("edu.csuft.andromeda.mapper") public class AndromedaApplication { public static void main(String[] args) { SpringApplication.run(AndromedaApplication.class, args); } }
27.2
68
0.82598
4cb122135949e4ab9162d590cfa4498b2c9aa47d
771
// // Generated by JTB 1.3.2 // package syntaxtree; /** * Grammar production: * f0 -> OmpPragma() * f1 -> ParallelDirective() * f2 -> Statement() */ public class ParallelConstruct implements Node { public OmpPragma f0; public ParallelDirective f1; public Statement f2; public ParallelConstruct(OmpPragma n0, ParallelDirective n1, Statement n2) { f0 = n0; f1 = n1; f2 = n2; } public void accept(visitor.Visitor v) { v.visit(this); } public <R,A> R accept(visitor.GJVisitor<R,A> v, A argu) { return v.visit(this,argu); } public <R> R accept(visitor.GJNoArguVisitor<R> v) { return v.visit(this); } public <A> void accept(visitor.GJVoidVisitor<A> v, A argu) { v.visit(this,argu); } }
20.289474
79
0.623865
719a225e469a3aeaa611a240cd77a8daa0e11114
756
/* * Copyright (c) 2021 Airbyte, Inc., all rights reserved. */ package io.airbyte.integrations.destination.gcs.writer; import com.amazonaws.services.s3.AmazonS3; import io.airbyte.integrations.destination.gcs.GcsDestinationConfig; import io.airbyte.integrations.destination.s3.writer.DestinationFileWriter; import io.airbyte.protocol.models.ConfiguredAirbyteStream; import java.sql.Timestamp; /** * Create different {@link GcsWriterFactory} based on {@link GcsDestinationConfig}. */ public interface GcsWriterFactory { DestinationFileWriter create(GcsDestinationConfig config, AmazonS3 s3Client, ConfiguredAirbyteStream configuredStream, Timestamp uploadTimestamp) throws Exception; }
30.24
83
0.755291
4bed412a11120037f2612fb2209f6a45e893d85b
7,553
package module3; //Java utilities libraries import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.data.PointFeature; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.marker.Marker; import de.fhpotsdam.unfolding.marker.SimplePointMarker; import de.fhpotsdam.unfolding.providers.MBTilesMapProvider; import de.fhpotsdam.unfolding.providers.OpenStreetMap; import de.fhpotsdam.unfolding.utils.MapUtils; import parsing.ParseFeed; import processing.core.PApplet; import java.util.ArrayList; import java.util.List; //import java.util.Collections; //import java.util.Comparator; //Processing library //Unfolding libraries //Parsing library /** * EarthquakeCityMap * An application with an interactive map displaying earthquake data. * Author: UC San Diego Intermediate Software Development MOOC team * * @author Your name here * Date: July 17, 2015 */ public class EarthquakeCityMap extends PApplet { // Less than this threshold is a light earthquake public static final float THRESHOLD_MODERATE = 5; // Less than this threshold is a minor earthquake public static final float THRESHOLD_LIGHT = 4; // You can ignore this. It's to keep eclipse from generating a warning. private static final long serialVersionUID = 1L; // IF YOU ARE WORKING OFFLINE, change the value of this variable to true private static final boolean offline = false; /** * This is where to find the local tiles, for working without an Internet connection */ public static String mbTilesString = "blankLight-1-3.mbtiles"; int colorTHRESHOLD_MODERATE = color(255, 255, 0); int colorHRESHOLD_LIGHT = color(150, 150, 0); int colorAnother = color(64, 44, 199); // The map private UnfoldingMap map; //feed with magnitude 2.5+ Earthquakes private String earthquakesURL = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.atom"; public void setup() { size(950, 600, OPENGL); if (offline) { map = new UnfoldingMap(this, 200, 50, 700, 500, new MBTilesMapProvider(mbTilesString)); earthquakesURL = "2.5_week.atom"; // Same feed, saved Aug 7, 2015, for working offline } else { map = new UnfoldingMap(this, 200, 50, 700, 500, new OpenStreetMap.OpenStreetMapProvider()); // IF YOU WANT TO TEST WITH A LOCAL FILE, uncomment the next line //earthquakesURL = "2.5_week.atom"; } map.zoomToLevel(2); MapUtils.createDefaultEventDispatcher(this, map); // The List you will populate with new SimplePointMarkers List<Marker> markers = new ArrayList<Marker>(); //Use provided parser to collect properties for each earthquake //PointFeatures have a getLocation method List<PointFeature> earthquakes = ParseFeed.parseEarthquake(this, earthquakesURL); //TODO (Step 3): Add a loop here that calls createMarker (see below) // to create a new SimplePointMarker for each PointFeature in // earthquakes. Then add each new SimplePointMarker to the // List markers (so that it will be added to the map in the line below) for (PointFeature earthquake : earthquakes) { markers.add(createMarker(earthquake)); } // Add the markers to the map so that they are displayed map.addMarkers(markers); } /* createMarker: A suggested helper method that takes in an earthquake * feature and returns a SimplePointMarker for that earthquake * * In step 3 You can use this method as-is. Call it from a loop in the * setp method. * * TODO (Step 4): Add code to this method so that it adds the proper * styling to each marker based on the magnitude of the earthquake. */ private SimplePointMarker createMarker(PointFeature feature) { // To print all of the features in a PointFeature (so you can see what they are) // uncomment the line below. Note this will only print if you call createMarker // from setup //System.out.println(feature.getProperties()); // Create a new SimplePointMarker at the location given by the PointFeature SimplePointMarker marker = new SimplePointMarker(feature.getLocation()); Object magObj = feature.getProperty("magnitude"); float mag = Float.parseFloat(magObj.toString()); System.out.println(Float.parseFloat(feature.getProperty("magnitude").toString())); // Here is an example of how to use Processing's color method to generate // an int that represents the color yellow. // TODO (Step 4): Add code below to style the marker's size and color // according to the magnitude of the earthquake. // Don't forget about the constants THRESHOLD_MODERATE and // THRESHOLD_LIGHT, which are declared above. // Rather than comparing the magnitude to a number directly, compare // the magnitude to these variables (and change their value in the code // above if you want to change what you mean by "moderate" and "light") if (mag < THRESHOLD_LIGHT) { marker.setRadius(12); marker.setColor(colorAnother); } else if (mag >= THRESHOLD_MODERATE) { marker.setRadius(18); marker.setColor(colorTHRESHOLD_MODERATE); } else { marker.setColor(colorHRESHOLD_LIGHT); marker.setRadius(15); } // Finally return the marker return marker; } public void draw() { background(9, 16, 38); map.draw(); addKey(); } // helper method to draw key in GUI // TODO: Implement this method to draw the key private void addKey() { noStroke(); fill(45, 51, 64); rect(30, 50, 150, 370, 10); fill(46, 154, 166); rect(35, 100, 140, 30, 10); rect(35, 145, 140, 30, 10); rect(35, 190, 140, 30, 10); rect(35, 235, 140, 30, 10); rect(35, 300, 140, 30, 10); fill(colorTHRESHOLD_MODERATE); noStroke(); ellipse(50, 115, 20, 20); fill(colorHRESHOLD_LIGHT); noStroke(); ellipse(50, 160, 20, 20); fill(colorAnother); noStroke(); ellipse(50, 205, 20, 20); fill(colorAnother); noStroke(); ellipse(50, 205, 20, 20); textSize(16); fill(255); textAlign(LEFT); text("MAGNITUDE", 60, 80); textSize(14); text(" > 5", 70, 122); text("from 4 to 5", 70, 167); text(" < 4", 70, 212); String time = String.valueOf(hour()); text(time + ":", 70, 255); time = String.valueOf(minute()); text(time + ":", 100, 255); time = String.valueOf(second()); text(time, 130, 255); fill(145, 1, 1); text("***SHAKE***", 55, 320); textSize(10); text("***Click right button***", 50, 345); // Remember you can use Processing's graphics methods here } public void mousePressed() { if (mousePressed && (mouseButton == RIGHT)){ noLoop(); double longitude = 180 - (Math.random() * 360); double latitude = 90 - (Math.random() * 180); SimplePointMarker markerRnd = new SimplePointMarker(new Location(longitude, latitude)); markerRnd.setColor(color(145, 1, 1)); markerRnd.setRadius(20); map.addMarker(markerRnd);} } public void mouseReleased() { loop(); } }
38.733333
110
0.643188
18a3242d836583727fb683c13438194ca245a714
563
package io.quarkus.registry.client; /** * Implements the basic queries a registry client is supposed to handle. * Although there are only a few kinds of queries, a registry is not required to support * all of them. For example, a registry may be configured to only provide platform extensions or * the other way around - provide only non-platform extensions but not platforms. */ public interface RegistryClient extends RegistryNonPlatformExtensionsResolver, RegistryPlatformExtensionsResolver, RegistryPlatformsResolver, RegistryConfigResolver { }
46.916667
114
0.801066
0ce83732f1d011d0cb9dc070fbd3a35bb39cc4be
1,894
package com.github.badoualy.telegram.tl.api; import com.github.badoualy.telegram.tl.core.TLObject; /** * Abstraction level for the following constructors: * <ul> * <li>{@link TLPageBlockAnchor}: pageBlockAnchor#ce0d37b0</li> * <li>{@link TLPageBlockAuthorDate}: pageBlockAuthorDate#baafe5e0</li> * <li>{@link TLPageBlockBlockquote}: pageBlockBlockquote#263d7c26</li> * <li>{@link TLPageBlockChannel}: pageBlockChannel#ef1751b5</li> * <li>{@link TLPageBlockCollage}: pageBlockCollage#8b31c4f</li> * <li>{@link TLPageBlockCover}: pageBlockCover#39f23300</li> * <li>{@link TLPageBlockDivider}: pageBlockDivider#db20b188</li> * <li>{@link TLPageBlockEmbed}: pageBlockEmbed#cde200d1</li> * <li>{@link TLPageBlockEmbedPost}: pageBlockEmbedPost#292c7be9</li> * <li>{@link TLPageBlockFooter}: pageBlockFooter#48870999</li> * <li>{@link TLPageBlockHeader}: pageBlockHeader#bfd064ec</li> * <li>{@link TLPageBlockList}: pageBlockList#3a58c7f4</li> * <li>{@link TLPageBlockParagraph}: pageBlockParagraph#467a0766</li> * <li>{@link TLPageBlockPhoto}: pageBlockPhoto#e9c69982</li> * <li>{@link TLPageBlockPreformatted}: pageBlockPreformatted#c070d93e</li> * <li>{@link TLPageBlockPullquote}: pageBlockPullquote#4f4456d3</li> * <li>{@link TLPageBlockSlideshow}: pageBlockSlideshow#130c8963</li> * <li>{@link TLPageBlockSubheader}: pageBlockSubheader#f12bb6e1</li> * <li>{@link TLPageBlockSubtitle}: pageBlockSubtitle#8ffa9a1f</li> * <li>{@link TLPageBlockTitle}: pageBlockTitle#70abc3fd</li> * <li>{@link TLPageBlockUnsupported}: pageBlockUnsupported#13567e8a</li> * <li>{@link TLPageBlockVideo}: pageBlockVideo#d9d71866</li> * </ul> * * @author Yannick Badoual [email protected] * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ public abstract class TLAbsPageBlock extends TLObject { public TLAbsPageBlock() { } }
47.35
95
0.751848
9cdf2d5095339f906447cfbd2bffc099be5e8935
1,053
package org.spongepowered.tools.obfuscation.interfaces; import java.util.Collection; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.tools.obfuscation.mapping.IMappingConsumer; public interface IObfuscationEnvironment { MappingMethod getObfMethod(MemberInfo paramMemberInfo); MappingMethod getObfMethod(MappingMethod paramMappingMethod); MappingMethod getObfMethod(MappingMethod paramMappingMethod, boolean paramBoolean); MappingField getObfField(MemberInfo paramMemberInfo); MappingField getObfField(MappingField paramMappingField); MappingField getObfField(MappingField paramMappingField, boolean paramBoolean); String getObfClass(String paramString); MemberInfo remapDescriptor(MemberInfo paramMemberInfo); String remapDescriptor(String paramString); void writeMappings(Collection<IMappingConsumer> paramCollection); }
35.1
85
0.837607
447112ddd76845ab67ac56b4776230ed2fb6373c
3,915
package org.ooc.frontend; /** * Contain the online (rather inline) help of the ooc compiler * * @author Amos Wenger */ public class Help { /** * Print a helpful help message that helps. */ public static void printHelp() { System.out.println("Usage: ooc [options] files\n"); System.out.println( "-v, -verbose verbose\n" + "-g, -debug compile with debug information\n" + "-noclean don't delete .c/.h files produced by\n" + " the backend\n" + "-gcc,-tcc,-icc,-clang,-onlygen choose the compiler backend (default=gcc)" + " onlygen doesn't launch any C compiler, and implies -noclean\n" + "-gc=[dynamic,static,off] link dynamically, link statically, or doesn't\n" + " link with the Boehm GC at all.\n" + "-driver=[combine,sequence] choose the driver to use. combine does all in one,\n" + " sequence does all the .c one after the other.\n" + "-sourcepath=output/path/ location of your source files\n" + "-outpath where to output the .c/.h files\n" + "-Ipath, -incpath=path where to find C headers\n" + "-Lpath, -libpath=path where to find libraries to link with\n" + "-lmylib link with library 'mylib'\n" + "-timing print how much time it took to compile\n" + "-r, -run runs the executable after compilation\n" + "+option pass 'option' to the C compiler, e.g. +-D_GNU_SOURCE, or +-O2" + "\nFor help about the backend options, run 'ooc -help-backends'" ); } /** * Print a helpful help message that helps about backends. */ public static void printHelpBackends() { System.out.println( "The available backends are: [none,gcc,make] and the default is gcc.\n" + "none just outputs the .c/.h files (be sure to have a main func)\n" + "gcc call the GNU C compiler with appropriate options\n" + "make generate a Makefile in the default output directory (ooc_tmp)\n" + "\nFor help about a specific backend, run 'ooc -help-gcc' for example" ); } /** * Print a helpful help message that helps about gcc. */ public static void printHelpGcc() { System.out.println( "gcc backend options:\n" + "-clean=[yes,no] delete (or not) temporary files. default: yes.\n" + " overriden by the global option -noclean\n" + "-verbose=[yes,no] print the gcc command lines called from the backend.\n" + " overriden by the global options -v, -verbose\n" + "-shout=[yes,no], -s prints a big fat [ OK ] at the end of the compilation\n" + " if it was successful (in green, on Linux platforms)\n" + "any other option passed to gcc\n" ); } /** * Print a helpful help message that helps about make. */ public static void printHelpMake() { System.out.println( "make backend options:\n" + "-cc=[gcc,icl] write a Makefile to be compatible with the said compiler\n" + "-link=libname.a link with the static library libname.a\n" + "any other option passed to the compiler\n" ); } /** * Print a helpful help message that helps about none. */ public static void printHelpNone() { System.out.println( "Be sure to have a main function! No .c/.h file will be outputted otherwise.\n\033[0;32;" +String.valueOf((int) (Math.random() * 6) + 31)+"m\n" + " | |\n" + " _ \\ _` | __| __| _ \\ __| _ \\ _` | _` | |\n" + " __/ ( |\\__ \\ | __/ | __/ ( | ( | _|\n" + "\\___|\\__,_|____/\\__|\\___|_| \\___|\\__, |\\__, | _)\n" + " |___/ |___/ \n\033[m" + "\nOh, one last thing: the cake is a lie. Too bad, eh.\n" ); } }
39.94898
97
0.563985
b4280ed1a5652602f9730080e8914352c9705f05
224
package de.adesso.budgeteer.core.budget.port.out; import de.adesso.budgeteer.core.budget.domain.Budget; import java.util.Optional; public interface GetBudgetByIdPort { Optional<Budget> getBudgetById(long budgetId); }
22.4
53
0.799107
347eaf7f0a7e524efc31221f88220cbe39b76560
13,432
package com.uniclau.simplefile; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.uniclau.network.URLNetRequester; import android.content.Context; import android.content.res.AssetManager; import android.os.Environment; import android.util.Base64; import android.util.Log; public class SimpleFilePlugin extends CordovaPlugin { private final String TAG="SimpleFilePlugin"; @Override public void onPause(boolean multitasking) { Log.d(TAG, "onPause"); //URLNetRequester.CancelAll(); super.onPause(multitasking); } @Override public void onResume(boolean multitasking) { Log.d(TAG, "onResume " ); super.onResume(multitasking); } private void DeleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { for (File child : fileOrDirectory.listFiles()) { DeleteRecursive(child); } } fileOrDirectory.delete(); } private String getRootPath(Context ctx, String type) { if ("external".equals(type)) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return Environment.getExternalStorageDirectory().getAbsolutePath(); } else { String packageName = ctx.getPackageName(); return "/data/data/" + packageName; } } else if ("internal".equals(type)) { return ctx.getFilesDir().getAbsolutePath(); } else if ("user".equals(type)) { return ctx.getFilesDir().getAbsolutePath(); } else if ("cache".equals(type)) { return ctx.getCacheDir().getAbsolutePath(); } else if ("tmp".equals(type)) { return ctx.getCacheDir().getAbsolutePath(); } else { return ""; } } private byte[] readFile(Context ctx, String root, String fileName) throws Exception { Log.d(TAG, "start Read: " + root + "/" + fileName ); byte[] buff; if ("bundle".equals(root)) { AssetManager assets = ctx.getAssets(); InputStream is = assets.open(fileName); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); int bytesRead; byte[] buf = new byte[4 * 1024]; // 4K buffer while ((bytesRead = is.read(buf)) != -1) { outstream.write(buf, 0, bytesRead); } buff = outstream.toByteArray(); } else { String rootPath = getRootPath(ctx, root); File f = new File(rootPath + "/" + fileName); if (!f.exists()) { Log.d(TAG, "The file does not exist: " + fileName); throw new Exception("The file does not exist: " + fileName); } FileInputStream is = new FileInputStream(rootPath + "/" +fileName); buff = new byte[(int)f.length()]; is.read(buff); is.close(); } Log.d(TAG, "end Read: " + root + "/" + fileName ); return buff; } private boolean readFile(final Context ctx, final JSONArray params, final CallbackContext callbackContext) throws Exception { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { try { String root = params.getString(0); String fileName = params.getString(1); byte [] buff = readFile(ctx, root, fileName); String data64 = Base64.encodeToString(buff, Base64.DEFAULT | Base64.NO_WRAP); callbackContext.success(data64); } catch(Exception e) { callbackContext.error(e.getMessage()); return; } } }); return true; } private void writeFile(Context ctx, String root, String fileName, byte [] data) throws Exception { Log.d(TAG, "start write: " + root + "/" + fileName ); if ("bundle".equals(root)) { throw new Exception("The bundle file system is read only"); } String rootPath = getRootPath(ctx, root); File f= new File(rootPath + "/" + fileName); if (f.exists()) { f.delete(); } File dir = f.getParentFile(); dir.mkdirs(); FileOutputStream fstream; fstream = new FileOutputStream(rootPath + "/" + fileName); fstream.write(data); fstream.flush(); fstream.close(); Log.d(TAG, "end write: " + root + "/" + fileName ); } private boolean writeFile(final Context ctx, final JSONArray params, final CallbackContext callbackContext) throws Exception { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { try { String root = params.getString(0); String fileName = params.getString(1); String data64 = params.getString(2); byte [] data = Base64.decode(data64, Base64.DEFAULT); writeFile(ctx, root, fileName, data); callbackContext.success(); } catch(Exception e) { callbackContext.error(e.getMessage()); } } }); return true; } private boolean remove(final Context ctx, final JSONArray args, final CallbackContext callbackContext) throws Exception { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { try { String root = args.getString(0); if ("bundle".equals(root)) { throw new Exception("The bundle file system is read only"); } String rootPath = getRootPath(ctx, root); String fileName = args.getString(1); File f= new File(rootPath + "/" + fileName); if (f.exists()) { DeleteRecursive(f); } callbackContext.success(); } catch(Exception e) { callbackContext.error(e.getMessage()); } } }); return true; } private boolean download(final Context ctx, JSONArray params, final CallbackContext callbackContext) throws Exception { final JSONArray args = params; final String root = args.getString(0); if ("bundle".equals(root)) { callbackContext.error("The bundle file system is read only"); return false; } String url; try { url = args.getString(1); } catch(Exception e) { return false;} URLNetRequester.NewRequest("", url, url, new URLNetRequester.AnswerHandler() { @Override public void OnAnswer(Object CallbackParam, byte[] Res) { if (Res == null) { callbackContext.error("Network Error"); return; } try { String rootPath = getRootPath(ctx, root); String fileName = args.getString(2); File f= new File(rootPath + "/" + fileName); if (f.exists()) { f.delete(); } File dir = f.getParentFile(); dir.mkdirs(); FileOutputStream fstream; fstream = new FileOutputStream(rootPath + "/" +fileName); fstream.write(Res); fstream.flush(); fstream.close(); callbackContext.success(); } catch(Exception e) { callbackContext.error(e.getMessage()); } } }); return true; } private boolean getUrl(final Context ctx, JSONArray args, final CallbackContext callbackContext) throws Exception { String root = args.getString(0); String fileName = args.getString(1); String res; if ("bundle".equals(root)) { res = "file:///android_asset/" + fileName; } else { String rootPath = getRootPath(ctx,root); res = "file://" + rootPath + "/" + fileName; } callbackContext.success(res); return true; } private boolean createFolder(final Context ctx, final JSONArray params, final CallbackContext callbackContext) throws Exception { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { try { String root = params.getString(0); if ("bundle".equals(root)) { throw new Exception("The bundle file system is read only"); } String rootPath = getRootPath(ctx,root); String dirName = params.getString(1); File dir = new File(rootPath + "/" + dirName); dir.mkdirs(); callbackContext.success(); } catch(Exception e) { Log.d(TAG, e.getMessage()); callbackContext.error(e.getMessage()); } }; }); return true; } private JSONArray list(Context ctx, String root, String dirName) throws Exception { Log.d(TAG, "start list: " + root + "/" + dirName ); JSONArray res = new JSONArray(); if ("bundle".equals(root)) { if (".".equals(dirName)) dirName = ""; Log.d(TAG, "list - 1"); String [] files = ctx.getAssets().list(dirName); Log.d(TAG, "list - 2"); if (files.length == 0) { boolean isDirectory = true; try { // This function will raise an exception if it is a directory. Log.d(TAG, "list - 3"); ctx.getAssets().open(dirName); Log.d(TAG, "list - 4"); isDirectory = false; } catch (Exception e) {} if (!isDirectory) { Log.d(TAG, "List error: Not a directory: " + dirName); throw new Exception(dirName + " is not a directory"); } } int i; for (i=0; i<files.length; i++) { JSONObject fileObject = new JSONObject(); fileObject.put("name", files[i]); fileObject.put("isFolder", true); try { Log.d(TAG, "list - 2.1"); String [] subFolders = ctx.getAssets().list("".equals(dirName) ? files[i] : dirName + "/" +files[i]); Log.d(TAG, "list - 2.2"); if (subFolders.length == 0) { fileObject.put("isFolder", false); } } catch(Exception e) { fileObject.put("isFolder", false); } res.put(fileObject); } } else { String rootPath = getRootPath(ctx,root); File dir; if ("".equals(dirName) || ".".equals(dirName)) { dir = new File(rootPath); } else { dir = new File(rootPath + "/" + dirName); } Log.d(TAG, "list - 5"); if (!dir.exists()) { Log.d(TAG, "The folder does not exist: " + dirName); throw new Error("The folder does not exist: " + dirName); } Log.d(TAG, "list - 6"); if (!dir.isDirectory()) { Log.d(TAG, dirName + " is not a directory"); throw new Error(dirName + " is not a directory"); } Log.d(TAG, "list - 7"); File []childs =dir.listFiles(); int i; for (i=0; i<childs.length; i++) { JSONObject fileObject = new JSONObject(); fileObject.put("name", childs[i].getName()); fileObject.put("isFolder", childs[i].isDirectory()); res.put(fileObject); } } Log.d(TAG, "end list: " + root + "/" + dirName ); return res; } private boolean list(final Context ctx, final JSONArray params, final CallbackContext callbackContext) throws Exception { Log.d(TAG, "start list (main thread): " ); cordova.getActivity().runOnUiThread(new Runnable() { public void run() { try { String root = params.getString(0); String dirName = params.getString(1); JSONArray res = list(ctx, root, dirName); callbackContext.success(res); Log.d(TAG, "end list (main thread)"); } catch(Exception e) { callbackContext.error(e.getMessage()); Log.d(TAG, e.getMessage()); } } }); return true; } private void copy(Context ctx, String rootFrom, String fileFrom,String rootTo,String fileTo) throws Exception { Boolean isDir=false; JSONArray l = null; try { l=list(ctx, rootFrom, fileFrom); isDir = true; } catch (Exception E){}; if (!isDir) { byte [] data = readFile(ctx, rootFrom, fileFrom); writeFile(ctx, rootTo,fileTo, data); return; } int i; for (i=0; i<l.length(); i++) { String childName = l.getJSONObject(i).getString("name"); isDir = l.getJSONObject(i).getBoolean("isFolder"); String newFrom = fileFrom; if (! "".equals(newFrom)) { newFrom += "/"; } newFrom += childName; String newTo = fileTo; if (! "".equals(newTo)) { newTo += "/"; } newTo += childName; if (isDir) { copy(ctx, rootFrom, newFrom, rootTo, newTo); } else { byte [] data = readFile(ctx, rootFrom, newFrom); writeFile(ctx, rootTo,newTo, data); } } } private boolean copy(final Context ctx, final JSONArray params, final CallbackContext callbackContext) throws Exception { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String rootFrom = params.getString(0); String fileFrom = params.getString(1); String rootTo = params.getString(2); String fileTo = params.getString(3); copy(ctx, rootFrom, fileFrom, rootTo, fileTo); callbackContext.success(); } catch(Exception e) { Log.d(TAG, "ERROR copy: " + e.getMessage()); callbackContext.error(e.getMessage()); } } }); return true; } @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { try { final Context ctx= this.cordova.getActivity(); if ("read".equals(action)) { return readFile(ctx, args, callbackContext); } else if ("write".equals(action)) { return writeFile(ctx, args, callbackContext); } else if ("remove".equals(action)) { return remove(ctx, args, callbackContext); } else if ("download".equals(action)) { return download(ctx, args, callbackContext); } else if ("getUrl".equals(action)) { return getUrl(ctx, args, callbackContext); } else if ("createFolder".equals(action)) { return createFolder(ctx, args, callbackContext); } else if ("list".equals(action)) { return list(ctx, args, callbackContext); } else if ("copy".equals(action)) { return copy(ctx, args, callbackContext); } return false; } catch(Exception e) { System.err.println("Exception: " + e.getMessage()); callbackContext.error(e.getMessage()); return false; } } }
27.694845
130
0.63654
9eb33c8d30c8a1861c39aa149f82725fe39a5167
1,318
/** * A variable definition. * @param modifiers variable modifiers * @param name variable name * @param vartype type of the variable * @param init variables initial value * @param sym symbol */ public static class JCVariableDecl extends JCStatement implements VariableTree { public JCModifiers mods; public Name name; public JCExpression vartype; public JCExpression init; public VarSymbol sym; protected JCVariableDecl(JCModifiers mods, Name name, JCExpression vartype, JCExpression init, VarSymbol sym) { super(VARDEF); this.mods = mods; this.name = name; this.vartype = vartype; this.init = init; this.sym = sym; } @Override public void accept(Visitor v) { v.visitVarDef(this); } public Kind getKind() { return Kind.VARIABLE; } public JCModifiers getModifiers() { return mods; } public Name getName() { return name; } public JCTree getType() { return vartype; } public JCExpression getInitializer() { return init; } @Override public <R,D> R accept(TreeVisitor<R,D> v, D d) { return v.visitVariable(this, d); } }
32.146341
84
0.584219
581ab2b392ac3fdbc0d7b4855f684ded36bff7f1
120
/** * Rabbitmq Queue Consumer(Listener) related classes */ package io.github.ykalay.rabbitmqtunnel.rabbitmq.listener;
24
58
0.783333
7b2f6dbc6f198e68b4dc16e9d7a41b049f2c01e0
545
package plusmul; import java.util.Scanner; public class PM { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int 값; System.out.println("2 이상의 정수를 입력하시오."); 값=sc.nextInt(); int i; int 합=0; if(값<10) { if(값>1) { for(i=1;i<=9;i++) System.out.println( 값 + "*" + i + "=" + 값 * i); }else System.out.println("범위 내의 정수가 아닙니다."); }else { for(i=1;i<=값;i++) 합=합+i; System.out.println("1부터 " + 값 + "의 합은 " + 합 + " 입니다!"); } } }
12.97619
58
0.488073
856e5f73fa8b764f9176c11e38aa11c3b4f2b91b
2,358
/* * Copyright 2014-2017 Rudy De Busscher (www.c4j.be) * * 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 be.c4j.demo.security.demo.model; import be.c4j.ee.security.permission.NamedPermission; /** * This is an entity object in production type application */ public class HRAppPermission implements NamedPermission { private String name; private String domain; private String actions; private String target; public HRAppPermission(String name, String domain, String actions, String target) { this.name = name; this.domain = domain; this.actions = actions; this.target = target; } public String getName() { return name; } @Override public String name() { return getName(); } public void setName(String name) { this.name = name; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getActions() { return actions; } public void setActions(String actions) { this.actions = actions; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public String getDomainPermissionRepresentation() { return domain + ':' + actions + ':' + target; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } HRAppPermission that = (HRAppPermission) o; if (!name.equals(that.name)) { return false; } return true; } @Override public int hashCode() { return name.hashCode(); } }
23.346535
87
0.620441
fa4f8fdf23473b8cf85c6489d945be3c7e923e71
4,139
/* * Copyright 2018 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.clova.extension.boot.message.context; import java.io.Serializable; import javax.validation.Valid; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonValue; import lombok.Data; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * An object that contains the context information of the client system. */ @Data public class SystemContext implements ContextProperty { private static final long serialVersionUID = 1L; @NotNull @Valid private Application application; @NotNull @Valid private Device device; @NotNull @Valid private User user; /** * An object that contains the context information of the extension. */ @Data public static class Application implements Serializable { private static final long serialVersionUID = 1L; @NotBlank private String applicationId; } /** * An object that contains the context information of the client device. */ @Data public static class Device implements Serializable { private static final long serialVersionUID = 1L; @NotBlank private String deviceId; @NotNull @Valid private Display display; @Data public static class Display implements Serializable { private static final long serialVersionUID = 1L; @Valid private ContentLayer contentLayer; private Integer dpi; private Orientation orientation; @NotNull private Size size; @AssertTrue @JsonIgnore public boolean isValidContentLayer() { if (size == null || size == Size.NONE) { return true; } return contentLayer != null; } @AssertTrue @JsonIgnore public boolean isValidDpi() { if (size == null || size == Size.NONE) { return true; } return dpi != null; } @Data public static class ContentLayer implements Serializable { private static final long serialVersionUID = 1L; @NotNull private Integer width; @NotNull private Integer height; } @RequiredArgsConstructor public enum Orientation { LANDSCAPE("landscape"), PORTRAIT("portrait"); @Getter(onMethod = @__(@JsonValue)) private final String value; } @RequiredArgsConstructor public enum Size { NONE("none"), S100("s100"), M100("m100"), L100("l100"), XL100("xl100"), CUSTOM("custom"); @Getter(onMethod = @__(@JsonValue)) private final String value; } } } /** * The default user linked to the device. */ @Data public static class User implements Serializable { private static final long serialVersionUID = 1L; @NotBlank private String userId; private String accessToken; } }
26.363057
78
0.595313
d8e8f18b6699adbd1d55d57e0063e5ec28bee071
188
package com.github.jeasyrest.core; import java.io.IOException; import java.io.Reader; public interface IUnmarshaller<T> { T unmarshall(Reader reader) throws IOException; }
17.090909
55
0.739362
700c12eff8f57d96f1b50b487b84082537a9d1fd
25,620
/** * * Copyright 2015-2021 Florian Schmaus * * 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.igniterealtime.smack.inttest; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Method; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode; import org.jivesoftware.smack.debugger.ConsoleDebugger; import org.jivesoftware.smack.util.CollectionUtil; import org.jivesoftware.smack.util.Function; import org.jivesoftware.smack.util.Objects; import org.jivesoftware.smack.util.ParserUtils; import org.jivesoftware.smack.util.SslContextFactory; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.debugger.EnhancedDebugger; import eu.geekplace.javapinning.java7.Java7Pinning; import org.jxmpp.jid.DomainBareJid; import org.jxmpp.jid.impl.JidCreate; import org.jxmpp.stringprep.XmppStringprepException; // TODO: Rename to SinttestConfiguration. public final class Configuration { private static final Logger LOGGER = Logger.getLogger(Configuration.class.getName()); public enum AccountRegistration { disabled, inBandRegistration, serviceAdministration, } public enum Debugger { none, console, enhanced, } public enum DnsResolver { minidns, javax, dnsjava, } public final DomainBareJid service; public final String serviceTlsPin; public final SslContextFactory sslContextFactory; public final SecurityMode securityMode; public final int replyTimeout; public final AccountRegistration accountRegistration; public final String adminAccountUsername; public final String adminAccountPassword; public final String accountOneUsername; public final String accountOnePassword; public final String accountTwoUsername; public final String accountTwoPassword; public final String accountThreeUsername; public final String accountThreePassword; public final Debugger debugger; public final Set<String> enabledTests; private final Map<String, Set<String>> enabledTestsMap; public final Set<String> disabledTests; private final Map<String, Set<String>> disabledTestsMap; public final String defaultConnectionNickname; public final Set<String> enabledConnections; public final Set<String> disabledConnections; public final Set<String> testPackages; public final ConnectionConfigurationBuilderApplier configurationApplier; public final boolean verbose; public final DnsResolver dnsResolver; public enum CompatibilityMode { standardsCompliant, ejabberd, } public final CompatibilityMode compatibilityMode; private Configuration(Configuration.Builder builder) throws KeyManagementException, NoSuchAlgorithmException { service = Objects.requireNonNull(builder.service, "'service' must be set. Either via 'properties' files or via system property 'sinttest.service'."); serviceTlsPin = builder.serviceTlsPin; if (serviceTlsPin != null) { SSLContext sslContext = Java7Pinning.forPin(serviceTlsPin); sslContextFactory = () -> sslContext; } else { sslContextFactory = null; } securityMode = builder.securityMode; if (builder.replyTimeout > 0) { replyTimeout = builder.replyTimeout; } else { replyTimeout = 60000; } debugger = builder.debugger; if (StringUtils.isNotEmpty(builder.adminAccountUsername, builder.adminAccountPassword)) { accountRegistration = AccountRegistration.serviceAdministration; } else if (StringUtils.isNotEmpty(builder.accountOneUsername, builder.accountOnePassword, builder.accountTwoUsername, builder.accountTwoPassword, builder.accountThreeUsername, builder.accountThreePassword)) { accountRegistration = AccountRegistration.disabled; } else { accountRegistration = AccountRegistration.inBandRegistration; } this.adminAccountUsername = builder.adminAccountUsername; this.adminAccountPassword = builder.adminAccountPassword; boolean accountOnePasswordSet = StringUtils.isNotEmpty(builder.accountOnePassword); if (accountOnePasswordSet != StringUtils.isNotEmpty(builder.accountTwoPassword) || accountOnePasswordSet != StringUtils.isNotEmpty(builder.accountThreePassword)) { // Ensure the invariant that either all main accounts have a password set, or none. throw new IllegalArgumentException(); } this.accountOneUsername = builder.accountOneUsername; this.accountOnePassword = builder.accountOnePassword; this.accountTwoUsername = builder.accountTwoUsername; this.accountTwoPassword = builder.accountTwoPassword; this.accountThreeUsername = builder.accountThreeUsername; this.accountThreePassword = builder.accountThreePassword; this.enabledTests = CollectionUtil.nullSafeUnmodifiableSet(builder.enabledTests); this.enabledTestsMap = convertTestsToMap(enabledTests); this.disabledTests = CollectionUtil.nullSafeUnmodifiableSet(builder.disabledTests); this.disabledTestsMap = convertTestsToMap(disabledTests); this.defaultConnectionNickname = builder.defaultConnectionNickname; this.enabledConnections = builder.enabledConnections; this.disabledConnections = builder.disabledConnections; this.testPackages = builder.testPackages; this.configurationApplier = b -> { if (sslContextFactory != null) { b.setSslContextFactory(sslContextFactory); } b.setSecurityMode(securityMode); b.setXmppDomain(service); switch (debugger) { case enhanced: b.setDebuggerFactory(EnhancedDebugger.Factory.INSTANCE); break; case console: b.setDebuggerFactory(ConsoleDebugger.Factory.INSTANCE); break; case none: // Nothing to do :). break; } }; this.verbose = builder.verbose; this.dnsResolver = builder.dnsResolver; this.compatibilityMode = builder.compatibilityMode; } public boolean isAccountRegistrationPossible() { return accountRegistration != AccountRegistration.disabled; } public static Builder builder() { return new Builder(); } public static final class Builder { private DomainBareJid service; private String serviceTlsPin; private SecurityMode securityMode; private int replyTimeout; private String adminAccountUsername; private String adminAccountPassword; private String accountOneUsername; private String accountOnePassword; private String accountTwoUsername; private String accountTwoPassword; public String accountThreeUsername; public String accountThreePassword; private Debugger debugger = Debugger.none; private Set<String> enabledTests; private Set<String> disabledTests; private String defaultConnectionNickname; private Set<String> enabledConnections; private Set<String> disabledConnections; private Set<String> testPackages; private boolean verbose; private DnsResolver dnsResolver = DnsResolver.minidns; private CompatibilityMode compatibilityMode = CompatibilityMode.standardsCompliant; private Builder() { } public Builder setService(String service) throws XmppStringprepException { if (service == null) { // Do nothing if user did not specify the XMPP service domain. When the builder // builds a configuration using build() it will throw a meaningful exception. return this; } return setService(JidCreate.domainBareFrom(service)); } public Builder setService(DomainBareJid service) { this.service = service; return this; } public Builder addEnabledTest(Class<? extends AbstractSmackIntTest> enabledTest) { if (enabledTests == null) { enabledTests = new HashSet<>(); } enabledTests.add(enabledTest.getName()); // Also add the package of the test as test package return addTestPackage(enabledTest.getPackage().getName()); } private void ensureTestPackagesIsSet(int length) { if (testPackages == null) { testPackages = new HashSet<>(length); } } public Builder addTestPackage(String testPackage) { ensureTestPackagesIsSet(4); testPackages.add(testPackage); return this; } public Builder setAdminAccountUsernameAndPassword(String adminAccountUsername, String adminAccountPassword) { this.adminAccountUsername = StringUtils.requireNotNullNorEmpty(adminAccountUsername, "adminAccountUsername must not be null nor empty"); this.adminAccountPassword = StringUtils.requireNotNullNorEmpty(adminAccountPassword, "adminAccountPassword must no be null nor empty"); return this; } public Builder setUsernamesAndPassword(String accountOneUsername, String accountOnePassword, String accountTwoUsername, String accountTwoPassword, String accountThreeUsername, String accountThreePassword) { this.accountOneUsername = StringUtils.requireNotNullNorEmpty(accountOneUsername, "accountOneUsername must not be null nor empty"); this.accountOnePassword = StringUtils.requireNotNullNorEmpty(accountOnePassword, "accountOnePassword must not be null nor empty"); this.accountTwoUsername = StringUtils.requireNotNullNorEmpty(accountTwoUsername, "accountTwoUsername must not be null nor empty"); this.accountTwoPassword = StringUtils.requireNotNullNorEmpty(accountTwoPassword, "accountTwoPasswordmust not be null nor empty"); this.accountThreeUsername = StringUtils.requireNotNullNorEmpty(accountThreeUsername, "accountThreeUsername must not be null nor empty"); this.accountThreePassword = StringUtils.requireNotNullNorEmpty(accountThreePassword, "accountThreePassword must not be null nor empty"); return this; } public Builder setServiceTlsPin(String tlsPin) { this.serviceTlsPin = tlsPin; return this; } public Builder setSecurityMode(String securityModeString) { if (securityModeString != null) { securityMode = SecurityMode.valueOf(securityModeString); } else { securityMode = SecurityMode.required; } return this; } public Builder setReplyTimeout(String timeout) { if (timeout != null) { replyTimeout = Integer.valueOf(timeout); } return this; } @SuppressWarnings("fallthrough") public Builder setDebugger(String debuggerString) { if (debuggerString == null) { return this; } switch (debuggerString) { case "false": // For backwards compatibility settings with previous boolean setting. LOGGER.warning("Debug string \"" + debuggerString + "\" is deprecated, please use \"none\" instead"); case "none": debugger = Debugger.none; break; case "true": // For backwards compatibility settings with previous boolean setting. LOGGER.warning("Debug string \"" + debuggerString + "\" is deprecated, please use \"console\" instead"); case "console": debugger = Debugger.console; break; case "enhanced": debugger = Debugger.enhanced; break; default: throw new IllegalArgumentException("Unrecognized debugger string: " + debuggerString); } return this; } public Builder setEnabledTests(String enabledTestsString) { enabledTests = getTestSetFrom(enabledTestsString); return this; } public Builder setDisabledTests(String disabledTestsString) { disabledTests = getTestSetFrom(disabledTestsString); return this; } public Builder setDefaultConnection(String defaultConnectionNickname) { this.defaultConnectionNickname = defaultConnectionNickname; return this; } public Builder setEnabledConnections(String enabledConnectionsString) { enabledConnections = split(enabledConnectionsString); return this; } public Builder setDisabledConnections(String disabledConnectionsString) { disabledConnections = split(disabledConnectionsString); return this; } public Builder addTestPackages(String testPackagesString) { if (testPackagesString != null) { String[] testPackagesArray = testPackagesString.split(","); ensureTestPackagesIsSet(testPackagesArray.length); for (String s : testPackagesArray) { testPackages.add(s.trim()); } } return this; } public Builder addTestPackages(String[] testPackagesString) { if (testPackagesString == null) { return this; } ensureTestPackagesIsSet(testPackagesString.length); for (String testPackage : testPackagesString) { testPackages.add(testPackage); } return this; } public Builder setVerbose(boolean verbose) { this.verbose = verbose; return this; } public Builder setVerbose(String verboseBooleanString) { if (verboseBooleanString == null) { return this; } boolean verbose = ParserUtils.parseXmlBoolean(verboseBooleanString); return setVerbose(verbose); } public Builder setDnsResolver(DnsResolver dnsResolver) { this.dnsResolver = Objects.requireNonNull(dnsResolver); return this; } public Builder setDnsResolver(String dnsResolverString) { if (dnsResolverString == null) { return this; } DnsResolver dnsResolver = DnsResolver.valueOf(dnsResolverString); return setDnsResolver(dnsResolver); } public Builder setCompatibilityMode(CompatibilityMode compatibilityMode) { this.compatibilityMode = compatibilityMode; return this; } public Builder setCompatibilityMode(String compatibilityModeString) { if (compatibilityModeString == null) { return this; } CompatibilityMode compatibilityMode = CompatibilityMode.valueOf(compatibilityModeString); return setCompatibilityMode(compatibilityMode); } public Configuration build() throws KeyManagementException, NoSuchAlgorithmException { return new Configuration(this); } } private static final String SINTTEST = "sinttest."; public static Configuration newConfiguration(String[] testPackages) throws IOException, KeyManagementException, NoSuchAlgorithmException { Properties properties = new Properties(); File propertiesFile = findPropertiesFile(); if (propertiesFile != null) { try (FileInputStream in = new FileInputStream(propertiesFile)) { properties.load(in); } } // Properties set via the system override the file properties Properties systemProperties = System.getProperties(); for (Map.Entry<Object, Object> entry : systemProperties.entrySet()) { String key = (String) entry.getKey(); if (!key.startsWith(SINTTEST)) { continue; } key = key.substring(SINTTEST.length()); String value = (String) entry.getValue(); properties.put(key, value); } Builder builder = builder(); builder.setService(properties.getProperty("service")); builder.setServiceTlsPin(properties.getProperty("serviceTlsPin")); builder.setSecurityMode(properties.getProperty("securityMode")); builder.setReplyTimeout(properties.getProperty("replyTimeout", "60000")); String adminAccountUsername = properties.getProperty("adminAccountUsername"); String adminAccountPassword = properties.getProperty("adminAccountPassword"); if (StringUtils.isNotEmpty(adminAccountUsername, adminAccountPassword)) { builder.setAdminAccountUsernameAndPassword(adminAccountUsername, adminAccountPassword); } String accountOneUsername = properties.getProperty("accountOneUsername"); String accountOnePassword = properties.getProperty("accountOnePassword"); String accountTwoUsername = properties.getProperty("accountTwoUsername"); String accountTwoPassword = properties.getProperty("accountTwoPassword"); String accountThreeUsername = properties.getProperty("accountThreeUsername"); String accountThreePassword = properties.getProperty("accountThreePassword"); if (accountOneUsername != null || accountOnePassword != null || accountTwoUsername != null || accountTwoPassword != null || accountThreeUsername != null || accountThreePassword != null) { builder.setUsernamesAndPassword(accountOneUsername, accountOnePassword, accountTwoUsername, accountTwoPassword, accountThreeUsername, accountThreePassword); } String debugString = properties.getProperty("debug"); if (debugString != null) { LOGGER.warning("Usage of depreacted 'debug' option detected, please use 'debugger' instead"); builder.setDebugger(debugString); } builder.setDebugger(properties.getProperty("debugger")); builder.setEnabledTests(properties.getProperty("enabledTests")); builder.setDisabledTests(properties.getProperty("disabledTests")); builder.setDefaultConnection(properties.getProperty("defaultConnection")); builder.setEnabledConnections(properties.getProperty("enabledConnections")); builder.setDisabledConnections(properties.getProperty("disabledConnections")); builder.addTestPackages(properties.getProperty("testPackages")); builder.addTestPackages(testPackages); builder.setVerbose(properties.getProperty("verbose")); builder.setDnsResolver(properties.getProperty("dnsResolver")); builder.setCompatibilityMode(properties.getProperty("compatibilityMode")); return builder.build(); } private static File findPropertiesFile() { List<String> possibleLocations = new LinkedList<>(); possibleLocations.add("properties"); String userHome = System.getProperty("user.home"); if (userHome != null) { possibleLocations.add(userHome + "/.config/smack-integration-test/properties"); } for (String possibleLocation : possibleLocations) { File res = new File(possibleLocation); if (res.isFile()) return res; } return null; } private static Set<String> split(String input) { return split(input, Function.identity()); } private static Set<String> split(String input, Function<String, String> transformer) { if (input == null) { return null; } String[] inputArray = input.split(","); Set<String> res = new HashSet<>(inputArray.length); for (String s : inputArray) { s = transformer.apply(s); boolean newElement = res.add(s); if (!newElement) { throw new IllegalArgumentException("The argument '" + s + "' was already provided."); } } return res; } private static Set<String> getTestSetFrom(String input) { return split(input, s -> { s = s.trim(); if (s.startsWith("smackx.") || s.startsWith("smack.")) { s = "org.jivesoftware." + s; } return s; }); } private static Map<String, Set<String>> convertTestsToMap(Set<String> tests) { Map<String, Set<String>> res = new HashMap<>(); for (String test : tests) { String[] testParts = test.split("\\."); if (testParts.length == 1) { // The whole test specification does not contain a dot, assume it is a test class specification. res.put(test, Collections.emptySet()); continue; } String lastTestPart = testParts[testParts.length - 1]; if (lastTestPart.isEmpty()) { throw new IllegalArgumentException("Invalid test specifier: " + test); } char firstCharOfLastTestPart = lastTestPart.charAt(0); if (!Character.isLowerCase(firstCharOfLastTestPart)) { // The first character of the last test part is not lowercase, assume this is a fully qualified test // class specification, e.g. org.foo.bar.TestClass. res.put(test, Collections.emptySet()); } // The first character of the last test part is lowercase, assume this is a test class *and* method name // specification. String testMethodName = lastTestPart; int classPartsCount = testParts.length - 1; String[] classParts = new String[classPartsCount]; System.arraycopy(testParts, 0, classParts, 0, classPartsCount); String testClass = String.join(".", classParts); res.compute(testClass, (k, v) -> { if (v == null) { v = new HashSet<>(); } v.add(testMethodName); return v; }); } return res; } private static Set<String> getKey(Class<?> testClass, Map<String, Set<String>> testsMap) { String className = testClass.getName(); if (testsMap.containsKey(className)) { return testsMap.get(className); } String unqualifiedClassName = testClass.getSimpleName(); if (testsMap.containsKey(unqualifiedClassName)) { return testsMap.get(unqualifiedClassName); } return null; } private static boolean contains(Class<? extends AbstractSmackIntTest> testClass, Map<String, Set<String>> testsMap) { Set<String> enabledMethods = getKey(testClass, testsMap); return enabledMethods != null; } public boolean isClassEnabled(Class<? extends AbstractSmackIntTest> testClass) { if (enabledTestsMap.isEmpty()) { return true; } return contains(testClass, enabledTestsMap); } public boolean isClassDisabled(Class<? extends AbstractSmackIntTest> testClass) { if (disabledTestsMap.isEmpty()) { return false; } return contains(testClass, disabledTestsMap); } private static boolean contains(Method method, Map<String, Set<String>> testsMap) { Class<?> testClass = method.getDeclaringClass(); Set<String> methods = getKey(testClass, testsMap); if (methods == null) { return false; } if (methods.isEmpty()) { return true; } String methodName = method.getName(); return methods.contains(methodName); } public boolean isMethodEnabled(Method method) { if (enabledTestsMap.isEmpty()) { return true; } return contains(method, enabledTestsMap); } public boolean isMethodDisabled(Method method) { if (disabledTestsMap.isEmpty()) { return false; } return contains(method, disabledTestsMap); } }
36.652361
148
0.649766
811293feb334f2f694b9678d0268cb0d6bfc3794
965
package com.coding.problems; /** * Write a function to find the longest common prefix string amongst an array of strings. * <p> * If there is no common prefix, return an empty string "". */ public class LongestCommonPrefix { public String longestCommonPrefix(String[] strs) { if(strs.length < 1){ return ""; } StringBuilder longestPrefix = new StringBuilder(); int shortestLength = Integer.MAX_VALUE; for (String str : strs) { if ( str.length() < shortestLength) { shortestLength = str.length(); } } for (int i = 0; i < shortestLength; i++) { char c = strs[0].charAt(i); for (String str : strs) { if (str.charAt(i) != c) { return longestPrefix.toString(); } } longestPrefix.append(c); } return longestPrefix.toString(); } }
26.805556
89
0.529534
4fc9b2002fe0b16f68372a71384a5b54d9dbb2d0
1,162
package com.tomaskostadinov.weatherapp.helper; import org.json.JSONArray; import org.json.JSONObject; /** * Created by Tomas on 03.06.2015. */ public class WeatherForecastHelper { JSONObject reader, main; JSONArray weather; private JSONArray list; public Integer date, temp, weather_id; public String description; public void ParseData(String in){ try { reader = new JSONObject(in); this.list = reader.getJSONArray("list"); } catch (Exception e) { e.printStackTrace(); } } public void getWeatherForecastForId(Integer i){ try { JSONObject jDayForecast = list.getJSONObject(i); date = jDayForecast.getInt("dt"); main = jDayForecast.getJSONObject("main"); temp = main.getInt("temp"); weather = jDayForecast.getJSONArray("weather"); JSONObject JSONWeather = weather.getJSONObject(0); description = JSONWeather.getString("description"); weather_id = JSONWeather.getInt("id"); } catch (Exception e) { e.printStackTrace(); } } }
25.822222
63
0.606713
4bd3530ee11948e561d19543280a1be50448a4a2
1,656
package com.github.penfeizhou.animation.webp; import android.content.Context; import com.github.penfeizhou.animation.FrameAnimationDrawable; import com.github.penfeizhou.animation.decode.FrameSeqDecoder; import com.github.penfeizhou.animation.loader.AssetStreamLoader; import com.github.penfeizhou.animation.loader.FileLoader; import com.github.penfeizhou.animation.loader.Loader; import com.github.penfeizhou.animation.loader.ResourceStreamLoader; import com.github.penfeizhou.animation.webp.decode.WebPDecoder; /** * @Description: Animated webp drawable * @Author: pengfei.zhou * @CreateDate: 2019/3/27 */ public class WebPDrawable extends FrameAnimationDrawable<WebPDecoder> { public WebPDrawable(Loader provider) { super(provider); } public WebPDrawable(WebPDecoder decoder) { super(decoder); } @Override protected WebPDecoder createFrameSeqDecoder(Loader streamLoader, FrameSeqDecoder.RenderListener listener) { return new WebPDecoder(streamLoader, listener); } public static WebPDrawable fromAsset(Context context, String assetPath) { AssetStreamLoader assetStreamLoader = new AssetStreamLoader(context, assetPath); return new WebPDrawable(assetStreamLoader); } public static WebPDrawable fromFile(String filePath) { FileLoader fileLoader = new FileLoader(filePath); return new WebPDrawable(fileLoader); } public static WebPDrawable fromResource(Context context, int resId) { ResourceStreamLoader resourceStreamLoader = new ResourceStreamLoader(context, resId); return new WebPDrawable(resourceStreamLoader); } }
34.5
111
0.768116
2f9fd8301dcf4cbd211da77d3b5eb92b4ca18d45
864
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.netapp.v2020_07_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.netapp.v2020_07_01.implementation.NetAppManager; import com.microsoft.azure.management.netapp.v2020_07_01.implementation.SnapshotPolicyVolumeListInner; import java.util.List; /** * Type representing SnapshotPolicyVolumeList. */ public interface SnapshotPolicyVolumeList extends HasInner<SnapshotPolicyVolumeListInner>, HasManager<NetAppManager> { /** * @return the value value. */ List<Object> value(); }
32
118
0.784722
47015d957ea16559a3698aaa07689d3d83077c78
1,431
/* * Copyright (C) 2014 Siegenthaler Solutions. * * 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 me.siegenthaler.spotify.webapi.android.request.browse; import me.siegenthaler.spotify.webapi.android.model.SimpleAlbum; import me.siegenthaler.spotify.webapi.android.request.AbstractPageRequest; import me.siegenthaler.spotify.webapi.android.request.AbstractRequest; /** * (non-doc) */ public final class BrowseAlbumRequest extends AbstractPageRequest<BrowseAlbumRequest, SimpleAlbum> { private final static AbstractRequest.PageType PARAMETER_TYPE = new AbstractRequest.PageType(SimpleAlbum.class); /** * (non-doc) */ public BrowseAlbumRequest() { super(PARAMETER_TYPE, "albums"); setPath("/v1/browse/new-releases"); } /** * (non-doc) */ public BrowseAlbumRequest setMarket(String market) { return addParameter("market", market); } }
33.27907
115
0.728861
10ff8111ef5cf654d29af8c80d93c635b9d961fa
21,549
/* * 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.qpid.proton.engine.impl; import static java.util.EnumSet.of; import static org.apache.qpid.proton.engine.EndpointState.ACTIVE; import static org.apache.qpid.proton.engine.EndpointState.UNINITIALIZED; import static org.apache.qpid.proton.systemtests.TestLoggingHelper.bold; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.logging.Logger; import org.apache.qpid.proton.Proton; import org.apache.qpid.proton.amqp.messaging.Accepted; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.amqp.messaging.Source; import org.apache.qpid.proton.amqp.messaging.Target; import org.apache.qpid.proton.amqp.transport.ReceiverSettleMode; import org.apache.qpid.proton.amqp.transport.SenderSettleMode; import org.apache.qpid.proton.engine.Connection; import org.apache.qpid.proton.engine.Delivery; import org.apache.qpid.proton.engine.Receiver; import org.apache.qpid.proton.engine.Sender; import org.apache.qpid.proton.engine.Session; import org.apache.qpid.proton.engine.Transport; import org.apache.qpid.proton.message.Message; import org.apache.qpid.proton.systemtests.EngineTestBase; import org.apache.qpid.proton.systemtests.ProtocolTracerEnabler; import org.apache.qpid.proton.systemtests.TestLoggingHelper; import org.junit.Test; public class DeferredSettlementTest extends EngineTestBase { private static final Logger LOGGER = Logger.getLogger(DeferredSettlementTest.class.getName()); private static final int BUFFER_SIZE = 4096; private final String _sourceAddress = getServer().getContainerId() + "-link1-source"; @Test public void testDeferredOutOfOrderSettlement() throws Exception { LOGGER.fine(bold("======== About to create transports")); Transport clientTransport = Proton.transport(); getClient().setTransport(clientTransport); ProtocolTracerEnabler.setProtocolTracer(clientTransport, TestLoggingHelper.CLIENT_PREFIX); Transport serverTransport = Proton.transport(); getServer().setTransport(serverTransport); ProtocolTracerEnabler.setProtocolTracer(serverTransport, " " + TestLoggingHelper.SERVER_PREFIX); doOutputInputCycle(); Connection clientConnection = Proton.connection(); getClient().setConnection(clientConnection); clientTransport.bind(clientConnection); Connection serverConnection = Proton.connection(); getServer().setConnection(serverConnection); serverTransport.bind(serverConnection); LOGGER.fine(bold("======== About to open connections")); clientConnection.open(); serverConnection.open(); doOutputInputCycle(); LOGGER.fine(bold("======== About to open sessions")); Session clientSession = clientConnection.session(); getClient().setSession(clientSession); clientSession.open(); pumpClientToServer(); Session serverSession = serverConnection.sessionHead(of(UNINITIALIZED), of(ACTIVE)); getServer().setSession(serverSession); assertEndpointState(serverSession, UNINITIALIZED, ACTIVE); serverSession.open(); assertEndpointState(serverSession, ACTIVE, ACTIVE); pumpServerToClient(); assertEndpointState(clientSession, ACTIVE, ACTIVE); LOGGER.fine(bold("======== About to create receiver")); Source clientSource = new Source(); getClient().setSource(clientSource); clientSource.setAddress(_sourceAddress); Target clientTarget = new Target(); getClient().setTarget(clientTarget); clientTarget.setAddress(null); Receiver clientReceiver = clientSession.receiver("link1"); getClient().setReceiver(clientReceiver); clientReceiver.setTarget(clientTarget); clientReceiver.setSource(clientSource); clientReceiver.setReceiverSettleMode(ReceiverSettleMode.FIRST); clientReceiver.setSenderSettleMode(SenderSettleMode.UNSETTLED); assertEndpointState(clientReceiver, UNINITIALIZED, UNINITIALIZED); clientReceiver.open(); assertEndpointState(clientReceiver, ACTIVE, UNINITIALIZED); pumpClientToServer(); LOGGER.fine(bold("======== About to set up implicitly created sender")); Sender serverSender = (Sender) getServer().getConnection().linkHead(of(UNINITIALIZED), of(ACTIVE)); getServer().setSender(serverSender); serverSender.setReceiverSettleMode(serverSender.getRemoteReceiverSettleMode()); serverSender.setSenderSettleMode(serverSender.getRemoteSenderSettleMode()); org.apache.qpid.proton.amqp.transport.Source serverRemoteSource = serverSender.getRemoteSource(); serverSender.setSource(serverRemoteSource); assertEndpointState(serverSender, UNINITIALIZED, ACTIVE); serverSender.open(); assertEndpointState(serverSender, ACTIVE, ACTIVE); pumpServerToClient(); assertEndpointState(clientReceiver, ACTIVE, ACTIVE); int messageCount = 5; clientReceiver.flow(messageCount); pumpClientToServer(); LOGGER.fine(bold("======== About to create messages and send to the client")); DeliveryImpl[] serverDeliveries = sendMessagesToClient(messageCount); pumpServerToClient(); for (int i = 0; i < messageCount; i++) { Delivery d = serverDeliveries[i]; assertNotNull("Should have had a delivery", d); assertNull("Delivery shouldnt have local state", d.getLocalState()); assertNull("Delivery shouldnt have remote state", d.getRemoteState()); } LOGGER.fine(bold("======== About to process the messages on the client")); // Grab the original linkHead, assert deliveries are there, keep refs for later DeliveryImpl d0 = (DeliveryImpl) clientReceiver.head(); assertNotNull("Should have a link head", d0); DeliveryImpl[] origClientLinkDeliveries = new DeliveryImpl[messageCount]; for (int i = 0 ; i < messageCount; i++) { origClientLinkDeliveries[i] = d0; DeliveryImpl linkPrevious = d0.getLinkPrevious(); DeliveryImpl linkNext = d0.getLinkNext(); if(i == 0) { assertNull("should not have link prev", linkPrevious); } else { assertNotNull("should have link prev", linkPrevious); assertSame("Unexpected delivery at link prev", origClientLinkDeliveries[i - 1], linkPrevious); assertSame("Expected to be prior deliveries link next", d0, origClientLinkDeliveries[i - 1].getLinkNext()); } if(i != messageCount - 1) { assertNotNull("should have link next", linkNext); } else { assertNull("should not have link next", linkNext); } d0 = linkNext; } // Receive the deliveries and verify contents, marking with matching integer context for easy identification. DeliveryImpl[] clientDeliveries = receiveMessagesFromServer(messageCount); // Accept but don't settle them all for (int i = 0; i < messageCount; i++) { Delivery d = clientDeliveries[i]; assertNotNull("Should have had a delivery", d); d.disposition(Accepted.getInstance()); } // Verify the client lists, i.e. deliveries now point to each other where expected for (int i = 0 ; i < messageCount; i++) { DeliveryImpl d = origClientLinkDeliveries[i]; assertSame("Unexpected delivery", origClientLinkDeliveries[i], clientDeliveries[i]); // Verify the Transport and Link list entries if(i == 0) { assertDeliveryLinkReferences(d, i, null, origClientLinkDeliveries[1]); assertDeliveryTransportWorkReferences(d, i, null, origClientLinkDeliveries[1]); } else if (i != messageCount - 1) { assertDeliveryLinkReferences(d, i, origClientLinkDeliveries[i - 1], origClientLinkDeliveries[i+1]); assertDeliveryTransportWorkReferences(d, i, origClientLinkDeliveries[i - 1], origClientLinkDeliveries[i+1]); } else { assertDeliveryLinkReferences(d, i, origClientLinkDeliveries[i - 1], null); assertDeliveryTransportWorkReferences(d, i, origClientLinkDeliveries[i - 1], null); } // Assert there are no 'work' list entries, as those are for remote peer updates. assertDeliveryWorkReferences(d, i, null, null); } // Verify the server gets intended state changes pumpClientToServer(); for (int i = 0; i < messageCount; i++) { DeliveryImpl d = serverDeliveries[i]; assertNotNull("Should have had a delivery", d); assertNull("Delivery shouldnt have local state", d.getLocalState()); assertEquals("Delivery should have remote state", Accepted.getInstance(), d.getRemoteState()); // Verify the Link and Work list entries if(i == 0) { assertDeliveryLinkReferences(d, null, null, serverDeliveries[1]); assertDeliveryWorkReferences(d, null, null, serverDeliveries[1]); } else if (i != messageCount - 1) { assertDeliveryLinkReferences(d, null, serverDeliveries[i - 1], serverDeliveries[i+1]); assertDeliveryWorkReferences(d, null, serverDeliveries[i - 1], serverDeliveries[i+1]); } else { assertDeliveryLinkReferences(d, null, serverDeliveries[i - 1], null); assertDeliveryWorkReferences(d, null, serverDeliveries[i - 1], null); } // Assert there are no 'transport work' list entries, as those are for local updates. assertDeliveryTransportWorkReferences(d, null, null, null); } // Settle one from the middle int toSettle = messageCount/2; assertTrue("need more deliveries", toSettle > 1); assertTrue("need more deliveries", toSettle < messageCount - 1); DeliveryImpl dSettle = clientDeliveries[toSettle]; Integer index = getDeliveryContextIndex(dSettle); // Verify the server gets intended state changes when settled assertFalse("Delivery should not have been remotely settled yet", serverDeliveries[toSettle].remotelySettled()); dSettle.settle(); // Verify the client delivery Link and Work list entries are cleared, tpWork is set assertDeliveryLinkReferences(dSettle, index, null, null); assertDeliveryWorkReferences(dSettle, index, null, null); assertDeliveryTransportWorkReferences(dSettle, index, null, null); assertSame("expected settled delivery to be client connection tpWork head", dSettle, ((ConnectionImpl) clientConnection).getTransportWorkHead()); // Verify the client Link and Work list entries are correct for neighbouring deliveries assertDeliveryLinkReferences(clientDeliveries[toSettle - 1], index - 1, clientDeliveries[toSettle - 2], clientDeliveries[toSettle + 1]); assertDeliveryTransportWorkReferences(clientDeliveries[toSettle - 1], index - 1, null, null); assertDeliveryWorkReferences(clientDeliveries[toSettle - 1], index - 1, null, null); assertDeliveryLinkReferences(clientDeliveries[toSettle + 1], index + 1, clientDeliveries[toSettle - 1], clientDeliveries[toSettle + 2]); assertDeliveryTransportWorkReferences(clientDeliveries[toSettle + 1], index + 1, null, null); assertDeliveryWorkReferences(clientDeliveries[toSettle + 1], index + 1, null, null); // Update the server with the changes pumpClientToServer(); // Verify server delivery is now remotelySettled, its Link and Work entries are NOT yet clear, but tpWork IS clear DeliveryImpl dSettleServer = serverDeliveries[toSettle]; assertTrue("Delivery should have been remotely settled on server", dSettleServer.remotelySettled()); assertDeliveryLinkReferences(dSettleServer, null, serverDeliveries[toSettle - 1], serverDeliveries[toSettle+1]); assertDeliveryWorkReferences(dSettleServer, null, serverDeliveries[toSettle - 1], serverDeliveries[toSettle+1]); assertDeliveryTransportWorkReferences(dSettleServer, null, null, null); assertNull("expected client connection tpWork head to now be null", ((ConnectionImpl) clientConnection).getTransportWorkHead()); // Settle on server, expect Link and Work list entries to be cleared, tpWork to remain clear (as delivery // is already remotely settled). Note 'work next' returns list head if none present, so we verify that here. dSettleServer.settle(); assertDeliveryLinkReferences(dSettleServer, null, null, null); assertNull("Unexpected workPrev", dSettleServer.getWorkPrev()); assertSame("Unexpected workNext", serverDeliveries[0], dSettleServer.getWorkNext()); assertDeliveryTransportWorkReferences(dSettleServer, null, null, null); assertNull("expected server connection tpWork head to still be null", ((ConnectionImpl) serverConnection).getTransportWorkHead()); // Verify the server entries are correct for neighbouring deliveries updated to reflect the settle assertDeliveryLinkReferences(serverDeliveries[toSettle - 1], null, serverDeliveries[toSettle - 2], serverDeliveries[toSettle + 1]); assertDeliveryWorkReferences(serverDeliveries[toSettle - 1], null, serverDeliveries[toSettle - 2], serverDeliveries[toSettle + 1]); assertDeliveryTransportWorkReferences(serverDeliveries[toSettle - 1], null, null, null); assertDeliveryLinkReferences(serverDeliveries[toSettle + 1], null, serverDeliveries[toSettle - 1], serverDeliveries[toSettle + 2]); assertDeliveryWorkReferences(serverDeliveries[toSettle + 1], null, serverDeliveries[toSettle - 1], serverDeliveries[toSettle + 2]); assertDeliveryTransportWorkReferences(serverDeliveries[toSettle + 1], null, null, null); } private Integer getDeliveryContextIndex(DeliveryImpl d) { assertNotNull("Should have had a delivery", d); Integer index = (Integer) d.getContext(); assertNotNull("Should have had a context index", index); return index; } private void assertDeliveryWorkReferences(DeliveryImpl delivery, Integer index, DeliveryImpl deliveryWorkPrev, DeliveryImpl deliveryWorkNext) { assertNotNull("No delivery given", delivery); if(index != null) { assertEquals("Unexpected context index", Integer.valueOf(index), getDeliveryContextIndex(delivery)); } if(deliveryWorkPrev == null) { assertNull("Unexpected workPrev", delivery.getWorkPrev()); } else { assertSame("Unexpected workPrev", deliveryWorkPrev, delivery.getWorkPrev()); assertSame("Unexpected workNext on previous delivery", delivery, deliveryWorkPrev.getWorkNext()); } if(deliveryWorkNext == null) { assertNull("Unexpected workNext", delivery.getWorkNext()); } else { assertSame("Unexpected workNext", deliveryWorkNext, delivery.getWorkNext()); assertSame("Unexpected workPrev on next delivery", delivery , deliveryWorkNext.getWorkPrev()); } } private void assertDeliveryTransportWorkReferences(DeliveryImpl delivery, Integer index, DeliveryImpl deliveryTpWorkPrev, DeliveryImpl deliveryTpWorkNext) { assertNotNull("No delivery given", delivery); if(index != null) { assertEquals("Unexpected context index", Integer.valueOf(index), getDeliveryContextIndex(delivery)); } if(deliveryTpWorkPrev == null) { assertNull("Unexpected transportWorkPrev", delivery.getTransportWorkPrev()); } else { assertSame("Unexpected transportWorkPrev", deliveryTpWorkPrev, delivery.getTransportWorkPrev()); assertSame("Unexpected transportWorkNext on previous delivery", delivery, deliveryTpWorkPrev.getTransportWorkNext()); } if (deliveryTpWorkNext == null) { assertNull("Unexpected transportWorkNext", delivery.getTransportWorkNext()); } else { assertSame("Unexpected transportWorkNext", deliveryTpWorkNext, delivery.getTransportWorkNext()); assertSame("Unexpected transportWorkPrev on next delivery", delivery , deliveryTpWorkNext.getTransportWorkPrev()); } } private void assertDeliveryLinkReferences(DeliveryImpl delivery, Integer index, DeliveryImpl deliveryLinkPrev, DeliveryImpl deliveryLinkNext) { assertNotNull("No delivery given", delivery); if(index != null) { assertEquals("Unexpected context index", Integer.valueOf(index), getDeliveryContextIndex(delivery)); } if(deliveryLinkPrev == null) { assertNull("Unexpected linkPrev", delivery.getLinkPrevious()); } else { assertSame("Unexpected linkPrev", deliveryLinkPrev, delivery.getLinkPrevious()); assertSame("Unexpected linkPrev on previous delivery", delivery, deliveryLinkPrev.getLinkNext()); } if(deliveryLinkNext == null) { assertNull("Unexpected linkNext", delivery.getLinkNext()); } else { assertSame("Unexpected linkNext", deliveryLinkNext, delivery.getLinkNext()); assertSame("Unexpected linkPrev on next delivery", delivery , deliveryLinkNext.getLinkPrevious()); } } private DeliveryImpl[] receiveMessagesFromServer(int count) { DeliveryImpl[] deliveries = new DeliveryImpl[count]; for(int i = 0; i < count; i++) { deliveries[i] = (DeliveryImpl) receiveMessageFromServer("Message" + i, i); } return deliveries; } private Delivery receiveMessageFromServer(String deliveryTag, int count) { Delivery delivery = getClient().getConnection().getWorkHead(); Receiver clientReceiver = getClient().getReceiver(); assertTrue(Arrays.equals(deliveryTag.getBytes(StandardCharsets.UTF_8), delivery.getTag())); assertEquals("The received delivery should be on our receiver", clientReceiver, delivery.getLink()); assertNull(delivery.getLocalState()); assertNull(delivery.getRemoteState()); assertFalse(delivery.isPartial()); assertTrue(delivery.isReadable()); int size = delivery.available(); byte[] received = new byte[size]; int len = clientReceiver.recv(received, 0, size); assertEquals("Should have received " + size + " bytes", size, len); assertEquals("Should be no bytes left", 0, delivery.available()); Message m = Proton.message(); m.decode(received, 0, len); Object messageBody = ((AmqpValue)m.getBody()).getValue(); assertEquals("Unexpected message content", count, messageBody); boolean receiverAdvanced = clientReceiver.advance(); assertTrue("receiver has not advanced", receiverAdvanced); delivery.setContext(count); return delivery; } private DeliveryImpl[] sendMessagesToClient(int count) { DeliveryImpl[] deliveries = new DeliveryImpl[count]; for(int i = 0; i< count; i++) { deliveries[i] = (DeliveryImpl) sendMessageToClient("Message" + i, i); } return deliveries; } private Delivery sendMessageToClient(String deliveryTag, int messageBody) { byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8); Message m = Proton.message(); m.setBody(new AmqpValue(messageBody)); byte[] encoded = new byte[BUFFER_SIZE]; int len = m.encode(encoded, 0, BUFFER_SIZE); assertTrue("given array was too small", len < BUFFER_SIZE); Sender serverSender = getServer().getSender(); Delivery serverDelivery = serverSender.delivery(tag); int sent = serverSender.send(encoded, 0, len); assertEquals("sender unable to send all data at once as assumed for simplicity", len, sent); boolean senderAdvanced = serverSender.advance(); assertTrue("sender has not advanced", senderAdvanced); return serverDelivery; } }
45.751592
160
0.68857
7c8b73080aec530aba472f5983b35ab117e17493
435
package io.agora.openvcall; /** * Create by xjs * _______date : 17/5/18 * _______description: */ public class AppConfig { //public static final String HOST = "http://api.pingqulive.ping-qu.com"; //public static final String HOST = "http://api.ping-qu.com"; public static final String HOST = "http://10.8.8.35"; /** * 获取频道key */ public static final String GET_CHANNEL_KEY = "/v2_1/agora/agora"; }
21.75
76
0.643678
3981e688281bf9bae9b2caed118854f5c744ac60
182
/** * User: Pedro.Miranda * Project: agenda * Description: this class execute...! * Date: 16/12/2020 */ package br.com.phmiranda.domain; public class Agenda { // comment }
15.166667
38
0.653846
932054c979052bbae639d09bdeca80ca9a724a63
842
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author ilisi */ /* ogretmen.java : Çocuk sınıf bildirimi */ public class ogretmen extends personel { public String brans; public int hizmet; /* Constructor metod */ public ogretmen(String cadi, String csoyadi, int cyasi, String cbrans, int chizmet) { super(cadi, csoyadi, cyasi); brans = cbrans; hizmet = chizmet; } public String getogretmenBilgi() { return brans + " " + hizmet; } /* Üst sınıfta geçersiz hale getirilmiş metod */ public void yazdirBilgi() { super.yazdirBilgi(); System.out.println("Öğretmen: Branş - Hizmet yılı: " + getogretmenBilgi()); } }
25.515152
88
0.649644