hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e0be17573a74bbb0694b8fda269f15ea33c4599
192
java
Java
logginghub-messaging3/src/main/java/com/logginghub/messaging/ResponseListener.java
logginghub/core
c40d963e7782330b0369c99f64a6b8102b7eea65
[ "Apache-2.0" ]
null
null
null
logginghub-messaging3/src/main/java/com/logginghub/messaging/ResponseListener.java
logginghub/core
c40d963e7782330b0369c99f64a6b8102b7eea65
[ "Apache-2.0" ]
null
null
null
logginghub-messaging3/src/main/java/com/logginghub/messaging/ResponseListener.java
logginghub/core
c40d963e7782330b0369c99f64a6b8102b7eea65
[ "Apache-2.0" ]
2
2015-12-09T16:39:10.000Z
2021-02-18T09:11:21.000Z
24
46
0.734375
5,023
package com.logginghub.messaging; public interface ResponseListener<T> { void onResponse(T response); void onResponseFailure(Throwable reason); void onResponseTimeout(); }
3e0be1cdd5c9e6d9087f85669ea0db026f873269
755
java
Java
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/ShowDiffPreviewAction.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/ShowDiffPreviewAction.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-07-30T19:04:47.000Z
2020-07-30T19:04:47.000Z
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/ShowDiffPreviewAction.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-10-15T05:56:42.000Z
2020-10-15T05:56:42.000Z
37.75
140
0.788079
5,024
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.ui.actions; import com.intellij.vcs.log.VcsLogBundle; import com.intellij.vcs.log.impl.CommonUiProperties; import com.intellij.vcs.log.impl.VcsLogUiProperties; public class ShowDiffPreviewAction extends BooleanPropertyToggleAction { public ShowDiffPreviewAction() { super(VcsLogBundle.messagePointer("vcs.log.action.show.diff.preview"), VcsLogBundle.messagePointer("vcs.log.action.description.show.diff.preview"), null); } @Override protected VcsLogUiProperties.VcsLogUiProperty<Boolean> getProperty() { return CommonUiProperties.SHOW_DIFF_PREVIEW; } }
3e0be2389cc96abc2ef1f5ae1df2c45b7dc6a5fb
4,730
java
Java
flink-connector-oracle-cdc/src/main/java/com/ververica/cdc/connectors/oracle/table/OracleReadableMetaData.java
zhongqishang/flink-cdc-connectors
b9264433ca49ef2f22cc6d6dedd63ce6aa557736
[ "Apache-2.0" ]
8
2022-01-14T03:02:24.000Z
2022-02-23T04:24:51.000Z
flink-connector-oracle-cdc/src/main/java/com/ververica/cdc/connectors/oracle/table/OracleReadableMetaData.java
ViseprSky/flink-cdc-connectors
c97968e6379f2a3a737645bbc2bcf6f047aaa92f
[ "Apache-2.0" ]
9
2021-08-20T07:26:04.000Z
2021-12-24T13:33:25.000Z
flink-connector-oracle-cdc/src/main/java/com/ververica/cdc/connectors/oracle/table/OracleReadableMetaData.java
ViseprSky/flink-cdc-connectors
c97968e6379f2a3a737645bbc2bcf6f047aaa92f
[ "Apache-2.0" ]
3
2021-09-14T02:56:31.000Z
2022-03-22T09:19:14.000Z
37.84
97
0.629175
5,025
/* * 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.ververica.cdc.connectors.oracle.table; import org.apache.flink.table.api.DataTypes; import org.apache.flink.table.data.StringData; import org.apache.flink.table.data.TimestampData; import org.apache.flink.table.types.DataType; import com.ververica.cdc.debezium.table.MetadataConverter; import io.debezium.connector.AbstractSourceInfo; import io.debezium.data.Envelope; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.source.SourceRecord; /** Defines the supported metadata columns for {@link OracleTableSource}. */ public enum OracleReadableMetaData { /** Name of the table that contain the row. */ TABLE_NAME( "table_name", DataTypes.STRING().notNull(), new MetadataConverter() { private static final long serialVersionUID = 1L; @Override public Object read(SourceRecord record) { Struct messageStruct = (Struct) record.value(); Struct sourceStruct = messageStruct.getStruct(Envelope.FieldName.SOURCE); return StringData.fromString( sourceStruct.getString(AbstractSourceInfo.TABLE_NAME_KEY)); } }), /** Name of the schema that contain the row. */ SCHEMA_NAME( "schema_name", DataTypes.STRING().notNull(), new MetadataConverter() { private static final long serialVersionUID = 1L; @Override public Object read(SourceRecord record) { Struct messageStruct = (Struct) record.value(); Struct sourceStruct = messageStruct.getStruct(Envelope.FieldName.SOURCE); return StringData.fromString( sourceStruct.getString(AbstractSourceInfo.SCHEMA_NAME_KEY)); } }), /** Name of the database that contain the row. */ DATABASE_NAME( "database_name", DataTypes.STRING().notNull(), new MetadataConverter() { private static final long serialVersionUID = 1L; @Override public Object read(SourceRecord record) { Struct messageStruct = (Struct) record.value(); Struct sourceStruct = messageStruct.getStruct(Envelope.FieldName.SOURCE); return StringData.fromString( sourceStruct.getString(AbstractSourceInfo.DATABASE_NAME_KEY)); } }), /** * It indicates the time that the change was made in the database. If the record is read from * snapshot of the table instead of the change stream, the value is always 0. */ OP_TS( "op_ts", DataTypes.TIMESTAMP_WITH_LOCAL_TIME_ZONE(3).notNull(), new MetadataConverter() { private static final long serialVersionUID = 1L; @Override public Object read(SourceRecord record) { Struct messageStruct = (Struct) record.value(); Struct sourceStruct = messageStruct.getStruct(Envelope.FieldName.SOURCE); return TimestampData.fromEpochMillis( (Long) sourceStruct.get(AbstractSourceInfo.TIMESTAMP_KEY)); } }); private final String key; private final DataType dataType; private final MetadataConverter converter; OracleReadableMetaData(String key, DataType dataType, MetadataConverter converter) { this.key = key; this.dataType = dataType; this.converter = converter; } public String getKey() { return key; } public DataType getDataType() { return dataType; } public MetadataConverter getConverter() { return converter; } }
3e0be2724c0a1aac37566c3f5b8b2fcd5c5303cd
1,240
java
Java
hasting-rpc/src/test/java/com/lindzh/hasting/rpc/service/StatisticsFilter.java
lindzh/rpc
efed0dabcc5181b9f81bb54514048b38adfd7177
[ "MIT" ]
187
2015-03-12T12:37:21.000Z
2018-02-28T02:38:21.000Z
hasting-rpc/src/test/java/com/lindzh/hasting/rpc/service/StatisticsFilter.java
lindzh/hasting
efed0dabcc5181b9f81bb54514048b38adfd7177
[ "MIT" ]
5
2015-04-20T13:14:29.000Z
2017-10-02T08:53:23.000Z
hasting-rpc/src/test/java/com/lindzh/hasting/rpc/service/StatisticsFilter.java
lindzh/rpc
efed0dabcc5181b9f81bb54514048b38adfd7177
[ "MIT" ]
141
2015-03-12T12:43:59.000Z
2018-02-27T07:40:32.000Z
21.016949
71
0.708065
5,026
package com.lindzh.hasting.rpc.service; import java.util.concurrent.atomic.AtomicLong; import com.lindzh.hasting.rpc.RemoteCall; import com.lindzh.hasting.rpc.RpcObject; import com.lindzh.hasting.rpc.Service; import com.lindzh.hasting.rpc.filter.RpcFilter; import com.lindzh.hasting.rpc.filter.RpcFilterChain; import com.lindzh.hasting.rpc.net.RpcSender; public class StatisticsFilter implements RpcFilter,Service{ private long start = 0; private long end = 0; private AtomicLong call = new AtomicLong(0); public void reset(){ this.call.set(0); this.start = 0; this.end = 0; } @Override public void doFilter(RpcObject rpc, RemoteCall call, RpcSender sender, RpcFilterChain chain) { this.call.incrementAndGet(); chain.nextFilter(rpc, call, sender); } @Override public void startService() { this.start = System.currentTimeMillis(); } @Override public void stopService() { this.end = System.currentTimeMillis(); } public long getTime(){ return this.end-this.start; } public long getCall(){ return this.call.get(); } public long getTps(){ long time = this.getTime(); long cc = this.getCall(); if(time>0){ return cc*1000/time; }else{ return 0; } } }
3e0be4628705039c8d13f5c010c0a883fcffa29c
3,534
java
Java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/HlsOutputSettingsJsonUnmarshaller.java
psmagin/aws-sdk-java
2250ab204ea1abf0e9e79209f27d139199cddd44
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/HlsOutputSettingsJsonUnmarshaller.java
psmagin/aws-sdk-java
2250ab204ea1abf0e9e79209f27d139199cddd44
[ "Apache-2.0" ]
1
2020-02-12T01:54:01.000Z
2020-02-12T01:54:11.000Z
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/HlsOutputSettingsJsonUnmarshaller.java
psmagin/aws-sdk-java
2250ab204ea1abf0e9e79209f27d139199cddd44
[ "Apache-2.0" ]
1
2020-02-12T01:46:54.000Z
2020-02-12T01:46:54.000Z
40.62069
136
0.654499
5,027
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.medialive.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.medialive.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * HlsOutputSettings JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class HlsOutputSettingsJsonUnmarshaller implements Unmarshaller<HlsOutputSettings, JsonUnmarshallerContext> { public HlsOutputSettings unmarshall(JsonUnmarshallerContext context) throws Exception { HlsOutputSettings hlsOutputSettings = new HlsOutputSettings(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("h265PackagingType", targetDepth)) { context.nextToken(); hlsOutputSettings.setH265PackagingType(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("hlsSettings", targetDepth)) { context.nextToken(); hlsOutputSettings.setHlsSettings(HlsSettingsJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("nameModifier", targetDepth)) { context.nextToken(); hlsOutputSettings.setNameModifier(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("segmentModifier", targetDepth)) { context.nextToken(); hlsOutputSettings.setSegmentModifier(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return hlsOutputSettings; } private static HlsOutputSettingsJsonUnmarshaller instance; public static HlsOutputSettingsJsonUnmarshaller getInstance() { if (instance == null) instance = new HlsOutputSettingsJsonUnmarshaller(); return instance; } }
3e0be47c0381a18b3938cc303e352ad271f7ac06
1,634
java
Java
2019-2020/src/designPattern/reseauSocial/core/SocialNetWorkImpl.java
2019-2020-IUT/M315-Conception-et-Programmation-Oriente-Objet-Avance
c6b3df1e09f09d1a31881d896d82953e827b2214
[ "CC-BY-4.0" ]
null
null
null
2019-2020/src/designPattern/reseauSocial/core/SocialNetWorkImpl.java
2019-2020-IUT/M315-Conception-et-Programmation-Oriente-Objet-Avance
c6b3df1e09f09d1a31881d896d82953e827b2214
[ "CC-BY-4.0" ]
null
null
null
2019-2020/src/designPattern/reseauSocial/core/SocialNetWorkImpl.java
2019-2020-IUT/M315-Conception-et-Programmation-Oriente-Objet-Avance
c6b3df1e09f09d1a31881d896d82953e827b2214
[ "CC-BY-4.0" ]
null
null
null
19
73
0.73623
5,028
package designPattern.reseauSocial.core; import java.util.Collection; import java.util.Observable; import java.util.Set; import designPattern.facebookGhost.FacebookGhostNetwork; import designPattern.grapheSimple.GrapheSimple; @SuppressWarnings("deprecation") public class SocialNetWorkImpl implements SocialNetworkInterface<Member>{ private String nom; private GrapheSimple<Member> reseau; public SocialNetWorkImpl() { this("Default"); } public SocialNetWorkImpl(String n) { this.nom = n; reseau = new GrapheSimple<Member>(); } @Override public void update(Observable arg0, Object arg1) { // TODO Auto-generated method stub } @Override public Member getMember(String identifier) { return reseau.getSommet(identifier); } @Override public Collection<Member> getMembers() { return reseau.sommets(); } @Override public void addMember(Member m) { reseau.ajouterSommet(m); } @Override public Member addMember(String ident, FacebookGhostNetwork fg) { // TODO Auto-generated method stub return null; } @Override public Member addMember(String identifier) { // TODO Auto-generated method stub return null; } @Override public void relate(Strength force, Member member, Member friend) { // TODO Auto-generated method stub } @Override public Set<Member> relatedToRank(Member member, int rank) { // TODO Auto-generated method stub return null; } @Override public int distance(Member member1, Member member2) { // TODO Auto-generated method stub return 0; } public String getNom() { return nom; } public void setNom(String n) { this.nom = n; } }
3e0be53a573319901b374b2747d594be274389cc
281
java
Java
src/main/java/design/simplefactory/Client.java
mayuanucas/CodingInterview
f7603e8b5640fb8a0e2cbb97e4abc589b2bde376
[ "Apache-2.0" ]
37
2018-02-03T14:17:01.000Z
2022-03-28T18:48:27.000Z
src/main/java/design/simplefactory/Client.java
mxuexxmy/CodingInterview
007884a15cbc6f68508fd5aa3034b05e6fa729c9
[ "Apache-2.0" ]
null
null
null
src/main/java/design/simplefactory/Client.java
mxuexxmy/CodingInterview
007884a15cbc6f68508fd5aa3034b05e6fa729c9
[ "Apache-2.0" ]
16
2018-09-21T14:40:52.000Z
2021-07-04T04:19:48.000Z
20.071429
58
0.654804
5,029
package design.simplefactory; /** * @author: mayuan * @desc: * @date: 2018/07/14 */ public class Client { public static void main(String[] args) { SimpleFactory simpleFactory = new SimpleFactory(); Product product = simpleFactory.createProduct(1); } }
3e0be5632a9f9c87ecacfff78b4cf6793e9b3b3f
4,150
java
Java
src/src/cn/limc/androidcharts/view/MinusStickChart.java
treycc/Android-Charts
3de48c6a640f63dc7e94e34a76daaf86ba428e0f
[ "Apache-2.0" ]
654
2015-01-01T18:39:28.000Z
2022-03-15T00:18:07.000Z
src/src/cn/limc/androidcharts/view/MinusStickChart.java
ynztlxdeai/Android-Charts
3de48c6a640f63dc7e94e34a76daaf86ba428e0f
[ "Apache-2.0" ]
7
2015-06-15T02:00:33.000Z
2021-12-16T17:47:24.000Z
src/src/cn/limc/androidcharts/view/MinusStickChart.java
ynztlxdeai/Android-Charts
3de48c6a640f63dc7e94e34a76daaf86ba428e0f
[ "Apache-2.0" ]
223
2015-01-02T09:08:35.000Z
2022-02-06T06:35:59.000Z
23.446328
81
0.645542
5,030
/* * MinusStickChart.java * Android-Charts * * Created by limc on 2011/05/29. * * Copyright 2011 limc.cn 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 cn.limc.androidcharts.view; import cn.limc.androidcharts.axis.IAxis; import cn.limc.androidcharts.entity.IMeasurable; import cn.limc.androidcharts.mole.StickMole; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; /** * * <p> * MinusStickChart is inherits from StickChart which its data can be minus value * </p> * <p> * MinusStickChartはグラフの一種です、マイナーデータをチャートで表示は可能です * </p> * <p> * MinusStickChart继承于StickChart的,可以在StickChart基础上绘制包含负数的柱状条。 * </p> * * @author limc * @version v1.0 2011/05/30 15:11:43 * */ public class MinusStickChart extends StickChart { @Override protected void calcDataValueRange() { double maxValue = -Double.MAX_VALUE; double minValue = Double.MAX_VALUE; IMeasurable first = this.stickData.get(0); // 第一个stick为停盘的情况 if (first.getHigh() == 0 && first.getLow() == 0) { } else { maxValue = first.getHigh(); minValue = first.getLow(); } // 判断显示为方柱或显示为线条 for (int i = 0; i < this.stickData.size(); i++) { IMeasurable stick = this.stickData.get(i); if (stick.getLow() < minValue) { minValue = stick.getLow(); } if (stick.getHigh() > maxValue) { maxValue = stick.getHigh(); } } this.maxValue = maxValue; this.minValue = minValue; } @Override protected void calcValueRangePaddingZero(){ } @Override protected void calcValueRangeFormatForAxis() { } /* * (non-Javadoc) * * @param context * * @see cn.limc.androidcharts.view.GridChart#GridChart(Context) */ public MinusStickChart(Context context) { super(context); } /* * (non-Javadoc) * * @param context * * @param attrs * * @param defStyle * * @see cn.limc.androidcharts.view.GridChart#GridChart(Context, * AttributeSet, int) */ public MinusStickChart(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /* * (non-Javadoc) * * @param context * * @param attrs * * @see cn.limc.androidcharts.view.GridChart#GridChart(Context, * AttributeSet) */ public MinusStickChart(Context context, AttributeSet attrs) { super(context, attrs); } /* * (non-Javadoc) * * @param canvas * * * * @see cn.limc.androidcharts.view.StickChart#drawSticks(Canvas) */ @Override protected void drawSticks(Canvas canvas) { if (null == stickData) { return; } if (stickData.size() <= 0) { return; } float stickWidth = dataQuadrant.getPaddingWidth() / maxSticksNum - stickSpacing; if (axisY.getPosition() == IAxis.AXIS_Y_POSITION_LEFT) { float stickX = dataQuadrant.getPaddingStartX(); for (int i = 0; i < stickData.size(); i++) { IMeasurable stick = stickData.get(i); StickMole mole = (StickMole)provider.getMole(); mole.setUp(this,stick,stickX,stickWidth); mole.draw(canvas); // next x stickX = stickX + stickSpacing + stickWidth; } } else { float stickX = dataQuadrant.getPaddingEndX() - stickWidth; for (int i = stickData.size() - 1; i >= 0; i--) { IMeasurable stick = stickData.get(i); StickMole mole = (StickMole)provider.getMole(); mole.setUp(this,stick,stickX,stickWidth); mole.draw(canvas); // next x stickX = stickX - stickSpacing - stickWidth; } } } }
3e0be68a017c26904a8e96f3ac80a423edb9971d
1,163
java
Java
Mage.Sets/src/mage/cards/m/MireBoa.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage.Sets/src/mage/cards/m/MireBoa.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage.Sets/src/mage/cards/m/MireBoa.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
26.431818
126
0.699914
5,031
package mage.cards.m; import java.util.UUID; import mage.MageInt; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.RegenerateSourceEffect; import mage.abilities.keyword.SwampwalkAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; /** * * @author fireshoes */ public final class MireBoa extends CardImpl { public MireBoa(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{G}"); this.subtype.add(SubType.SNAKE); this.power = new MageInt(2); this.toughness = new MageInt(1); // Swampwalk this.addAbility(new SwampwalkAbility()); // {G}: Regenerate Mire Boa. this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new RegenerateSourceEffect(), new ManaCostsImpl("{G}"))); } private MireBoa(final MireBoa card) { super(card); } @Override public MireBoa copy() { return new MireBoa(this); } }
3e0be6feee1b8f897567e7ed1c93e02397dad631
2,470
java
Java
example/src/main/java/com/walid/jsbridge/example/PlanetModule.java
walid1992/JSBridge
834a2b65b30da7cd851296fd4c95dc6de5210d24
[ "MIT" ]
3
2019-06-28T03:33:20.000Z
2019-07-10T07:11:45.000Z
example/src/main/java/com/walid/jsbridge/example/PlanetModule.java
walid1992/JSBridge
834a2b65b30da7cd851296fd4c95dc6de5210d24
[ "MIT" ]
null
null
null
example/src/main/java/com/walid/jsbridge/example/PlanetModule.java
walid1992/JSBridge
834a2b65b30da7cd851296fd4c95dc6de5210d24
[ "MIT" ]
null
null
null
42.586207
131
0.463563
5,032
package com.walid.jsbridge.example; import android.util.Log; import com.walid.jsbridge.BridgeWebView; import com.walid.jsbridge.IDispatchCallBack; import com.walid.jsbridge.factory.BridgeModule; import com.walid.jsbridge.factory.JSCallData; import com.walid.jsbridge.factory.JSMethod; import com.walid.jsbridge.factory.JSMoudle; import java.util.Map; /** * Author : walid * Date : 2019-08-16 16:24 * Describe : */ @JSMoudle(name = "planet") public class PlanetModule extends BridgeModule { @JSMethod(alias = "onClick") public void onClick(BridgeWebView webView, Map<String, Object> map, IDispatchCallBack function) { Log.e("planet", map.toString()); function.onCallBack(new JSCallData(0, "", "{\n" + "      \"userIdEcpt\": \"WVllUUczSFhISUxWVlgvZUh1NEExdz09\",\n" + "      \"count\": 1,\n" + "      \"invisible\": false,\n" + "      \"matchValue\": 0.93,\n" + "      \"time\": 1565753072172,\n" + "      \"user\": {\n" + "        \"userId\": 41874674,\n" + "        \"signature\": \"Avant Laube\",\n" + "        \"avatarName\": \"1558045574804\",\n" + "        \"avatarColor\": \"HeaderColor_Default\",\n" + "        \"background\": \"/image/2019-08-13/a0b544cc-0d2f-4cdd-a242-1fa2f5d2d2cc-1565673677111.png\",\n" + "        \"planet\": \"来自灵性艺术家星球\",\n" + "        \"cityId\": 131,\n" + "        \"gender\": 1,\n" + "        \"birthday\": 752515200000,\n" + "        \"constellation\": 9,\n" + "        \"deviceName\": \"EVA-TL00\",\n" + "        \"deleteTime\": null,\n" + "        \"createTime\": 1553086498000,\n" + "        \"modifyTime\": 1566162222000,\n" + "        \"countryName\": \"中国\",\n" + "        \"countryCode\": \"cn\",\n" + "        \"cityCode\": \"110000\",\n" + "        \"personalSignature\": \"Avant L'aube\",\n" + "        \"personalBackground\": \"/image/2019-08-19/ee9c8a15-f589-47cf-90f8-70f03668a2c9-1566162219195.png\",\n" + "        \"signatrue\": \"Avant Laube\"\n" + "      },\n" + "      \"openPush\": false\n" + "    }")); } }
3e0be77d6a454163874fe50b935646efe8b62f2d
430
java
Java
dora/src/test/java/fixtures/model/Attach.java
nrudenko/dora
5396c05394fd240bfe72b5b1ca48b3cae2039600
[ "MIT" ]
4
2016-02-08T22:13:31.000Z
2017-02-28T18:18:19.000Z
dora/src/test/java/fixtures/model/Attach.java
nrudenko/dora
5396c05394fd240bfe72b5b1ca48b3cae2039600
[ "MIT" ]
null
null
null
dora/src/test/java/fixtures/model/Attach.java
nrudenko/dora
5396c05394fd240bfe72b5b1ca48b3cae2039600
[ "MIT" ]
null
null
null
21.5
56
0.693023
5,033
package fixtures.model; import com.github.nrudenko.dora.annotation.DbColumn; import com.github.nrudenko.dora.annotation.Table; @Table public class Attach { public int _id; public String url; @DbColumn(additional = "UNIQUE ON CONFLICT REPLACE") public String messageId; public Attach() {} public Attach(String url, String messageId) { this.url = url; this.messageId = messageId; } }
3e0be8458fda1a1acd87348cefc07919fd7cd7a3
773
java
Java
webapp/src/main/java/io/webApp/springbootstarter/WebApiApp.java
DD-HAREKAZE/csye6225-spring2019
f49524eaf5b9ba650278f4aaeb2169fccc1c4835
[ "Apache-2.0" ]
null
null
null
webapp/src/main/java/io/webApp/springbootstarter/WebApiApp.java
DD-HAREKAZE/csye6225-spring2019
f49524eaf5b9ba650278f4aaeb2169fccc1c4835
[ "Apache-2.0" ]
null
null
null
webapp/src/main/java/io/webApp/springbootstarter/WebApiApp.java
DD-HAREKAZE/csye6225-spring2019
f49524eaf5b9ba650278f4aaeb2169fccc1c4835
[ "Apache-2.0" ]
null
null
null
32.208333
81
0.789133
5,034
package io.webApp.springbootstarter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import io.webApp.springbootstarter.fileStorage.FileStorageProperties; @SpringBootApplication @EnableConfigurationProperties({ FileStorageProperties.class }) public class WebApiApp { private final static Logger logger = LoggerFactory.getLogger(WebApiApp.class); public static void main(String[] args) { // TODO Auto-generated method stub logger.info("\n###############Application running##################\n"); SpringApplication.run(WebApiApp.class, args); } }
3e0be854296dfd948d172fdd2113b91a5470d083
2,446
java
Java
tsdbreader/src/main/java/com/alibaba/datax/plugin/reader/tsdbreader/util/HttpUtils.java
chenzhaoplus/DataX
d131bcc2b0bf9fed69efa931597e51c68d348132
[ "Apache-2.0" ]
14,564
2015-12-10T07:48:57.000Z
2022-03-31T08:20:41.000Z
tsdbreader/src/main/java/com/alibaba/datax/plugin/reader/tsdbreader/util/HttpUtils.java
chenzhaoplus/DataX
d131bcc2b0bf9fed69efa931597e51c68d348132
[ "Apache-2.0" ]
1,390
2015-12-27T07:33:57.000Z
2022-03-30T08:11:59.000Z
tsdbreader/src/main/java/com/alibaba/datax/plugin/reader/tsdbreader/util/HttpUtils.java
chenzhaoplus/DataX
d131bcc2b0bf9fed69efa931597e51c68d348132
[ "Apache-2.0" ]
5,545
2015-12-11T08:20:31.000Z
2022-03-31T08:58:30.000Z
35.970588
117
0.674162
5,035
package com.alibaba.datax.plugin.reader.tsdbreader.util; import com.alibaba.fastjson.JSON; import org.apache.http.client.fluent.Content; import org.apache.http.client.fluent.Request; import org.apache.http.entity.ContentType; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Copyright @ 2019 alibaba.com * All right reserved. * Function:HttpUtils * * @author Benedict Jin * @since 2019-10-21 */ public final class HttpUtils { public final static int CONNECT_TIMEOUT_DEFAULT_IN_MILL = (int) TimeUnit.SECONDS.toMillis(60); public final static int SOCKET_TIMEOUT_DEFAULT_IN_MILL = (int) TimeUnit.SECONDS.toMillis(60); private HttpUtils() { } public static String get(String url) throws Exception { Content content = Request.Get(url) .connectTimeout(CONNECT_TIMEOUT_DEFAULT_IN_MILL) .socketTimeout(SOCKET_TIMEOUT_DEFAULT_IN_MILL) .execute() .returnContent(); if (content == null) { return null; } return content.asString(StandardCharsets.UTF_8); } public static String post(String url, Map<String, Object> params) throws Exception { return post(url, JSON.toJSONString(params), CONNECT_TIMEOUT_DEFAULT_IN_MILL, SOCKET_TIMEOUT_DEFAULT_IN_MILL); } public static String post(String url, String params) throws Exception { return post(url, params, CONNECT_TIMEOUT_DEFAULT_IN_MILL, SOCKET_TIMEOUT_DEFAULT_IN_MILL); } public static String post(String url, Map<String, Object> params, int connectTimeoutInMill, int socketTimeoutInMill) throws Exception { return post(url, JSON.toJSONString(params), connectTimeoutInMill, socketTimeoutInMill); } public static String post(String url, String params, int connectTimeoutInMill, int socketTimeoutInMill) throws Exception { Content content = Request.Post(url) .connectTimeout(connectTimeoutInMill) .socketTimeout(socketTimeoutInMill) .addHeader("Content-Type", "application/json") .bodyString(params, ContentType.APPLICATION_JSON) .execute() .returnContent(); if (content == null) { return null; } return content.asString(StandardCharsets.UTF_8); } }
3e0be8b3919229264f4003eef96bc6f7376cc739
3,538
java
Java
aws-java-sdk-nimblestudio/src/main/java/com/amazonaws/services/nimblestudio/model/transform/EulaJsonUnmarshaller.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-nimblestudio/src/main/java/com/amazonaws/services/nimblestudio/model/transform/EulaJsonUnmarshaller.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-nimblestudio/src/main/java/com/amazonaws/services/nimblestudio/model/transform/EulaJsonUnmarshaller.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
38.879121
136
0.624647
5,036
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.nimblestudio.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.nimblestudio.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * Eula JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class EulaJsonUnmarshaller implements Unmarshaller<Eula, JsonUnmarshallerContext> { public Eula unmarshall(JsonUnmarshallerContext context) throws Exception { Eula eula = new Eula(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("content", targetDepth)) { context.nextToken(); eula.setContent(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("createdAt", targetDepth)) { context.nextToken(); eula.setCreatedAt(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context)); } if (context.testExpression("eulaId", targetDepth)) { context.nextToken(); eula.setEulaId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("name", targetDepth)) { context.nextToken(); eula.setName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("updatedAt", targetDepth)) { context.nextToken(); eula.setUpdatedAt(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return eula; } private static EulaJsonUnmarshaller instance; public static EulaJsonUnmarshaller getInstance() { if (instance == null) instance = new EulaJsonUnmarshaller(); return instance; } }
3e0be8e86384c37e13d2b9489dec62664df91aa6
9,184
java
Java
library/src/main/java/com/firebase/geofire/core/GeoHashQuery.java
VuongDo92/realtime-location-android
49b3415198c581caaaace9273126bfcbd8ca1f1d
[ "Apache-2.0" ]
125
2019-06-13T02:25:38.000Z
2022-03-23T18:03:39.000Z
library/src/main/java/com/firebase/geofire/core/GeoHashQuery.java
VuongDo92/realtime-location-android
49b3415198c581caaaace9273126bfcbd8ca1f1d
[ "Apache-2.0" ]
16
2020-01-04T04:44:09.000Z
2022-03-27T16:57:59.000Z
library/src/main/java/com/firebase/geofire/core/GeoHashQuery.java
VuongDo92/realtime-location-android
49b3415198c581caaaace9273126bfcbd8ca1f1d
[ "Apache-2.0" ]
38
2019-06-14T12:36:36.000Z
2022-03-13T17:32:18.000Z
41.369369
125
0.650479
5,037
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.firebase.geofire.core; import com.firebase.geofire.GeoLocation; import com.firebase.geofire.util.Base32Utils; import com.firebase.geofire.util.Constants; import com.firebase.geofire.util.GeoUtils; import java.util.HashSet; import java.util.Set; public class GeoHashQuery { public static final class Utils { private Utils() { throw new AssertionError("No instances."); } public static double bitsLatitude(double resolution) { return Math.min(Math.log(Constants.EARTH_MERIDIONAL_CIRCUMFERENCE/2/resolution)/Math.log(2), GeoHash.MAX_PRECISION_BITS); } public static double bitsLongitude(double resolution, double latitude) { double degrees = GeoUtils.distanceToLongitudeDegrees(resolution, latitude); return (Math.abs(degrees) > 0) ? Math.max(1, Math.log(360/degrees)/Math.log(2)) : 1; } public static int bitsForBoundingBox(GeoLocation location, double size) { double latitudeDegreesDelta = GeoUtils.distanceToLatitudeDegrees(size); double latitudeNorth = Math.min(90, location.latitude + latitudeDegreesDelta); double latitudeSouth = Math.max(-90, location.latitude - latitudeDegreesDelta); int bitsLatitude = (int)Math.floor(Utils.bitsLatitude(size)) *2; int bitsLongitudeNorth = (int)Math.floor(Utils.bitsLongitude(size, latitudeNorth)) *2 - 1; int bitsLongitudeSouth = (int)Math.floor(Utils.bitsLongitude(size, latitudeSouth)) *2 - 1; return Math.min(bitsLatitude, Math.min(bitsLongitudeNorth, bitsLongitudeSouth)); } } private final String startValue; private final String endValue; public GeoHashQuery(String startValue, String endValue) { this.startValue = startValue; this.endValue = endValue; } public static GeoHashQuery queryForGeoHash(GeoHash geohash, int bits) { String hash = geohash.getGeoHashString(); int precision = (int)Math.ceil((double)bits/Base32Utils.BITS_PER_BASE32_CHAR); if (hash.length() < precision) { return new GeoHashQuery(hash, hash+"~"); } hash = hash.substring(0, precision); String base = hash.substring(0, hash.length() - 1); int lastValue = Base32Utils.base32CharToValue(hash.charAt(hash.length() - 1)); int significantBits = bits - (base.length() * Base32Utils.BITS_PER_BASE32_CHAR); int unusedBits = Base32Utils.BITS_PER_BASE32_CHAR - significantBits; // delete unused bits int startValue = (lastValue >> unusedBits) << unusedBits; int endValue = startValue + (1 << unusedBits); String startHash = base + Base32Utils.valueToBase32Char(startValue); String endHash; if (endValue > 31) { endHash = base + "~"; } else { endHash = base + Base32Utils.valueToBase32Char(endValue); } return new GeoHashQuery(startHash, endHash); } public static Set<GeoHashQuery> queriesAtLocation(GeoLocation location, double radius) { int queryBits = Math.max(1, Utils.bitsForBoundingBox(location, radius)); int geoHashPrecision = (int) Math.ceil((float)queryBits /Base32Utils.BITS_PER_BASE32_CHAR); double latitude = location.latitude; double longitude = location.longitude; double latitudeDegrees = radius/Constants.METERS_PER_DEGREE_LATITUDE; double latitudeNorth = Math.min(90, latitude + latitudeDegrees); double latitudeSouth = Math.max(-90, latitude - latitudeDegrees); double longitudeDeltaNorth = GeoUtils.distanceToLongitudeDegrees(radius, latitudeNorth); double longitudeDeltaSouth = GeoUtils.distanceToLongitudeDegrees(radius, latitudeSouth); double longitudeDelta = Math.max(longitudeDeltaNorth, longitudeDeltaSouth); Set<GeoHashQuery> queries = new HashSet<>(); GeoHash geoHash = new GeoHash(latitude, longitude, geoHashPrecision); GeoHash geoHashW = new GeoHash(latitude, GeoUtils.wrapLongitude(longitude - longitudeDelta), geoHashPrecision); GeoHash geoHashE = new GeoHash(latitude, GeoUtils.wrapLongitude(longitude + longitudeDelta), geoHashPrecision); GeoHash geoHashN = new GeoHash(latitudeNorth, longitude, geoHashPrecision); GeoHash geoHashNW = new GeoHash(latitudeNorth, GeoUtils.wrapLongitude(longitude - longitudeDelta), geoHashPrecision); GeoHash geoHashNE = new GeoHash(latitudeNorth, GeoUtils.wrapLongitude(longitude + longitudeDelta), geoHashPrecision); GeoHash geoHashS = new GeoHash(latitudeSouth, longitude, geoHashPrecision); GeoHash geoHashSW = new GeoHash(latitudeSouth, GeoUtils.wrapLongitude(longitude - longitudeDelta), geoHashPrecision); GeoHash geoHashSE = new GeoHash(latitudeSouth, GeoUtils.wrapLongitude(longitude + longitudeDelta), geoHashPrecision); queries.add(queryForGeoHash(geoHash, queryBits)); queries.add(queryForGeoHash(geoHashE, queryBits)); queries.add(queryForGeoHash(geoHashW, queryBits)); queries.add(queryForGeoHash(geoHashN, queryBits)); queries.add(queryForGeoHash(geoHashNE, queryBits)); queries.add(queryForGeoHash(geoHashNW, queryBits)); queries.add(queryForGeoHash(geoHashS, queryBits)); queries.add(queryForGeoHash(geoHashSE, queryBits)); queries.add(queryForGeoHash(geoHashSW, queryBits)); // Join queries boolean didJoin; do { GeoHashQuery query1 = null; GeoHashQuery query2 = null; for (GeoHashQuery query: queries) { for (GeoHashQuery other: queries) { if (query != other && query.canJoinWith(other)) { query1 = query; query2 = other; break; } } } if (query1 != null && query2 != null) { queries.remove(query1); queries.remove(query2); queries.add(query1.joinWith(query2)); didJoin = true; } else { didJoin = false; } } while (didJoin); return queries; } private boolean isPrefix(GeoHashQuery other) { return (other.endValue.compareTo(this.startValue) >= 0) && (other.startValue.compareTo(this.startValue) < 0) && (other.endValue.compareTo(this.endValue) < 0); } private boolean isSuperQuery(GeoHashQuery other) { int startCompare = other.startValue.compareTo(this.startValue); return startCompare <= 0 && other.endValue.compareTo(this.endValue) >= 0; } public boolean canJoinWith(GeoHashQuery other) { return this.isPrefix(other) || other.isPrefix(this) || this.isSuperQuery(other) || other.isSuperQuery(this); } public GeoHashQuery joinWith(GeoHashQuery other) { if (other.isPrefix(this)) { return new GeoHashQuery(this.startValue, other.endValue); } else if (this.isPrefix(other)) { return new GeoHashQuery(other.startValue, this.endValue); } else if (this.isSuperQuery(other)) { return other; } else if (other.isSuperQuery(this)) { return this; } else { throw new IllegalArgumentException("Can't join these 2 queries: " + this + ", " + other); } } public boolean containsGeoHash(GeoHash hash) { String hashStr = hash.getGeoHashString(); return this.startValue.compareTo(hashStr) <= 0 && this.endValue.compareTo(hashStr) > 0; } public String getStartValue() { return this.startValue; } public String getEndValue() { return this.endValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GeoHashQuery that = (GeoHashQuery) o; if (!endValue.equals(that.endValue)) return false; if (!startValue.equals(that.startValue)) return false; return true; } @Override public int hashCode() { int result = startValue.hashCode(); result = 31 * result + endValue.hashCode(); return result; } @Override public String toString() { return "GeoHashQuery{" + "startValue='" + startValue + '\'' + ", endValue='" + endValue + '\'' + '}'; } }
3e0be8eeaa22288abd1c08b88a473ebec03fbfa5
1,352
java
Java
hazelcast/src/main/java/com/hazelcast/map/impl/mapstore/writebehind/StoreEvent.java
ldziedziul-gh-tests/hazelcast
3a7382ac8164bc17836fc9b1f852b2667e7bef96
[ "ECL-2.0", "Apache-2.0" ]
4,283
2015-01-02T03:56:10.000Z
2022-03-29T23:07:45.000Z
hazelcast/src/main/java/com/hazelcast/map/impl/mapstore/writebehind/StoreEvent.java
ldziedziul-gh-tests/hazelcast
3a7382ac8164bc17836fc9b1f852b2667e7bef96
[ "ECL-2.0", "Apache-2.0" ]
14,014
2015-01-01T04:29:38.000Z
2022-03-31T21:47:55.000Z
hazelcast/src/main/java/com/hazelcast/map/impl/mapstore/writebehind/StoreEvent.java
ldziedziul-gh-tests/hazelcast
3a7382ac8164bc17836fc9b1f852b2667e7bef96
[ "ECL-2.0", "Apache-2.0" ]
1,608
2015-01-04T09:57:08.000Z
2022-03-31T12:05:26.000Z
27.591837
75
0.693787
5,038
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.impl.mapstore.writebehind; import java.util.EventObject; /** * For internal usage only. * * @param <E> */ public final class StoreEvent<E> extends EventObject { private static final long serialVersionUID = -7071512331813330032L; /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred. * @throws IllegalArgumentException if source is null. */ private StoreEvent(E source) { super(source); } public static <E> StoreEvent<E> createStoreEvent(E source) { return new StoreEvent<>(source); } @Override public E getSource() { return (E) super.getSource(); } }
3e0be90360ed9408102bb391b7a8d8c54bce86c0
2,401
java
Java
sproutStudy_ejb/src/main/java/edu/harvard/mgh/lcs/sprout/forms/study/to/CohortMemberTO.java
stephenlorenz/sproutstudy
5070cba7a44f015b5eabc961409a37229161fa95
[ "Apache-2.0" ]
null
null
null
sproutStudy_ejb/src/main/java/edu/harvard/mgh/lcs/sprout/forms/study/to/CohortMemberTO.java
stephenlorenz/sproutstudy
5070cba7a44f015b5eabc961409a37229161fa95
[ "Apache-2.0" ]
null
null
null
sproutStudy_ejb/src/main/java/edu/harvard/mgh/lcs/sprout/forms/study/to/CohortMemberTO.java
stephenlorenz/sproutstudy
5070cba7a44f015b5eabc961409a37229161fa95
[ "Apache-2.0" ]
null
null
null
23.539216
87
0.643065
5,039
package edu.harvard.mgh.lcs.sprout.forms.study.to; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; public class CohortMemberTO implements Serializable { private String fullName; private String prettyName; private String firstName; private String middleName; private String lastName; private String email; private String gender; private Date birthDate; private List<CohortAddressTO> cohortAddressTOList; private List<CohortIdentityTO> cohortIdentityTOList; public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getPrettyName() { return prettyName; } public void setPrettyName(String prettyName) { this.prettyName = prettyName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public List<CohortAddressTO> getCohortAddressTOList() { return cohortAddressTOList; } public void setCohortAddressTOList(List<CohortAddressTO> cohortAddressTOList) { this.cohortAddressTOList = cohortAddressTOList; } public List<CohortIdentityTO> getCohortIdentityTOList() { return cohortIdentityTOList; } public void setCohortIdentityTOList(List<CohortIdentityTO> cohortIdentityTOList) { this.cohortIdentityTOList = cohortIdentityTOList; } }
3e0beb45a02cc786ab17213068f0242d2e493870
610
java
Java
8._Paintings/src/main/java/dk/andl/paintings/models/Gallery.java
anderslatif/Kea_DAT20A_Construction_2019_Autumn
f9f21d6411ce4968aa365971395cf7626c910be0
[ "MIT" ]
2
2021-09-08T06:55:21.000Z
2021-10-05T06:30:00.000Z
8._Paintings/src/main/java/dk/andl/paintings/models/Gallery.java
anderslatif/Kea_DAT20A_Construction_2021_Autumn
f9f21d6411ce4968aa365971395cf7626c910be0
[ "MIT" ]
null
null
null
8._Paintings/src/main/java/dk/andl/paintings/models/Gallery.java
anderslatif/Kea_DAT20A_Construction_2021_Autumn
f9f21d6411ce4968aa365971395cf7626c910be0
[ "MIT" ]
2
2021-09-30T06:58:13.000Z
2021-11-25T13:05:37.000Z
17.428571
87
0.703279
5,040
package dk.andl.paintings.models; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import javax.persistence.*; import java.util.Set; @Data @Table(name = "galleries") @Entity public class Gallery { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id private Long id; @Column private String owner; @Column private String name; @Column private String location; @Column private int squareFeet; @JsonIgnore @OneToMany(mappedBy = "gallery", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private Set<Artist> artists; }
3e0bebb76e8d5be19bb18a284c37a07649802217
754
java
Java
pvmanager/datasource-timecache/src/main/java/org/diirt/datasource/timecache/PVCacheListener.java
diirt/diirt
6070306dd321e95dc6ca15e9c04903fae7b595a9
[ "MIT" ]
12
2015-03-24T19:11:36.000Z
2021-08-14T11:48:05.000Z
pvmanager/datasource-timecache/src/main/java/org/diirt/datasource/timecache/PVCacheListener.java
diirt/diirt
6070306dd321e95dc6ca15e9c04903fae7b595a9
[ "MIT" ]
36
2015-01-20T14:37:30.000Z
2022-02-16T00:55:15.000Z
pvmanager/datasource-timecache/src/main/java/org/diirt/datasource/timecache/PVCacheListener.java
diirt/diirt
6070306dd321e95dc6ca15e9c04903fae7b595a9
[ "MIT" ]
13
2015-01-13T00:17:43.000Z
2018-07-03T10:57:08.000Z
29
82
0.740053
5,041
/** * Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.datasource.timecache; import java.util.SortedSet; import org.diirt.datasource.timecache.util.IntervalsList; import org.diirt.util.time.TimeInterval; /** * {@link PVCache} listener. * @author Fred Arnaud (Sopra Group) - ITER */ public interface PVCacheListener { /** Informs that a new set of {@link Data} is available in storage. */ public void newDataInCache(final SortedSet<Data> newData, final TimeInterval newDataInterval, final IntervalsList completedIntervals); public void updatedCompletedIntervals(final IntervalsList completedIntervals); }
3e0bec2db645c3a0b2507b6db689a010ce20181a
4,994
java
Java
app/src/main/java/com/orange/orangenote/util/ContentUtil.java
ChiuLui/orangenote
c92a741c11affb189dbb672f67fde8ecbdc4a5da
[ "Apache-2.0" ]
5
2021-06-23T09:47:59.000Z
2021-09-14T08:45:36.000Z
app/src/main/java/com/orange/orangenote/util/ContentUtil.java
ChiuLui/orangenote
c92a741c11affb189dbb672f67fde8ecbdc4a5da
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/orange/orangenote/util/ContentUtil.java
ChiuLui/orangenote
c92a741c11affb189dbb672f67fde8ecbdc4a5da
[ "Apache-2.0" ]
2
2019-05-08T11:05:36.000Z
2020-06-10T05:23:54.000Z
25.875648
90
0.445134
5,042
package com.orange.orangenote.util; /** * @author 神经大条蕾弟 * @version 1.0 * @date 2018/04/21 18:01 * @copyright 赵蕾 */ public class ContentUtil { private static final int TITLE_LENGHT = 20; private static final int CONTENT_LENGHT = 100; /** * 把一段字符串截取成要显示的标题 * @param content * @return */ public static String getTitle(String content){ String temp = content; //---有换行符 if (temp.contains("\n")){ return temp.substring(0,temp.indexOf("\n")); } else { //---没换行符 //长度小于20个字,直接返回 if (temp.length() < TITLE_LENGHT){ return temp; } else { //否则截取前20个字 return temp.substring(0, TITLE_LENGHT); } } } /** * 在瀑布流界面用于裁剪标题 * @param content * @param length * @return */ public static String getTitle(String content,int length){ String temp = content; //---有换行符 if (temp.contains("\n")){ return temp.substring(0,temp.indexOf("\n")); } else { //---没换行符 //长度小于20个字,直接返回 if (temp.length() < length){ return temp; } else { //否则截取前20个字 return temp.substring(0, length); } } } /** * 把一段字符串截取成要显示的内容概略 * @param content * @return */ public static String getContent(String content){ String temp = content; //---有换行符 if (temp.contains("\n")){ //截取换行符后面的文字 temp = temp.substring(temp.indexOf("\n")+1);//+1是因为不截取换行符 if (temp.contains("\n")){ temp = temp.substring(0,temp.indexOf("\n")); if (temp.length() > 0) { temp = temp; } else { temp = ""; } } else { if (content.substring(0,content.indexOf("\n")).length() > TITLE_LENGHT) { temp = "..." + temp; } else { temp = temp; } } } else { //没换行符 if (temp.length() < TITLE_LENGHT){ temp = ""; } else { temp = temp.substring(TITLE_LENGHT); } } //长度小于100个字,直接返回 if (temp.length() < CONTENT_LENGHT){ temp = temp; } else { //否则截取前100个字 temp = temp.substring(0,CONTENT_LENGHT) + "..."; } return temp; } /** * 在瀑布流界面用于裁剪内容 * @param content * @param title_lenght * @return */ public static String getContent(String content, int title_lenght){ String temp = content; //---有换行符 if (temp.contains("\n")){ //截取换行符后面的文字 temp = temp.substring(temp.indexOf("\n")+1);//+1是因为不截取换行符 if (temp.contains("\n")){ temp = temp.substring(0,temp.indexOf("\n")); if (temp.length() > 0) { temp = temp; } else { temp = ""; } } else { if (content.substring(0,content.indexOf("\n")).length() > title_lenght) { temp = "..." + temp; } else { temp = temp; } } } else { //没换行符 if (temp.length() < title_lenght){ temp = ""; } else { temp = temp.substring(title_lenght); } } //长度小于100个字,直接返回 if (temp.length() < CONTENT_LENGHT){ temp = temp; } else { //否则截取前100个字 temp = temp.substring(0,CONTENT_LENGHT) + "..."; } return temp; } /** * 截取用于放在提示界面的内容 * @param content * @return */ public static String getDialogContent(String content){ String temp = content; if (content.length() <= 60){ return temp; }else { return temp.substring(0,60) + "..."; } } /** * 用于更换HTML中的换行和空格 * 用于剔除HTML格式 * @param content * @return */ public static String getNoHtmlContent(String content){ String temp = content; temp = temp.replaceAll("<br>", "\n"); //更换<br>和标签 temp = temp.replaceAll("&nbsp;", " "); //更换&nbsp;标签 temp = temp.replaceAll("</?[^>]+>", ""); //剔出<html>的标签 // temp = temp.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符 return temp; } /** * 替换内容 * @param regex 要替换的内容 * @param replacement 替换的内容 * @return */ public static String replaceContent(String content, String regex, String replacement){ String temp = content; temp = temp.replaceAll(regex, replacement); return temp; } }
3e0becc246aabc3306535c7a2402d8b274435fea
719
java
Java
freeze2/src/main/java/com/isaacbrodsky/freeze2/game/editor/ViewMode.java
isaacbrodsky/freeze
a2114b53a8e866fd2f070d4b049c13cc757f3975
[ "MIT" ]
null
null
null
freeze2/src/main/java/com/isaacbrodsky/freeze2/game/editor/ViewMode.java
isaacbrodsky/freeze
a2114b53a8e866fd2f070d4b049c13cc757f3975
[ "MIT" ]
null
null
null
freeze2/src/main/java/com/isaacbrodsky/freeze2/game/editor/ViewMode.java
isaacbrodsky/freeze
a2114b53a8e866fd2f070d4b049c13cc757f3975
[ "MIT" ]
null
null
null
17.119048
89
0.66064
5,043
/** * */ package com.isaacbrodsky.freeze2.game.editor; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author isaac * */ public enum ViewMode { EDITOR, PREVIEW, EMPTIES, STAT_COUNT, STAT_ORDER, SUPER_WINDOW, MONOCHROME, OOP_PRESENT, WALKABLE; public static String makeViewModeList() { return AddElementUtils.makeSelectionList( Stream.of(values()) .map(m -> new AddElementUtils.Selection(Integer.toString(m.ordinal() + 1), m.name())) .collect(Collectors.toList()), true); } public static ViewMode forCode(String cmd) { int i = cmd.charAt(0) - '1'; for (ViewMode m : values()) { if (m.ordinal() == i) { return m; } } return null; } }
3e0beda6b63b577ae586fed1be998225bb7275d3
667
java
Java
src/main/java/com/wissen/e_commerce/pojo/InventoryBo.java
punitsukhija/E_Commerce
69c59bf258f17845be8deeb0f28b8468e7e965e0
[ "Unlicense" ]
null
null
null
src/main/java/com/wissen/e_commerce/pojo/InventoryBo.java
punitsukhija/E_Commerce
69c59bf258f17845be8deeb0f28b8468e7e965e0
[ "Unlicense" ]
null
null
null
src/main/java/com/wissen/e_commerce/pojo/InventoryBo.java
punitsukhija/E_Commerce
69c59bf258f17845be8deeb0f28b8468e7e965e0
[ "Unlicense" ]
null
null
null
18.527778
54
0.724138
5,044
package com.wissen.e_commerce.pojo; public class InventoryBo extends BaseInventoryBo { private String inventoryName; private String location; private String sellerEmailId; public String getInventoryName() { return inventoryName; } public void setInventoryName(String inventoryName) { this.inventoryName = inventoryName; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getSellerEmailId() { return sellerEmailId; } public void setSellerEmailId(String sellerEmailId) { this.sellerEmailId = sellerEmailId; } }
3e0bee2dd11080d9f8cecb1d0c1aaaa7a5ed138d
1,175
java
Java
src/main/java/frc/robot/commands/AutoZeroYaw.java
RoboLions/frc-2022-new
c16bdd0054b12deebb8f1efb5ea3a5e2dee6b651
[ "BSD-3-Clause" ]
1
2022-02-17T19:43:12.000Z
2022-02-17T19:43:12.000Z
src/main/java/frc/robot/commands/AutoZeroYaw.java
RoboLions/frc-2022-new
c16bdd0054b12deebb8f1efb5ea3a5e2dee6b651
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/AutoZeroYaw.java
RoboLions/frc-2022-new
c16bdd0054b12deebb8f1efb5ea3a5e2dee6b651
[ "BSD-3-Clause" ]
null
null
null
24.479167
74
0.71234
5,045
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.DriveSubsystem; public class AutoZeroYaw extends CommandBase { private final DriveSubsystem drivesubsystem; private boolean endme = false; public AutoZeroYaw(final DriveSubsystem subsystem) { drivesubsystem = subsystem; addRequirements(drivesubsystem); } // Called when the command is initially scheduled. @Override public void initialize() { drivesubsystem.ZeroYaw(); } // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { if (drivesubsystem.getYaw() == 0) { endme = true; } else { endme = false; } } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { endme = true; } // Returns true when the command should end. @Override public boolean isFinished() { return endme; } }
3e0bee6913c95f7bf9de22b9bb4b86fd3020a1ec
2,202
java
Java
src/java/com/echothree/control/user/filter/common/result/GetFilterStepElementDescriptionsResult.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-09-01T08:39:01.000Z
2020-09-01T08:39:01.000Z
src/java/com/echothree/control/user/filter/common/result/GetFilterStepElementDescriptionsResult.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
null
null
null
src/java/com/echothree/control/user/filter/common/result/GetFilterStepElementDescriptionsResult.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-05-31T08:34:46.000Z
2020-05-31T08:34:46.000Z
44.04
116
0.738874
5,046
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // -------------------------------------------------------------------------------- package com.echothree.control.user.filter.common.result; import com.echothree.model.control.filter.common.transfer.FilterKindTransfer; import com.echothree.model.control.filter.common.transfer.FilterStepElementDescriptionTransfer; import com.echothree.model.control.filter.common.transfer.FilterStepElementTransfer; import com.echothree.model.control.filter.common.transfer.FilterStepTransfer; import com.echothree.model.control.filter.common.transfer.FilterTransfer; import com.echothree.model.control.filter.common.transfer.FilterTypeTransfer; import com.echothree.util.common.command.BaseResult; import java.util.List; public interface GetFilterStepElementDescriptionsResult extends BaseResult { FilterKindTransfer getFilterKind(); void setFilterKind(FilterKindTransfer filterKind); FilterTypeTransfer getFilterType(); void setFilterType(FilterTypeTransfer filterType); FilterTransfer getFilter(); void setFilter(FilterTransfer filter); FilterStepTransfer getFilterStep(); void setFilterStep(FilterStepTransfer filterStep); FilterStepElementTransfer getFilterStepElement(); void setFilterStepElement(FilterStepElementTransfer filterStepElement); List<FilterStepElementDescriptionTransfer> getFilterStepElementDescriptions(); void setFilterStepElementDescriptions(List<FilterStepElementDescriptionTransfer> filterStepElementDescriptions); }
3e0bee90bc1271f5d08884c40c7f904470de2dab
277
java
Java
wuffy-network/src/main/java/net/wuffy/network/Packet.java
NgLoader/Discord-Bot-Wuffy-v1
8ea01c1bcf88444e7bccb6406026985e5264398d
[ "Apache-2.0" ]
null
null
null
wuffy-network/src/main/java/net/wuffy/network/Packet.java
NgLoader/Discord-Bot-Wuffy-v1
8ea01c1bcf88444e7bccb6406026985e5264398d
[ "Apache-2.0" ]
null
null
null
wuffy-network/src/main/java/net/wuffy/network/Packet.java
NgLoader/Discord-Bot-Wuffy-v1
8ea01c1bcf88444e7bccb6406026985e5264398d
[ "Apache-2.0" ]
null
null
null
21.307692
58
0.776173
5,047
package net.wuffy.network; import java.io.IOException; /** * @author Ingrim4 */ public interface Packet<T extends INetHandler> { void read(PacketBuffer packetBuffer) throws IOException; void write(PacketBuffer packetBuffer) throws IOException; void handle(T handler); }
3e0bef2b5b054e367bc295b3bbe42a4fbd88dd63
7,110
java
Java
iot/home-management-system/android-app/app/src/main/java/com/hms/power_sockets/view/activities/PowerSocketsActivity.java
Kyledmw/student-projects
766ef9d4b879c8c2d2086c2abe0fa224e2e051c6
[ "Apache-2.0" ]
null
null
null
iot/home-management-system/android-app/app/src/main/java/com/hms/power_sockets/view/activities/PowerSocketsActivity.java
Kyledmw/student-projects
766ef9d4b879c8c2d2086c2abe0fa224e2e051c6
[ "Apache-2.0" ]
null
null
null
iot/home-management-system/android-app/app/src/main/java/com/hms/power_sockets/view/activities/PowerSocketsActivity.java
Kyledmw/student-projects
766ef9d4b879c8c2d2086c2abe0fa224e2e051c6
[ "Apache-2.0" ]
null
null
null
35.909091
128
0.665823
5,048
package com.hms.power_sockets.view.activities; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.hms.common.view.models.callbacks.exceptions.CallbackException; import com.hms.common.view.models.callbacks.interfaces.ICallback; import com.hms.common.controllers.ExternalController; import com.hms_app.R; import com.hms.account.view.activities.LoginActivity; import com.hms.devices.model.interfaces.IDeviceReadable; import com.hms.power_sockets.models.interfaces.IPowerSocketReadable; import com.hms.devices.model.DeviceModel; import com.hms.power_sockets.models.PowerSocketModel; import com.hms.power_sockets.view.util.PowerSocketsAdapter; import java.util.ArrayList; import java.util.List; public class PowerSocketsActivity extends AppCompatActivity implements ICallback<List<IPowerSocketReadable>> { private ExternalController _externalController; private ArrayList<IPowerSocketReadable> _powerSockets; private PowerSocketsAdapter _powerSocketsAdapter; private View _addPowerSocketView; private IDeviceReadable _device; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_power_sockets); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); final Bundle deviceBundle = getIntent().getExtras(); String deviceId = deviceBundle.getString("device_id"); String deviceName= deviceBundle.getString("device_name"); _device = new DeviceModel(deviceId, deviceName); _powerSockets = new ArrayList<>(); _powerSocketsAdapter = new PowerSocketsAdapter(this, _powerSockets, _device); ListView powerSocketsLv = (ListView)findViewById(R.id.power_sockets_lv); powerSocketsLv.setAdapter(_powerSocketsAdapter); _externalController = new ExternalController(); _externalController.getPowerSocketHandler().getPowerSockets(_device, this); showPowerSocketView(); initButtonListeners(); } private void initButtonListeners(){ FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showAddSocketView(); } }); final EditText socketNameEt = (EditText)findViewById(R.id.power_sockets_et_socket_name); final EditText socketNumberEt = (EditText)findViewById(R.id.power_sockets_et_socket_number); Button addBtn = (Button)_addPowerSocketView.findViewById(R.id.power_sockets_btn_add_socket); addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String socketName = socketNameEt.getText().toString(); String strSocketNumber = socketNumberEt.getText().toString(); if((socketName.isEmpty()) || (strSocketNumber.isEmpty())) { showDialog("Empty Fields!", "Please fill in all fields"); } else { int socketNumber = Integer.parseInt(strSocketNumber); IPowerSocketReadable powerSocket = new PowerSocketModel(null, socketName, socketNumber, false); _externalController.getPowerSocketHandler().sendPowerSocket(_device, powerSocket, new ICallback<Boolean>() { @Override public void callback(CallbackException e, Boolean data) { if (!data.booleanValue()) { showDialog("Error!", "Failed to add power socket, check your connection and try again."); } else { showPowerSocketView(); } } }); } } }); Button cancelBtn = (Button)_addPowerSocketView.findViewById(R.id.power_sockets_btn_cancel); cancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPowerSocketView(); socketNameEt.setText(""); socketNumberEt.setText(""); } }); } private void showDialog(String title, String message) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.setTitle(title); alertBuilder.setMessage(message); alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = alertBuilder.create(); alertDialog.show(); } private void showAddSocketView() { ListView powerSocketsLv = (ListView)findViewById(R.id.power_sockets_lv); powerSocketsLv.setVisibility(View.GONE); _addPowerSocketView = findViewById(R.id.power_sockets_add_view); _addPowerSocketView.setVisibility(View.VISIBLE); } private void showPowerSocketView() { ListView powerSocketsLv = (ListView)findViewById(R.id.power_sockets_lv); powerSocketsLv.setVisibility(View.VISIBLE); _addPowerSocketView = findViewById(R.id.power_sockets_add_view); _addPowerSocketView.setVisibility(View.GONE); } @Override public void callback(CallbackException e, List<IPowerSocketReadable> data) { _powerSocketsAdapter.clear(); _powerSocketsAdapter.addAll(data); } private void toLoginActivity() { Intent loginActivity = new Intent(this, LoginActivity.class); startActivity(loginActivity); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(android.view.MenuItem item) { switch (item.getItemId()) { case android.R.id.home: _externalController.getPowerSocketHandler().unRegisterAsCallback(); onBackPressed(); break; case R.id.logout_item: _externalController.getAccountHandler().logout(); _externalController.getPowerSocketHandler().unRegisterAsCallback(); toLoginActivity(); break; } return super.onOptionsItemSelected(item); } }
3e0bef4402114525495f2733aaa6074394ab69ce
589
java
Java
hyperion-client/src/main/java/it/takethesecoins/hyperion/grabbers/RobotGrabber.java
maxill1/hyperion-client
84712fa8aa93548a097b1058a0ff4d4bbcf9cff7
[ "MIT" ]
null
null
null
hyperion-client/src/main/java/it/takethesecoins/hyperion/grabbers/RobotGrabber.java
maxill1/hyperion-client
84712fa8aa93548a097b1058a0ff4d4bbcf9cff7
[ "MIT" ]
null
null
null
hyperion-client/src/main/java/it/takethesecoins/hyperion/grabbers/RobotGrabber.java
maxill1/hyperion-client
84712fa8aa93548a097b1058a0ff4d4bbcf9cff7
[ "MIT" ]
null
null
null
23.56
110
0.696095
5,049
package it.takethesecoins.hyperion.grabbers; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; /** * Grab screen using {@link Robot} * @author Luca * */ public class RobotGrabber extends AbsGrabber{ @Override protected BufferedImage getScreenshot() { BufferedImage screenShot = null; try { screenShot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); } catch (Exception e) { e.printStackTrace(); } return screenShot; } }
3e0bf0d7f5be7ae954dc5971b05c2181231d6101
12,175
java
Java
oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/mongo/ClusterConflictTest.java
sho25/jackrabbit-oak
1bb8a341fdf907578298f9ed52a48458e4f6efdc
[ "Apache-2.0" ]
null
null
null
oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/mongo/ClusterConflictTest.java
sho25/jackrabbit-oak
1bb8a341fdf907578298f9ed52a48458e4f6efdc
[ "Apache-2.0" ]
2
2020-06-15T19:48:29.000Z
2021-02-08T21:25:54.000Z
oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/mongo/ClusterConflictTest.java
sho25/jackrabbit-oak
1bb8a341fdf907578298f9ed52a48458e4f6efdc
[ "Apache-2.0" ]
null
null
null
14.511323
810
0.797618
5,050
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|document operator|. name|mongo package|; end_package begin_import import|import name|com operator|. name|mongodb operator|. name|MongoClient import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|CommitFailedException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|commons operator|. name|PathUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|document operator|. name|AbstractMongoConnectionTest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|document operator|. name|DocumentMK import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|document operator|. name|DocumentNodeStore import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|document operator|. name|LeaseCheckMode import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|document operator|. name|util operator|. name|MongoConnection import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|commit operator|. name|CommitHook import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|commit operator|. name|CommitInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|commit operator|. name|EmptyHook import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|state operator|. name|NodeBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|state operator|. name|NodeState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|state operator|. name|NodeStore import|; end_import begin_import import|import name|org operator|. name|jetbrains operator|. name|annotations operator|. name|NotNull import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|fail import|; end_import begin_class specifier|public class|class name|ClusterConflictTest extends|extends name|AbstractMongoConnectionTest block|{ specifier|private name|DocumentNodeStore name|ns2 decl_stmt|; annotation|@ name|Override specifier|public name|void name|setUpConnection parameter_list|() throws|throws name|Exception block|{ name|super operator|. name|setUpConnection argument_list|() expr_stmt|; name|MongoConnection name|connection init|= name|connectionFactory operator|. name|getConnection argument_list|() decl_stmt|; name|ns2 operator|= name|newBuilder argument_list|( name|connection operator|. name|getMongoClient argument_list|() argument_list|, name|connection operator|. name|getDBName argument_list|() argument_list|) operator|. name|setClusterId argument_list|( literal|2 argument_list|) operator|. name|getNodeStore argument_list|() expr_stmt|; block|} annotation|@ name|Override specifier|protected name|DocumentMK operator|. name|Builder name|newBuilder parameter_list|( name|MongoClient name|client parameter_list|, name|String name|dbName parameter_list|) throws|throws name|Exception block|{ return|return name|super operator|. name|newBuilder argument_list|( name|client argument_list|, name|dbName argument_list|) operator|. name|setAsyncDelay argument_list|( literal|0 argument_list|) operator|. name|setLeaseCheckMode argument_list|( name|LeaseCheckMode operator|. name|DISABLED argument_list|) return|; block|} annotation|@ name|Override specifier|public name|void name|tearDownConnection parameter_list|() throws|throws name|Exception block|{ name|ns2 operator|. name|dispose argument_list|() expr_stmt|; name|super operator|. name|tearDownConnection argument_list|() expr_stmt|; block|} comment|// OAK-3433 annotation|@ name|Test specifier|public name|void name|mergeRetryWhileBackgroundRead parameter_list|() throws|throws name|Exception block|{ name|DocumentNodeStore name|ns1 init|= name|mk operator|. name|getNodeStore argument_list|() decl_stmt|; name|NodeBuilder name|b1 init|= name|ns1 operator|. name|getRoot argument_list|() operator|. name|builder argument_list|() decl_stmt|; name|b1 operator|. name|child argument_list|( literal|"a" argument_list|) operator|. name|child argument_list|( literal|"b" argument_list|) operator|. name|child argument_list|( literal|"c" argument_list|) operator|. name|child argument_list|( literal|"foo" argument_list|) expr_stmt|; name|merge argument_list|( name|ns1 argument_list|, name|b1 argument_list|) expr_stmt|; name|ns1 operator|. name|runBackgroundOperations argument_list|() expr_stmt|; name|ns2 operator|. name|runBackgroundOperations argument_list|() expr_stmt|; name|NodeBuilder name|b2 init|= name|ns2 operator|. name|getRoot argument_list|() operator|. name|builder argument_list|() decl_stmt|; comment|// force cache fill name|assertNodeExists argument_list|( name|b2 argument_list|, literal|"/a/b/c/foo" argument_list|) expr_stmt|; comment|// remove /a/b/c on ns1 name|b1 operator|= name|ns1 operator|. name|getRoot argument_list|() operator|. name|builder argument_list|() expr_stmt|; name|b1 operator|. name|child argument_list|( literal|"a" argument_list|) operator|. name|child argument_list|( literal|"b" argument_list|) operator|. name|child argument_list|( literal|"c" argument_list|) operator|. name|remove argument_list|() expr_stmt|; name|merge argument_list|( name|ns1 argument_list|, name|b1 argument_list|) expr_stmt|; comment|// perform some change on ns2 name|b2 operator|. name|child argument_list|( literal|"z" argument_list|) expr_stmt|; name|merge argument_list|( name|ns2 argument_list|, name|b2 argument_list|) expr_stmt|; name|runBackgroundUpdate argument_list|( name|ns2 argument_list|) expr_stmt|; comment|// this will pickup changes done by ns2 and update comment|// the head revision name|runBackgroundRead argument_list|( name|ns1 argument_list|) expr_stmt|; comment|// the next step is where the issue described comment|// in OAK-3433 occurs. comment|// the journal entry with changes done on ns1 is pushed comment|// with the current head revision, which is newer comment|// than the most recent change in the journal entry name|runBackgroundUpdate argument_list|( name|ns1 argument_list|) expr_stmt|; comment|// perform a background read after the rebase comment|// the first merge attempt will fail with a conflict comment|// because /a/b/c is seen as changed in the future comment|// without the fix for OAK-3433: comment|// the second merge attempt succeeds because now the comment|// /a/b/c change revision is visible and happened before the commit comment|// revision but before the base revision name|b2 operator|= name|ns2 operator|. name|getRoot argument_list|() operator|. name|builder argument_list|() expr_stmt|; name|b2 operator|. name|child argument_list|( literal|"z" argument_list|) operator|. name|setProperty argument_list|( literal|"q" argument_list|, literal|"v" argument_list|) expr_stmt|; try|try block|{ name|ns2 operator|. name|merge argument_list|( name|b2 argument_list|, operator|new name|CommitHook argument_list|() block|{ annotation|@ name|NotNull annotation|@ name|Override specifier|public name|NodeState name|processCommit parameter_list|( name|NodeState name|before parameter_list|, name|NodeState name|after parameter_list|, name|CommitInfo name|info parameter_list|) throws|throws name|CommitFailedException block|{ name|runBackgroundRead argument_list|( name|ns2 argument_list|) expr_stmt|; name|NodeBuilder name|builder init|= name|after operator|. name|builder argument_list|() decl_stmt|; if|if condition|( name|builder operator|. name|getChildNode argument_list|( literal|"a" argument_list|) operator|. name|getChildNode argument_list|( literal|"b" argument_list|) operator|. name|hasChildNode argument_list|( literal|"c" argument_list|) condition|) block|{ name|builder operator|. name|child argument_list|( literal|"a" argument_list|) operator|. name|child argument_list|( literal|"b" argument_list|) operator|. name|child argument_list|( literal|"c" argument_list|) operator|. name|child argument_list|( literal|"bar" argument_list|) expr_stmt|; block|} else|else block|{ throw|throw operator|new name|CommitFailedException argument_list|( name|CommitFailedException operator|. name|OAK argument_list|, literal|0 argument_list|, literal|"/a/b/c does not exist anymore" argument_list|) throw|; block|} return|return name|builder operator|. name|getNodeState argument_list|() return|; block|} block|} argument_list|, name|CommitInfo operator|. name|EMPTY argument_list|) expr_stmt|; name|fail argument_list|( literal|"Merge must fail with CommitFailedException" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|CommitFailedException name|e parameter_list|) block|{ comment|// expected block|} block|} specifier|private name|void name|assertNodeExists parameter_list|( name|NodeBuilder name|builder parameter_list|, name|String name|path parameter_list|) block|{ for|for control|( name|String name|name range|: name|PathUtils operator|. name|elements argument_list|( name|path argument_list|) control|) block|{ name|builder operator|= name|builder operator|. name|getChildNode argument_list|( name|name argument_list|) expr_stmt|; name|assertTrue argument_list|( literal|"node '" operator|+ name|name operator|+ literal|"' does not exist" argument_list|, name|builder operator|. name|exists argument_list|() argument_list|) expr_stmt|; block|} block|} specifier|private specifier|static name|void name|merge parameter_list|( name|NodeStore name|store parameter_list|, name|NodeBuilder name|builder parameter_list|) throws|throws name|Exception block|{ name|store operator|. name|merge argument_list|( name|builder argument_list|, name|EmptyHook operator|. name|INSTANCE argument_list|, name|CommitInfo operator|. name|EMPTY argument_list|) expr_stmt|; block|} block|} end_class end_unit
3e0bf0d9083b2d39848af155f7b39419810d83c6
2,949
java
Java
app/controllers/HomeController.java
nookio/kitchen
243a30bdd0f658b9426c4db9804798c94f604a24
[ "Apache-2.0" ]
null
null
null
app/controllers/HomeController.java
nookio/kitchen
243a30bdd0f658b9426c4db9804798c94f604a24
[ "Apache-2.0" ]
null
null
null
app/controllers/HomeController.java
nookio/kitchen
243a30bdd0f658b9426c4db9804798c94f604a24
[ "Apache-2.0" ]
null
null
null
24.575
81
0.657172
5,051
package controllers; import com.google.inject.Inject; import helper.Response; import models.Contact; import models.Credential; import models.House; import models.address.Area; import models.address.City; import models.address.District; import models.address.Province; import play.mvc.*; import services.CredentialService; import services.HouseService; import services.PictureService; import views.html.*; import views.html.house.houseAdd; import views.html.house.houseShow; import views.html.house.houses; import views.html.staff.login; import vo.HouseVo; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * This controller contains an action to handle HTTP requests * to the application's home page. */ public class HomeController extends Controller { @Inject private HouseService houseService; @Inject private CredentialService credentialService; @Inject PictureService pictureService; public Result house(Integer id) { House house = houseService.get(id); Credential credential = credentialService.byHouseId(house.getId()); house.setCredential(credential); house.setPictures(pictureService.byHouseId(house.getId())); return ok(houseShow.apply(HouseVo.transformFromHouse(house, Contact.finder.byId(house.getContactId())))); } public Result jsp() { House house = houseService.get(1); return ok(jsq.apply(house)); } public Result home(){ return ok(home.apply()); } public Result show(Integer houseId) { House house = houseService.get(houseId); return ok(show.apply(house)); } public Result showCase() { // return ok(search.apply()); return TODO; } public Result editHouse() { return Results.TODO; } public Result houses() { return ok(houses.apply()); } public Result addHouse() { return ok(houseAdd.apply()); } public Result header() { if (null == session("user")) redirect("/staff/login"); return ok(header.apply(session("user"))); } public Result boot() { return ok(boot.apply()); } public Result getAreas() { List<Area> areas = Area.finder.where().eq("cityCode", 110100).findList(); return ok(areas.toString()); } /** * An action that renders an HTML page with a welcome message. * The configuration in the <code>routes</code> file means that * this method will be called when the application receives a * <code>GET</code> request with a path of <code>/</code>. */ public Result index() { return ok(index.render("Your new application is ready.")); } public Result login(){ return ok(login.render("welcome")); } // public Result houses() { // return ok(houses.render(Area.finder.where().eq("id", 1).findUnique())); // } }
3e0bf16b686b9b6f9d3ca678260c85acba029efd
1,073
java
Java
multi-module/main/src/test/java/pl/edu/agh/kis/pz1/ReaderXLSXTest.java
YgLK/parserCSV-XLSX-to-XML
224da9c18b76a959f2c1f032c6db8f8151384559
[ "MIT" ]
null
null
null
multi-module/main/src/test/java/pl/edu/agh/kis/pz1/ReaderXLSXTest.java
YgLK/parserCSV-XLSX-to-XML
224da9c18b76a959f2c1f032c6db8f8151384559
[ "MIT" ]
null
null
null
multi-module/main/src/test/java/pl/edu/agh/kis/pz1/ReaderXLSXTest.java
YgLK/parserCSV-XLSX-to-XML
224da9c18b76a959f2c1f032c6db8f8151384559
[ "MIT" ]
null
null
null
33.53125
83
0.643057
5,052
package pl.edu.agh.kis.pz1; import org.junit.Assert; import org.junit.Test; /** * Class used for testing XLSX reader * methods and functionalities. */ public class ReaderXLSXTest { @Test public void testIfAllInvoicesAreReadFromFile(){ Invoices invoices = new Invoices(); Summary sum = new Summary(); InvoiceCorrection invoiceCorrection = new InvoiceCorrection(); String path = "src/test/java/inv-test.xlsx"; ReaderXLSX readerXLSX = new ReaderXLSX(invoices, invoiceCorrection, path); // read data from csv test file and get data from records readerXLSX.readFromXLSXfile(); // this XLSX file isn't converted properly from CSV so some data from // CSV format is lost - that's why only 58 invoices is left in here // (I couldn't find more efficient csv to xlsx converter) Assert.assertEquals("Invoices list should contain 109 invoices.", 58, readerXLSX.getInvoices().getListInvoice().size() ); } }
3e0bf18760d2e2e221e64b9edfa9ba0585a337a5
9,926
java
Java
hl7_java/src/main/java/com/babylonhealth/lit/hl7_java/builders/Claim_SupportingInfoBuilder.java
babylonhealth/lit-fhir
7942938ec86ccc1ee7c17852032d5f5d06753629
[ "Apache-2.0" ]
18
2021-12-17T22:05:39.000Z
2022-01-28T14:14:15.000Z
hl7_java/src/main/java/com/babylonhealth/lit/hl7_java/builders/Claim_SupportingInfoBuilder.java
babylonhealth/lit-fhir
7942938ec86ccc1ee7c17852032d5f5d06753629
[ "Apache-2.0" ]
2
2021-12-21T19:19:01.000Z
2022-01-25T11:07:56.000Z
hl7_java/src/main/java/com/babylonhealth/lit/hl7_java/builders/Claim_SupportingInfoBuilder.java
babylonhealth/lit-fhir
7942938ec86ccc1ee7c17852032d5f5d06753629
[ "Apache-2.0" ]
null
null
null
41.705882
100
0.723151
5,053
package com.babylonhealth.lit.hl7_java.builders; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; import java.util.stream.Collectors; import scala.math.BigDecimal; import scala.Option; import scala.collection.immutable.Seq; import scala.jdk.javaapi.CollectionConverters; import scala.jdk.javaapi.OptionConverters; import lombok.NonNull; import com.babylonhealth.lit.core.FHIRComponentFieldMeta; import com.babylonhealth.lit.core.FHIRDateTime; import com.babylonhealth.lit.core.FHIRDate; import com.babylonhealth.lit.core.LitSeqJCollector; import com.babylonhealth.lit.core.LitSeq; import com.babylonhealth.lit.core.LitSeq$; import com.babylonhealth.lit.core.NonEmptyLitSeqJCollector; import com.babylonhealth.lit.core.Choice; import com.babylonhealth.lit.core.Choice$; import com.babylonhealth.lit.core.model.*; import com.babylonhealth.lit.hl7.model.*; import com.babylonhealth.lit.core_java.builders.*; import com.babylonhealth.lit.hl7_java.builders.*; import com.babylonhealth.lit.core_java.model.Unions.*; import com.babylonhealth.lit.hl7_java.model.Unions.*; import com.babylonhealth.lit.core.$bslash$div; import com.babylonhealth.lit.core_java.LitUtils; import static com.babylonhealth.lit.core_java.LitUtils.autoSuffix; import static com.babylonhealth.lit.core_java.LitUtils.guard; import static java.util.stream.Collectors.toList; public interface Claim_SupportingInfoBuilder { public Claim.SupportingInfo build(); public static Impl init(Integer sequence, CodeableConcept category) { return new Impl(sequence, category); } public static Impl builder(Integer sequence, CodeableConceptBuilder category) { return new Impl(sequence, category.build()); } public static Choice_2028408917 value(Attachment a) { return new Choice_2028408917(a); } public static Choice_2028408917 value(Boolean b) { return new Choice_2028408917(b); } public static Choice_2028408917 value(Quantity q) { return new Choice_2028408917(q); } public static Choice_2028408917 value(Reference r) { return new Choice_2028408917(r); } public static Choice_2028408917 value(String s) { return new Choice_2028408917(s); } public static ChoiceDateOrPeriod timing(FHIRDate f) { return new ChoiceDateOrPeriod(f); } public static ChoiceDateOrPeriod timing(Period p) { return new ChoiceDateOrPeriod(p); } public class Impl implements Claim_SupportingInfoBuilder { private Optional<String> id = Optional.empty(); private Optional<CodeableConcept> code = Optional.empty(); private Optional<CodeableConcept> reason = Optional.empty(); private Integer sequence; private CodeableConcept category; private Optional<Choice_2028408917> value = Optional.empty(); private Collection<Extension> extension = Collections.emptyList(); private Optional<ChoiceDateOrPeriod> timing = Optional.empty(); private Collection<Extension> modifierExtension = Collections.emptyList(); /** * Required fields for {@link Claim.SupportingInfo} * * @param sequence * @param category */ public Impl(Integer sequence, CodeableConcept category) { this.sequence = sequence; this.category = category; } /** * @param id - The logical id of the resource, as used in the URL for the resource. Once * assigned, this value never changes. */ public Claim_SupportingInfoBuilder.Impl withId(@NonNull String id) { this.id = Optional.of(id); return this; } /** @param code */ public Claim_SupportingInfoBuilder.Impl withCode(@NonNull CodeableConcept code) { this.code = Optional.of(code); return this; } public Claim_SupportingInfoBuilder.Impl withCode(@NonNull CodeableConceptBuilder code) { this.code = Optional.of(code.build()); return this; } /** @param reason */ public Claim_SupportingInfoBuilder.Impl withReason(@NonNull CodeableConcept reason) { this.reason = Optional.of(reason); return this; } public Claim_SupportingInfoBuilder.Impl withReason(@NonNull CodeableConceptBuilder reason) { this.reason = Optional.of(reason.build()); return this; } /** * @param value Field is a 'choice' field. Type should be one of Attachment, Boolean, Quantity, * Reference, String. To pass the value in, wrap with one of the * Claim_SupportingInfoBuilder.value static methods */ public Claim_SupportingInfoBuilder.Impl withValue(@NonNull Choice_2028408917 value) { this.value = Optional.of(value); return this; } /** * @param extension - May be used to represent additional information that is not part of the * basic definition of the resource. To make the use of extensions safe and manageable, * there is a strict set of governance applied to the definition and use of extensions. * Though any implementer can define an extension, there is a set of requirements that SHALL * be met as part of the definition of the extension. */ public Claim_SupportingInfoBuilder.Impl withExtension(@NonNull Extension... extension) { this.extension = Arrays.asList(extension); return this; } /** * @param extension - May be used to represent additional information that is not part of the * basic definition of the resource. To make the use of extensions safe and manageable, * there is a strict set of governance applied to the definition and use of extensions. * Though any implementer can define an extension, there is a set of requirements that SHALL * be met as part of the definition of the extension. */ public Claim_SupportingInfoBuilder.Impl withExtension( @NonNull Collection<Extension> extension) { this.extension = Collections.unmodifiableCollection(extension); return this; } public Claim_SupportingInfoBuilder.Impl withExtension(@NonNull ExtensionBuilder... extension) { this.extension = Arrays.stream(extension).map(e -> e.build()).collect(toList()); return this; } /** * @param timing Field is a 'choice' field. Type should be one of FHIRDate, Period. To pass the * value in, wrap with one of the Claim_SupportingInfoBuilder.timing static methods */ public Claim_SupportingInfoBuilder.Impl withTiming(@NonNull ChoiceDateOrPeriod timing) { this.timing = Optional.of(timing); return this; } /** * @param modifierExtension - May be used to represent additional information that is not part * of the basic definition of the resource and that modifies the understanding of the * element that contains it and/or the understanding of the containing element's * descendants. Usually modifier elements provide negation or qualification. To make the use * of extensions safe and manageable, there is a strict set of governance applied to the * definition and use of extensions. Though any implementer is allowed to define an * extension, there is a set of requirements that SHALL be met as part of the definition of * the extension. Applications processing a resource are required to check for modifier * extensions. * <p>Modifier extensions SHALL NOT change the meaning of any elements on Resource or * DomainResource (including cannot change the meaning of modifierExtension itself). */ public Claim_SupportingInfoBuilder.Impl withModifierExtension( @NonNull Extension... modifierExtension) { this.modifierExtension = Arrays.asList(modifierExtension); return this; } /** * @param modifierExtension - May be used to represent additional information that is not part * of the basic definition of the resource and that modifies the understanding of the * element that contains it and/or the understanding of the containing element's * descendants. Usually modifier elements provide negation or qualification. To make the use * of extensions safe and manageable, there is a strict set of governance applied to the * definition and use of extensions. Though any implementer is allowed to define an * extension, there is a set of requirements that SHALL be met as part of the definition of * the extension. Applications processing a resource are required to check for modifier * extensions. * <p>Modifier extensions SHALL NOT change the meaning of any elements on Resource or * DomainResource (including cannot change the meaning of modifierExtension itself). */ public Claim_SupportingInfoBuilder.Impl withModifierExtension( @NonNull Collection<Extension> modifierExtension) { this.modifierExtension = Collections.unmodifiableCollection(modifierExtension); return this; } public Claim_SupportingInfoBuilder.Impl withModifierExtension( @NonNull ExtensionBuilder... modifierExtension) { this.modifierExtension = Arrays.stream(modifierExtension).map(e -> e.build()).collect(toList()); return this; } public Claim.SupportingInfo build() { return new Claim.SupportingInfo( OptionConverters.toScala(id), OptionConverters.toScala(code), OptionConverters.toScala(reason), sequence, category, (Option) OptionConverters.toScala(value), extension.stream().collect(new LitSeqJCollector<>()), (Option) OptionConverters.toScala(timing), modifierExtension.stream().collect(new LitSeqJCollector<>()), LitUtils.emptyMetaElMap()); } } }
3e0bf1e3550d96c620499bd885a47fabafbe9287
9,566
java
Java
tests/src/test/java/alluxio/server/ft/MultiWorkerIntegrationTest.java
wheatxiong/alluxio
46f774b3b6db8e21e3ecda784869428801b8a8e7
[ "Apache-2.0", "CC0-1.0" ]
4,081
2016-02-23T06:35:40.000Z
2022-03-31T16:04:40.000Z
tests/src/test/java/alluxio/server/ft/MultiWorkerIntegrationTest.java
wheatxiong/alluxio
46f774b3b6db8e21e3ecda784869428801b8a8e7
[ "Apache-2.0", "CC0-1.0" ]
12,242
2016-02-23T05:37:45.000Z
2022-03-31T22:14:03.000Z
tests/src/test/java/alluxio/server/ft/MultiWorkerIntegrationTest.java
wheatxiong/alluxio
46f774b3b6db8e21e3ecda784869428801b8a8e7
[ "Apache-2.0", "CC0-1.0" ]
2,665
2016-02-23T05:26:57.000Z
2022-03-31T08:08:53.000Z
43.09009
98
0.744616
5,054
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.server.ft; import static org.junit.Assert.assertEquals; import alluxio.AlluxioURI; import alluxio.Constants; import alluxio.client.block.policy.BlockLocationPolicy; import alluxio.client.block.policy.options.GetWorkerOptions; import alluxio.client.file.FileSystemContext; import alluxio.conf.AlluxioConfiguration; import alluxio.conf.PropertyKey; import alluxio.client.WriteType; import alluxio.client.block.AlluxioBlockStore; import alluxio.client.block.BlockWorkerInfo; import alluxio.client.file.FileInStream; import alluxio.client.file.FileSystem; import alluxio.client.file.FileSystemTestUtils; import alluxio.client.file.URIStatus; import alluxio.client.file.options.InStreamOptions; import alluxio.client.file.options.OutStreamOptions; import alluxio.conf.ServerConfiguration; import alluxio.grpc.CreateFilePOptions; import alluxio.grpc.OpenFilePOptions; import alluxio.grpc.WritePType; import alluxio.testutils.BaseIntegrationTest; import alluxio.testutils.LocalAlluxioClusterResource; import alluxio.util.io.BufferUtils; import alluxio.wire.BlockInfo; import alluxio.wire.FileBlockInfo; import alluxio.wire.WorkerNetAddress; import com.google.common.io.ByteStreams; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.stream.StreamSupport; /** * Tests a cluster containing multiple workers. */ public final class MultiWorkerIntegrationTest extends BaseIntegrationTest { private static final int NUM_WORKERS = 4; private static final int WORKER_MEMORY_SIZE_BYTES = Constants.MB; private static final int BLOCK_SIZE_BYTES = WORKER_MEMORY_SIZE_BYTES / 2; public static class FindFirstBlockLocationPolicy implements BlockLocationPolicy { // Set this prior to sending the create request to FSM. private static WorkerNetAddress sWorkerAddress; public FindFirstBlockLocationPolicy(AlluxioConfiguration conf) { } @Override public WorkerNetAddress getWorker(GetWorkerOptions options) { return StreamSupport.stream(options.getBlockWorkerInfos().spliterator(), false) .filter(x -> x.getNetAddress().equals(sWorkerAddress)).findFirst().get() .getNetAddress(); } } @Rule public LocalAlluxioClusterResource mResource = new LocalAlluxioClusterResource.Builder() .setProperty(PropertyKey.WORKER_RAMDISK_SIZE, WORKER_MEMORY_SIZE_BYTES) .setProperty(PropertyKey.USER_BLOCK_SIZE_BYTES_DEFAULT, BLOCK_SIZE_BYTES) .setProperty(PropertyKey.USER_FILE_BUFFER_BYTES, BLOCK_SIZE_BYTES) .setNumWorkers(NUM_WORKERS) .build(); @Test @LocalAlluxioClusterResource.Config(confParams = { PropertyKey.Name.USER_BLOCK_WRITE_LOCATION_POLICY, "alluxio.client.block.policy.RoundRobinPolicy", }) public void writeLargeFile() throws Exception { int fileSize = NUM_WORKERS * WORKER_MEMORY_SIZE_BYTES; AlluxioURI file = new AlluxioURI("/test"); FileSystem fs = mResource.get().getClient(); FileSystemTestUtils.createByteFile(fs, file.getPath(), fileSize, CreateFilePOptions.newBuilder().setWriteType(WritePType.MUST_CACHE).build()); URIStatus status = fs.getStatus(file); assertEquals(100, status.getInAlluxioPercentage()); try (FileInStream inStream = fs.openFile(file)) { assertEquals(fileSize, IOUtils.toByteArray(inStream).length); } } @Test @LocalAlluxioClusterResource.Config(confParams = {PropertyKey.Name.USER_SHORT_CIRCUIT_ENABLED, "false", PropertyKey.Name.USER_BLOCK_SIZE_BYTES_DEFAULT, "16MB", PropertyKey.Name.USER_STREAMING_READER_CHUNK_SIZE_BYTES, "64KB", PropertyKey.Name.USER_BLOCK_READ_RETRY_MAX_DURATION, "1s", PropertyKey.Name.WORKER_RAMDISK_SIZE, "1GB"}) public void readRecoverFromLostWorker() throws Exception { int offset = 17 * Constants.MB; int length = 33 * Constants.MB; int total = offset + length; // creates a test file on one worker AlluxioURI filePath = new AlluxioURI("/test"); createFileOnWorker(total, filePath, mResource.get().getWorkerAddress()); FileSystem fs = mResource.get().getClient(); try (FileInStream in = fs.openFile(filePath, OpenFilePOptions.getDefaultInstance())) { byte[] buf = new byte[total]; int size = in.read(buf, 0, offset); replicateFileBlocks(filePath); mResource.get().getWorkerProcess().stop(); size += in.read(buf, offset, length); Assert.assertEquals(total, size); Assert.assertTrue(BufferUtils.equalIncreasingByteArray(offset, size, buf)); } } @Test @LocalAlluxioClusterResource.Config(confParams = {PropertyKey.Name.USER_SHORT_CIRCUIT_ENABLED, "false", PropertyKey.Name.USER_BLOCK_SIZE_BYTES_DEFAULT, "4MB", PropertyKey.Name.USER_STREAMING_READER_CHUNK_SIZE_BYTES, "64KB", PropertyKey.Name.USER_BLOCK_READ_RETRY_MAX_DURATION, "1s", PropertyKey.Name.WORKER_RAMDISK_SIZE, "1GB"}) public void readOneRecoverFromLostWorker() throws Exception { int offset = 1 * Constants.MB; int length = 5 * Constants.MB; int total = offset + length; // creates a test file on one worker AlluxioURI filePath = new AlluxioURI("/test"); FileSystem fs = mResource.get().getClient(); createFileOnWorker(total, filePath, mResource.get().getWorkerAddress()); try (FileInStream in = fs.openFile(filePath, OpenFilePOptions.getDefaultInstance())) { byte[] buf = new byte[total]; int size = in.read(buf, 0, offset); replicateFileBlocks(filePath); mResource.get().getWorkerProcess().stop(); for (int i = 0; i < length; i++) { int result = in.read(); Assert.assertEquals(result, (i + size) & 0xff); } } } @Test @LocalAlluxioClusterResource.Config(confParams = {PropertyKey.Name.USER_SHORT_CIRCUIT_ENABLED, "false", PropertyKey.Name.USER_BLOCK_SIZE_BYTES_DEFAULT, "4MB", PropertyKey.Name.USER_STREAMING_READER_CHUNK_SIZE_BYTES, "64KB", PropertyKey.Name.USER_BLOCK_READ_RETRY_MAX_DURATION, "1s", PropertyKey.Name.WORKER_RAMDISK_SIZE, "1GB"}) public void positionReadRecoverFromLostWorker() throws Exception { int offset = 1 * Constants.MB; int length = 7 * Constants.MB; int total = offset + length; // creates a test file on one worker AlluxioURI filePath = new AlluxioURI("/test"); FileSystem fs = mResource.get().getClient(); createFileOnWorker(total, filePath, mResource.get().getWorkerAddress()); try (FileInStream in = fs.openFile(filePath, OpenFilePOptions.getDefaultInstance())) { byte[] buf = new byte[length]; replicateFileBlocks(filePath); mResource.get().getWorkerProcess().stop(); int size = in.positionedRead(offset, buf, 0, length); Assert.assertEquals(length, size); Assert.assertTrue(BufferUtils.equalIncreasingByteArray(offset, size, buf)); } } private void createFileOnWorker(int total, AlluxioURI filePath, WorkerNetAddress address) throws IOException { FindFirstBlockLocationPolicy.sWorkerAddress = address; String previousPolicy = ServerConfiguration.get(PropertyKey.USER_BLOCK_WRITE_LOCATION_POLICY); // This only works because the client instance hasn't been created yet. ServerConfiguration.set(PropertyKey.USER_BLOCK_WRITE_LOCATION_POLICY, FindFirstBlockLocationPolicy.class.getName()); FileSystemTestUtils.createByteFile(mResource.get().getClient(), filePath, CreateFilePOptions.newBuilder().setWriteType(WritePType.MUST_CACHE).build(), total); ServerConfiguration.set(PropertyKey.USER_BLOCK_WRITE_LOCATION_POLICY, previousPolicy); } private void replicateFileBlocks(AlluxioURI filePath) throws Exception { FileSystemContext fsContext = FileSystemContext.create(ServerConfiguration.global()); AlluxioBlockStore store = AlluxioBlockStore.create(fsContext); URIStatus status = mResource.get().getClient().getStatus(filePath); List<FileBlockInfo> blocks = status.getFileBlockInfos(); List<BlockWorkerInfo> workers = fsContext.getCachedWorkers(); for (FileBlockInfo block : blocks) { BlockInfo blockInfo = block.getBlockInfo(); WorkerNetAddress src = blockInfo.getLocations().get(0).getWorkerAddress(); WorkerNetAddress dest = workers.stream() .filter(candidate -> !candidate.getNetAddress().equals(src)) .findFirst() .get() .getNetAddress(); try (OutputStream outStream = store.getOutStream(blockInfo.getBlockId(), blockInfo.getLength(), dest, OutStreamOptions.defaults(fsContext.getClientContext()) .setBlockSizeBytes(8 * Constants.MB).setWriteType(WriteType.MUST_CACHE))) { try (InputStream inStream = store.getInStream(blockInfo.getBlockId(), new InStreamOptions(status, ServerConfiguration.global()))) { ByteStreams.copy(inStream, outStream); } } } } }
3e0bf1f2d93cf9ba76ef273d61e85f25e12631c7
1,294
java
Java
thunx-model/src/test/java/eu/xenit/contentcloud/thunx/predicates/model/ComparisonTest.java
paulcwarren/thunx
03be10d0831def1ccd619a059aa18764c7eeba23
[ "Apache-2.0" ]
4
2021-07-22T11:45:11.000Z
2022-01-26T08:10:19.000Z
thunx-model/src/test/java/eu/xenit/contentcloud/thunx/predicates/model/ComparisonTest.java
paulcwarren/thunx
03be10d0831def1ccd619a059aa18764c7eeba23
[ "Apache-2.0" ]
5
2021-09-02T14:05:02.000Z
2022-02-21T23:14:09.000Z
thunx-model/src/test/java/eu/xenit/contentcloud/thunx/predicates/model/ComparisonTest.java
paulcwarren/thunx
03be10d0831def1ccd619a059aa18764c7eeba23
[ "Apache-2.0" ]
2
2021-07-22T11:12:59.000Z
2022-01-05T14:10:53.000Z
34.052632
117
0.7017
5,055
package eu.xenit.contentcloud.thunx.predicates.model; import static org.assertj.core.api.Assertions.assertThat; import eu.xenit.contentcloud.thunx.predicates.model.FunctionExpression.Operator; import org.junit.jupiter.api.Test; class ComparisonTest { @Test void compareEquals() { var comparison = Comparison.areEqual(Scalar.of(5), Scalar.of(3)); assertThat(comparison).isNotNull(); assertThat(comparison.getOperator()).isEqualTo(Operator.EQUALS); assertThat(comparison.getLeftTerm()).isNotNull(); assertThat(comparison.getRightTerm()).isNotNull(); } @Test void greaterOrEquals() { var comparison = Comparison.greaterOrEquals(Scalar.of(5), Scalar.of(3)); assertThat(comparison).isNotNull(); assertThat(comparison.getOperator()).isEqualTo(Operator.GREATER_THAN_OR_EQUAL_TO); assertThat(comparison.getLeftTerm()).isNotNull(); assertThat(comparison.getRightTerm()).isNotNull(); } @Test void comparison_toString() { // rule: user.clothing.coat.color == "blue" var comparison = Comparison.areEqual(SymbolicReference.parse("user.clothing.coat.color"), Scalar.of("blue")); assertThat(comparison).hasToString("EQ(user.clothing.coat.color, 'blue')"); } }
3e0bf2080ddf72150c30f797c9c0b8a76a25e6b8
3,299
java
Java
src/main/java/com/irurueta/units/SpeedUnit.java
albertoirurueta/irurueta-units
250880f1eb5b3bf137352ae61b81fb7b6013b7c5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/irurueta/units/SpeedUnit.java
albertoirurueta/irurueta-units
250880f1eb5b3bf137352ae61b81fb7b6013b7c5
[ "Apache-2.0" ]
1
2020-10-13T10:56:37.000Z
2021-12-11T12:13:41.000Z
src/main/java/com/irurueta/units/SpeedUnit.java
albertoirurueta/irurueta-units
250880f1eb5b3bf137352ae61b81fb7b6013b7c5
[ "Apache-2.0" ]
null
null
null
27.289256
75
0.612053
5,056
/* * Copyright (C) 2018 Alberto Irurueta Carro (kenaa@example.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.irurueta.units; /** * Enumerator containing recognized typical speed units. */ public enum SpeedUnit { /** * Meters per second (m/s). */ METERS_PER_SECOND, /** * Kilometers per hour (Km/h) */ KILOMETERS_PER_HOUR, /** * Kilometers per second (Km/s) */ KILOMETERS_PER_SECOND, /** * Feet per second (ft/s) */ FEET_PER_SECOND, /** * Miles per hour (mph) */ MILES_PER_HOUR; /** * Returns unit system for provided speed unit. * * @param unit speed unit to be checked. * @return unit system (metric or imperial). * @throws IllegalArgumentException if unit is null or not supported. */ public static UnitSystem getUnitSystem( final SpeedUnit unit) { if (unit == null) { throw new IllegalArgumentException(); } switch (unit) { case FEET_PER_SECOND: case MILES_PER_HOUR: return UnitSystem.IMPERIAL; case METERS_PER_SECOND: case KILOMETERS_PER_HOUR: case KILOMETERS_PER_SECOND: default: return UnitSystem.METRIC; } } /** * Gets all supported metric speed units. * * @return all supported metric speed units. */ public static SpeedUnit[] getMetricUnits() { return new SpeedUnit[]{ METERS_PER_SECOND, KILOMETERS_PER_HOUR, KILOMETERS_PER_SECOND }; } /** * Gets all supported imperial speed units. * * @return all supported imperial speed units. */ public static SpeedUnit[] getImperialUnits() { return new SpeedUnit[]{ FEET_PER_SECOND, MILES_PER_HOUR }; } /** * Indicates whether provided unit belongs to the metric unit system. * * @param unit speed unit to be checked. * @return true if unit belongs to metric unit system. * @throws IllegalArgumentException if unit is null or not supported. */ public static boolean isMetric( final SpeedUnit unit) { return getUnitSystem(unit) == UnitSystem.METRIC; } /** * Indicates whether provided unit belongs to the imperial unit system. * * @param unit speed unit to be checked. * @return true if unit belongs to imperial unit system. * @throws IllegalArgumentException if unit is null or not supported. */ public static boolean isImperial( final SpeedUnit unit) { return getUnitSystem(unit) == UnitSystem.IMPERIAL; } }
3e0bf2c9f1b2533cdfbc0289a3ac5b6c0d2db7ec
1,124
java
Java
Mage.Sets/src/mage/cards/w/WrathfulJailbreaker.java
BritCoder96/mage
64daeccdfa73f756c08514bb4b97aa889739671d
[ "MIT" ]
1
2020-11-08T18:56:04.000Z
2020-11-08T18:56:04.000Z
Mage.Sets/src/mage/cards/w/WrathfulJailbreaker.java
BritCoder96/mage
64daeccdfa73f756c08514bb4b97aa889739671d
[ "MIT" ]
28
2020-07-27T06:55:47.000Z
2022-03-28T00:02:53.000Z
Mage.Sets/src/mage/cards/w/WrathfulJailbreaker.java
BritCoder96/mage
64daeccdfa73f756c08514bb4b97aa889739671d
[ "MIT" ]
1
2019-12-23T18:58:31.000Z
2019-12-23T18:58:31.000Z
25.545455
71
0.703737
5,057
package mage.cards.w; import mage.MageInt; import mage.abilities.common.AttacksEachCombatStaticAbility; import mage.abilities.keyword.NightboundAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import java.util.UUID; /** * @author TheElk801 */ public final class WrathfulJailbreaker extends CardImpl { public WrathfulJailbreaker(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, ""); this.subtype.add(SubType.WEREWOLF); this.power = new MageInt(6); this.toughness = new MageInt(6); this.color.setRed(true); this.nightCard = true; // Wrathful Jailbreaker attacks each combat if able. this.addAbility(new AttacksEachCombatStaticAbility()); // Nightbound this.addAbility(new NightboundAbility()); } private WrathfulJailbreaker(final WrathfulJailbreaker card) { super(card); } @Override public WrathfulJailbreaker copy() { return new WrathfulJailbreaker(this); } }
3e0bf32f413a4d136840be6344c7f817e13ef470
1,131
java
Java
agouti-http/src/main/java/com/ztianzeng/agouti/http/AgoutiHttpResponse.java
zxcvbnmzsedr/agou
7fd61bb8f012639801dfbdb434a6ab30da39cd47
[ "Apache-2.0" ]
15
2019-01-29T09:11:05.000Z
2022-01-26T06:23:30.000Z
agouti-http/src/main/java/com/ztianzeng/agouti/http/AgoutiHttpResponse.java
jiegengmi/agouti
7fd61bb8f012639801dfbdb434a6ab30da39cd47
[ "Apache-2.0" ]
11
2020-03-04T22:35:14.000Z
2022-03-31T12:23:32.000Z
agouti-http/src/main/java/com/ztianzeng/agouti/http/AgoutiHttpResponse.java
jiegengmi/agouti
7fd61bb8f012639801dfbdb434a6ab30da39cd47
[ "Apache-2.0" ]
13
2019-03-10T03:11:20.000Z
2022-01-26T06:22:23.000Z
25.133333
75
0.685234
5,058
/* * Copyright 2018-2019 zTianzeng Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ztianzeng.agouti.http; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author zhaotianzeng * @version V1.0 * @date 2019-04-18 14:57 */ public class AgoutiHttpResponse { int status; Map<String, List<String>> headers; Object body; public Map<String, Object> asMap() { Map<String, Object> map = new HashMap<>(); map.put("body", body); map.put("headers", headers); map.put("status", status); return map; } }
3e0bf354106176f6bce712aee6ab68cd26798c08
20,176
java
Java
plugins/org.jkiss.dbeaver.data.gis.view/src/org/jkiss/dbeaver/ui/gis/panel/GISLeafletViewer.java
hucy2014/dbeaver
0b9fcd68ae03979794acef90290740578d2977fb
[ "Apache-2.0" ]
null
null
null
plugins/org.jkiss.dbeaver.data.gis.view/src/org/jkiss/dbeaver/ui/gis/panel/GISLeafletViewer.java
hucy2014/dbeaver
0b9fcd68ae03979794acef90290740578d2977fb
[ "Apache-2.0" ]
null
null
null
plugins/org.jkiss.dbeaver.data.gis.view/src/org/jkiss/dbeaver/ui/gis/panel/GISLeafletViewer.java
hucy2014/dbeaver
0b9fcd68ae03979794acef90290740578d2977fb
[ "Apache-2.0" ]
null
null
null
38.870906
153
0.569892
5,059
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider (kenaa@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.gis.panel; import com.vividsolutions.jts.geom.Geometry; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.ImageTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.*; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBValueFormatting; import org.jkiss.dbeaver.model.data.DBDDisplayFormat; import org.jkiss.dbeaver.model.exec.DBCException; import org.jkiss.dbeaver.model.gis.*; import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.ui.ActionUtils; import org.jkiss.dbeaver.ui.DBeaverIcons; import org.jkiss.dbeaver.ui.UIIcon; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.css.CSSUtils; import org.jkiss.dbeaver.ui.css.DBStyles; import org.jkiss.dbeaver.ui.data.IValueController; import org.jkiss.dbeaver.ui.gis.GeometryDataUtils; import org.jkiss.dbeaver.ui.gis.GeometryViewerConstants; import org.jkiss.dbeaver.ui.gis.internal.GISViewerActivator; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.IOUtils; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Map; public class GISLeafletViewer { private static final Log log = Log.getLog(GISLeafletViewer.class); private static final String PREF_RECENT_SRID_LIST = "srid.list.recent"; private static final int MAX_RECENT_SRID_SIZE = 10; private final IValueController valueController; private final Browser browser; private DBGeometry[] lastValue; private int sourceSRID; // Explicitly set SRID private int actualSourceSRID; // SRID taken from geometry value private File scriptFile; private final ToolBarManager toolBarManager; private int defaultSRID; // Target SRID used to render map private List<Integer> recentSRIDs = new ArrayList<>(); private boolean toolsVisible = true; private final Composite composite; public GISLeafletViewer(Composite parent, IValueController valueController) { this.valueController = valueController; composite = UIUtils.createPlaceholder(parent, 1); CSSUtils.setCSSClass(composite, DBStyles.COLORED_BY_CONNECTION_TYPE); browser = new Browser(composite, SWT.NONE); browser.addDisposeListener(e -> { cleanupFiles(); }); browser.setLayoutData(new GridData(GridData.FILL_BOTH)); { Composite bottomPanel = UIUtils.createPlaceholder(composite, 1);//new Composite(composite, SWT.NONE); bottomPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); CSSUtils.setCSSClass(bottomPanel, DBStyles.COLORED_BY_CONNECTION_TYPE); ToolBar bottomToolbar = new ToolBar(bottomPanel, SWT.FLAT | SWT.HORIZONTAL | SWT.RIGHT); toolBarManager = new ToolBarManager(bottomToolbar); } { String recentSRIDString = GISViewerActivator.getDefault().getPreferences().getString(PREF_RECENT_SRID_LIST); if (!CommonUtils.isEmpty(recentSRIDString)) { for (String sridStr : recentSRIDString.split(",")) { int recentSRID = CommonUtils.toInt(sridStr); if (recentSRID == 0 || recentSRID == GeometryDataUtils.getDefaultSRID() || recentSRID == GisConstants.DEFAULT_OSM_SRID) { continue; } if (!recentSRIDs.contains(recentSRID)) { recentSRIDs.add(recentSRID); } } } //recentSRIDs.sort(Integer::compareTo); } } private void setSourceSRID(int srid) { if (srid == sourceSRID) { //return; } int oldSRID = sourceSRID; this.sourceSRID = srid; try { reloadGeometryData(lastValue, true); } catch (DBException e) { DBWorkbench.getPlatformUI().showError("Setting SRID", "Can't change source SRID to " + srid, e); sourceSRID = oldSRID; } { // Save SRID to the list of recently used SRIDs if (srid != GeometryDataUtils.getDefaultSRID() && srid != GisConstants.DEFAULT_OSM_SRID && !recentSRIDs.contains(srid)) { recentSRIDs.add(srid); } if (recentSRIDs.size() > MAX_RECENT_SRID_SIZE) { recentSRIDs.remove(0); } StringBuilder sridListStr = new StringBuilder(); for (Integer sridInt : recentSRIDs) { if (sridListStr.length() > 0) sridListStr.append(","); sridListStr.append(sridInt); } GISViewerActivator.getDefault().getPreferences().setValue(PREF_RECENT_SRID_LIST, sridListStr.toString()); } } public void setGeometryData(@Nullable DBGeometry[] values) throws DBException { reloadGeometryData(values, false); } public void reloadGeometryData(@Nullable DBGeometry[] values, boolean force) throws DBException { if (!force && CommonUtils.equalObjects(lastValue, values)) { return; } int maxObjects = GISViewerActivator.getDefault().getPreferences().getInt(GeometryViewerConstants.PREF_MAX_OBJECTS_RENDER); if (maxObjects <= 0) { maxObjects = GeometryViewerConstants.DEFAULT_MAX_OBJECTS_RENDER; } if (values != null && values.length > maxObjects) { // Truncate value list DBGeometry[] truncValues = new DBGeometry[maxObjects]; System.arraycopy(values, 0, truncValues, 0, maxObjects); values = truncValues; } if (browser != null) { try { if (ArrayUtils.isEmpty(values)) { browser.setUrl("about:blank"); } else { File file = generateViewScript(values); browser.setUrl(file.toURI().toURL().toString()); } } catch (IOException e) { throw new DBException("Error generating viewer script", e); } } lastValue = values; updateToolbar(); } private File generateViewScript(DBGeometry[] values) throws IOException { if (scriptFile == null) { File tempDir = DBWorkbench.getPlatform().getTempFolder(new VoidProgressMonitor(), "gis-viewer-files"); checkIncludesExistence(tempDir); scriptFile = File.createTempFile("view", "gis.html", tempDir); } int baseSRID = 0; String[] geomValues = new String[values.length]; String[] geomTipValues = new String[values.length]; boolean showMap = false; for (int i = 0; i < values.length; i++) { DBGeometry value = values[i]; Object targetValue = value.getRawValue(); int srid = sourceSRID == 0 ? value.getSRID() : sourceSRID; if (srid == 0) { srid = GeometryDataUtils.getDefaultSRID(); } if (srid == GeometryDataUtils.getDefaultSRID()) { showMap = true; actualSourceSRID = srid; } else { Geometry geometry = value.getGeometry(); if (geometry != null) { try { GisTransformRequest request = new GisTransformRequest(geometry, srid, GisConstants.DEFAULT_SRID); GisTransformUtils.transformGisData(request); targetValue = request.getTargetValue(); srid = request.getTargetSRID(); actualSourceSRID = request.getSourceSRID(); showMap = request.isShowOnMap(); } catch (DBException e) { log.debug("Error transforming CRS", e); actualSourceSRID = srid; showMap = false; } } } if (actualSourceSRID == 0) { actualSourceSRID = GeometryDataUtils.getDefaultSRID(); } if (baseSRID == 0) { baseSRID = srid; } if (targetValue == null) { continue; } geomValues[i] = "'" + targetValue + "'"; if (CommonUtils.isEmpty(value.getProperties())) { geomTipValues[i] = "null"; } else { StringBuilder geomProps = new StringBuilder("{"); boolean first = true; for (Map.Entry<String, Object> prop : value.getProperties().entrySet()) { if (!first) geomProps.append(","); first = false; geomProps.append('"').append(prop.getKey().replace("\"", "\\\"")).append("\":\"") .append(DBValueFormatting.getDefaultValueDisplayString(prop.getValue(), DBDDisplayFormat.UI).replace("\"", "\\\"")).append("\""); } geomProps.append("}"); geomTipValues[i] = geomProps.toString(); } } if (baseSRID == 0) { if (valueController != null && valueController.getValueType() instanceof GisAttribute) { try { baseSRID = ((GisAttribute) valueController.getValueType()).getAttributeGeometrySRID(new VoidProgressMonitor()); } catch (DBCException e) { log.error(e); } } } if (baseSRID == 0) { baseSRID = GeometryDataUtils.getDefaultSRID(); } this.defaultSRID = baseSRID; String geomValuesString = String.join(",", geomValues); String geomTipValuesString = String.join(",", geomTipValues); boolean isShowMap = showMap; InputStream fis = GISViewerActivator.getDefault().getResourceStream(GISBrowserViewerConstants.VIEW_TEMPLATE_PATH); if (fis == null) { throw new IOException("View template file not found (" + GISBrowserViewerConstants.VIEW_TEMPLATE_PATH + ")"); } try (InputStreamReader isr = new InputStreamReader(fis)) { String viewTemplate = IOUtils.readToString(isr); viewTemplate = GeneralUtils.replaceVariables(viewTemplate, name -> { if (name.equals("geomValues")) { return geomValuesString; } else if (name.equals("geomTipValues")) { return String.valueOf(geomTipValuesString); } else if (name.equals("geomSRID")) { return String.valueOf(defaultSRID); } else if (name.equals("showMap")) { return String.valueOf(isShowMap); } else if (name.equals("showTools")) { return String.valueOf(toolsVisible); } return null; }); try (FileOutputStream fos = new FileOutputStream(scriptFile)) { fos.write(viewTemplate.getBytes(GeneralUtils.UTF8_CHARSET)); } } finally { ContentUtils.close(fis); } return scriptFile; } private void checkIncludesExistence(File scriptDir) throws IOException { File incFolder = new File(scriptDir, "inc"); if (!incFolder.exists()) { if (!incFolder.mkdirs()) { throw new IOException("Can't create inc folder '" + incFolder.getAbsolutePath() + "'"); } for (String fileName : GISBrowserViewerConstants.INC_FILES) { InputStream fis = GISViewerActivator.getDefault().getResourceStream(GISBrowserViewerConstants.WEB_INC_PATH + fileName); if (fis != null) { try (FileOutputStream fos = new FileOutputStream(new File(incFolder, fileName))) { try { IOUtils.copyStream(fis, fos); } catch (Exception e) { log.warn("Error copying inc file " + fileName, e); } finally { ContentUtils.close(fis); } } } } } } private void cleanupFiles() { if (scriptFile != null) { if (!scriptFile.delete()) { log.debug("Can't delete temp script file '" + scriptFile.getAbsolutePath() + "'"); } } } public Composite getBrowserComposite() { return composite; } public Browser getBrowser() { return browser; } public DBGeometry[] getCurrentValue() { return lastValue; } private int getCurrentSourceSRID() { return actualSourceSRID != 0 ? actualSourceSRID : defaultSRID != 0 ? defaultSRID : GeometryDataUtils.getDefaultSRID(); } private void updateToolbar() { toolBarManager.removeAll(); toolBarManager.add(new Action("Open in browser", DBeaverIcons.getImageDescriptor(UIIcon.BROWSER)) { @Override public void run() { UIUtils.launchProgram(scriptFile.getAbsolutePath()); } }); toolBarManager.add(new Action("Copy as picture", DBeaverIcons.getImageDescriptor(UIIcon.PICTURE)) { @Override public void run() { Image image = new Image(Display.getDefault(), browser.getBounds()); GC gc = new GC(image); try { browser.print(gc); } finally { gc.dispose(); } ImageTransfer imageTransfer = ImageTransfer.getInstance(); Clipboard clipboard = new Clipboard(Display.getCurrent()); clipboard.setContents(new Object[] {image.getImageData()}, new Transfer[]{imageTransfer}); } }); toolBarManager.add(new Action("Save as picture", DBeaverIcons.getImageDescriptor(UIIcon.PICTURE_SAVE)) { @Override public void run() { /* Image image = new Image(Display.getDefault(), browser.getBounds()); GC gc = new GC(image); try { browser.print(gc); } finally { gc.dispose(); } ImageTransfer imageTransfer = ImageTransfer.getInstance(); Clipboard clipboard = new Clipboard(Display.getCurrent()); clipboard.setContents(new Object[] {image.getImageData()}, new Transfer[]{imageTransfer}); */ } }); toolBarManager.add(new Action("Print", DBeaverIcons.getImageDescriptor(UIIcon.PRINT)) { @Override public void run() { GC gc = new GC(browser.getDisplay()); try { browser.execute("javascript:window.print();"); } finally { gc.dispose(); } } }); Action crsSelectorAction = new ChangeCRSAction(); toolBarManager.add(ActionUtils.makeActionContribution(crsSelectorAction, true)); toolBarManager.add(new Separator()); toolBarManager.add(new Action("Show/Hide controls", Action.AS_CHECK_BOX) { { setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.PALETTE)); } @Override public boolean isChecked() { return toolsVisible; } @Override public void run() { toolsVisible = !toolsVisible; updateControlsVisibility(); updateToolbar(); } }); toolBarManager.update(true); } private void updateControlsVisibility() { GC gc = new GC(browser.getDisplay()); try { browser.execute("javascript:showTools(" + toolsVisible +");"); } finally { gc.dispose(); } } private class ChangeCRSAction extends Action implements IMenuCreator { private MenuManager menuManager; public ChangeCRSAction() { super("EPSG:" + getCurrentSourceSRID(), Action.AS_DROP_DOWN_MENU); setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.CHART_LINE)); } @Override public void run() { SelectSRIDDialog manageCRSDialog = new SelectSRIDDialog( UIUtils.getActiveWorkbenchShell(), getCurrentSourceSRID()); if (manageCRSDialog.open() == IDialogConstants.OK_ID) { setSourceSRID(manageCRSDialog.getSelectedSRID()); } } @Override public IMenuCreator getMenuCreator() { return this; } @Override public void dispose() { if (menuManager != null) { menuManager.dispose(); menuManager = null; } } @Override public Menu getMenu(Control parent) { if (menuManager == null) { menuManager = new MenuManager(); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(manager -> { menuManager.add(new SetCRSAction(GeometryDataUtils.getDefaultSRID())); menuManager.add(new SetCRSAction(GisConstants.DEFAULT_OSM_SRID)); menuManager.add(new Separator()); if (!recentSRIDs.isEmpty()) { for (Integer recentSRID : recentSRIDs) { menuManager.add(new SetCRSAction(recentSRID)); } menuManager.add(new Separator()); } menuManager.add(new Action("Other ...") { @Override public void run() { ChangeCRSAction.this.run(); } }); menuManager.add(new Action("Configuration ...") { @Override public void run() { new GISViewerConfigurationDialog(composite.getShell()).open(); } }); }); } return menuManager.createContextMenu(parent); } @Override public Menu getMenu(Menu parent) { return null; } } private class SetCRSAction extends Action { private final int srid; public SetCRSAction(int srid) { super("EPSG:" + srid, AS_CHECK_BOX); this.srid = srid; } @Override public boolean isChecked() { return srid == getCurrentSourceSRID(); } @Override public void run() { setSourceSRID(srid); } } }
3e0bf437db7e72e615c5e6c29817af9f9d918efd
5,447
java
Java
core/src/main/java/com/orientechnologies/orient/core/sql/parser/OStatement.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
3,651
2015-01-02T23:58:10.000Z
2022-03-31T21:12:12.000Z
core/src/main/java/com/orientechnologies/orient/core/sql/parser/OStatement.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
6,890
2015-01-01T09:41:48.000Z
2022-03-29T08:39:49.000Z
core/src/main/java/com/orientechnologies/orient/core/sql/parser/OStatement.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
923
2015-01-01T20:40:08.000Z
2022-03-21T07:26:56.000Z
33.213415
163
0.743161
5,060
/* Generated By:JJTree: Do not edit this line. OStatement.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package com.orientechnologies.orient.core.sql.parser; import com.orientechnologies.common.exception.OException; import com.orientechnologies.common.listener.OProgressListener; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.db.ODatabase; import com.orientechnologies.orient.core.exception.OCommandExecutionException; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.OCommandSQLParsingException; import com.orientechnologies.orient.core.sql.executor.OInternalExecutionPlan; import com.orientechnologies.orient.core.sql.executor.OResult; import com.orientechnologies.orient.core.sql.executor.OResultInternal; import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery; import java.util.Map; public class OStatement extends SimpleNode { // only for internal use!!! (caching and profiling) protected String originalStatement; public static final String CUSTOM_STRICT_SQL = "strictSql"; public OStatement(int id) { super(id); } public OStatement(OrientSql p, int id) { super(p, id); } public void toString(Map<Object, Object> params, StringBuilder builder) { throw new UnsupportedOperationException( "missing implementation in " + getClass().getSimpleName()); } public void validate() throws OCommandSQLParsingException {} @Override public String toString(String prefix) { StringBuilder builder = new StringBuilder(); toString(null, builder); return builder.toString(); } public Object execute( OSQLAsynchQuery<ODocument> request, OCommandContext context, OProgressListener progressListener) { throw new UnsupportedOperationException("Unsupported command: " + getClass().getSimpleName()); } public OResultSet execute(ODatabase db, Object[] args) { return execute(db, args, true); } public OResultSet execute(ODatabase db, Object[] args, OCommandContext parentContext) { return execute(db, args, parentContext, true); } public OResultSet execute(ODatabase db, Map args) { return execute(db, args, true); } public OResultSet execute(ODatabase db, Map args, OCommandContext parentContext) { return execute(db, args, parentContext, true); } public OResultSet execute(ODatabase db, Object[] args, boolean usePlanCache) { return execute(db, args, null, usePlanCache); } public OResultSet execute( ODatabase db, Object[] args, OCommandContext parentContext, boolean usePlanCache) { throw new UnsupportedOperationException(); } public OResultSet execute(ODatabase db, Map args, boolean usePlanCache) { return execute(db, args, null, usePlanCache); } public OResultSet execute( ODatabase db, Map args, OCommandContext parentContext, boolean usePlanCache) { throw new UnsupportedOperationException(); } /** * creates an execution plan for current statement, with profiling disabled * * @param ctx the context that will be used to execute the statement * @return an execution plan */ public OInternalExecutionPlan createExecutionPlan(OCommandContext ctx) { return createExecutionPlan(ctx, false); } /** * creates an execution plan for current statement * * @param ctx the context that will be used to execute the statement * @param profile true to enable profiling, false to disable it * @return an execution plan */ public OInternalExecutionPlan createExecutionPlan(OCommandContext ctx, boolean profile) { throw new UnsupportedOperationException(); } public OInternalExecutionPlan createExecutionPlanNoCache(OCommandContext ctx, boolean profile) { return createExecutionPlan(ctx, profile); } public OStatement copy() { throw new UnsupportedOperationException("IMPLEMENT copy() ON " + getClass().getSimpleName()); } public boolean refersToParent() { throw new UnsupportedOperationException( "Implement " + getClass().getSimpleName() + ".refersToParent()"); } public boolean isIdempotent() { return false; } public static OStatement deserializeFromOResult(OResult doc) { try { OStatement result = (OStatement) Class.forName(doc.getProperty("__class")) .getConstructor(Integer.class) .newInstance(-1); result.deserialize(doc); } catch (Exception e) { throw OException.wrapException(new OCommandExecutionException(""), e); } return null; } public OResult serialize() { OResultInternal result = new OResultInternal(); result.setProperty("__class", getClass().getName()); return result; } public void deserialize(OResult fromResult) { throw new UnsupportedOperationException(); } public boolean executinPlanCanBeCached() { return false; } public String getOriginalStatement() { return originalStatement; } public void setOriginalStatement(String originalStatement) { this.originalStatement = originalStatement; } } /* JavaCC - OriginalChecksum=589c4dcc8287f430e46d8eb12b0412c5 (do not edit this line) */
3e0bf46e6902db301935726fe1a62e22fe63c45c
2,431
java
Java
src/main/java/com/xudod/gen_code/common/HttpSend.java
xudod/gencode_ddd
9f02e9539d0955c7f1888a5ffbe3074183e413a2
[ "Apache-2.0" ]
1
2020-06-14T01:54:47.000Z
2020-06-14T01:54:47.000Z
src/main/java/com/xudod/gen_code/common/HttpSend.java
xudod/gencode_ddd
9f02e9539d0955c7f1888a5ffbe3074183e413a2
[ "Apache-2.0" ]
3
2021-05-11T17:24:45.000Z
2022-02-27T06:34:52.000Z
src/main/java/com/xudod/gen_code/common/HttpSend.java
xudod/gencode_ddd
9f02e9539d0955c7f1888a5ffbe3074183e413a2
[ "Apache-2.0" ]
null
null
null
27.942529
86
0.730152
5,061
package com.xudod.gen_code.common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpSend { public static String sendHttpsGet(String urlStr) throws IOException { // 1. 获取访问地址URL URL url = new URL(urlStr); // 2. 创建HttpURLConnection对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /* 3. 设置请求参数等 */ // 请求方式 connection.setRequestMethod("GET"); // 超时时间 connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // 设置是否输出 connection.setDoOutput(true); // 设置是否读入 connection.setDoInput(true); // 设置是否使用缓存 connection.setUseCaches(false); // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向 connection.setInstanceFollowRedirects(true); // 连接 connection.connect(); return getReturn(connection); } public static String sendHttpsPost(String urlStr, String params) throws IOException { // 1. 获取访问地址URL URL url = new URL(urlStr); // 2. 创建HttpURLConnection对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /* 3. 设置请求参数等 */ // 请求方式 connection.setRequestMethod("POST"); // 设置使用标准编码格式编码参数的名-值对 connection.setRequestProperty("Content-Type","application/json"); // 超时时间 connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // 设置是否输出 connection.setDoOutput(true); // 设置是否读入 connection.setDoInput(true); // 设置是否使用缓存 connection.setUseCaches(false); // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向 connection.setInstanceFollowRedirects(true); // 连接 connection.connect(); OutputStream out = connection.getOutputStream(); out.write(params.getBytes()); out.flush(); out.close(); return getReturn(connection); } /* 请求url获取返回的内容 */ private static String getReturn(HttpURLConnection connection) throws IOException { StringBuffer buffer = new StringBuffer(); // 将返回的输入流转换成字符串 try ( InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); ) { String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } String result = buffer.toString(); return result; } } }
3e0bf4ea7f42846795716d84eb8f2417d60b1924
4,510
java
Java
src/main/java/com/moople/gitpals/MainApplication/controller/api/SearchAPIController.java
danmoop/Gitpals
d36f12477a77750fa7c64839057e0f750091763e
[ "MIT" ]
73
2018-03-18T12:19:56.000Z
2021-09-14T09:19:20.000Z
src/main/java/com/moople/gitpals/MainApplication/controller/api/SearchAPIController.java
danmoop/Gitpals
d36f12477a77750fa7c64839057e0f750091763e
[ "MIT" ]
3
2018-03-12T13:24:52.000Z
2020-12-18T22:10:57.000Z
src/main/java/com/moople/gitpals/MainApplication/controller/api/SearchAPIController.java
danmoop/Gitpals
d36f12477a77750fa7c64839057e0f750091763e
[ "MIT" ]
2
2020-09-10T01:06:18.000Z
2021-01-04T13:01:54.000Z
40.267857
107
0.71796
5,062
package com.moople.gitpals.MainApplication.controller.api; import com.moople.gitpals.MainApplication.model.ForumPost; import com.moople.gitpals.MainApplication.model.Project; import com.moople.gitpals.MainApplication.model.User; import com.moople.gitpals.MainApplication.service.ForumService; import com.moople.gitpals.MainApplication.service.ProjectService; import com.moople.gitpals.MainApplication.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; @RestController @CrossOrigin @RequestMapping("/api/search") public class SearchAPIController { @Autowired private UserService userService; @Autowired private ProjectService projectService; @Autowired private ForumService forumService; /** * This function returns a list of users whose username matches the input * * @param username is a username we pass in path * @return list of users whose username match the one we pass */ @GetMapping(value = "/matchUsersByUsername/{username}", produces = MediaType.APPLICATION_JSON_VALUE) public List<User> matchUsersByUsername(@PathVariable String username) { return userService.matchUsersByUsername(username); } /** * This function returns a list of project which title matches the input * * @param title is a project name we pass in path * @return list of projects whose title match the one we pass */ @GetMapping(value = "/matchProjectsByProjectName/{title}", produces = MediaType.APPLICATION_JSON_VALUE) public List<Project> matchProjectsByProjectName(@PathVariable String title) { return projectService.matchProjectsByProjectTitle(title); } /** * This request finds all the forum posts whose titles match target value * * @return list of posts, whose titles match the target value sent by the user */ @GetMapping(value = "/matchForumPostsByTitle/{title}", produces = MediaType.APPLICATION_JSON_VALUE) public List<ForumPost> matchForumPostsByTitle(@PathVariable String title) { return forumService.matchForumPostsByTitle(title); } /** * This function returns all the posts from a particular user * * @return all the posts from the user specified */ @GetMapping(value = "/matchForumPostsByAuthor/{author}", produces = MediaType.APPLICATION_JSON_VALUE) public List<ForumPost> matchForumPostsByAuthor(@PathVariable String author) { return forumService.findByAuthor(author); } /** * This function returns a list of projects with technologies specified by a user * * @param technologies is a list of technologies project should contain * @return list of projects whose technologies match the user's input */ @PostMapping(value = "/matchProjectsByTechnologies", produces = MediaType.APPLICATION_JSON_VALUE) public List<Project> matchProjectsByTechnologies(@RequestBody List<String> technologies) { return projectService.matchProjectsByTechnologies(technologies); } /** * This function returns a list of projects with roles specified by a user * * @param roles is a list of required roles project should contain * @return list of projects whose required roles match the user's input */ @PostMapping(value = "/matchProjectsByRoles", produces = MediaType.APPLICATION_JSON_VALUE) public List<Project> matchProjectsByRoles(@RequestBody List<String> roles) { return projectService.matchProjectsByRoles(roles); } /** * This function returns a list of users that know skills specified by whoever calls this request * * @param skills is a list of skills (like java/c/python) that users can know * @return list of users that know all the skills given in a body of this request */ @PostMapping(value = "/matchUsersBySkills", produces = MediaType.APPLICATION_JSON_VALUE) public List<User> matchUsersBySkills(@RequestBody List<String> skills) { return userService.findBySkillList(skills) .stream() .map(username -> userService.findByUsername(username)) .peek(user -> { user.setDialogs(null); user.setNotifications(null); }) .collect(Collectors.toList()); } }
3e0bf502541911f69b383e4b3a21a3d7e07b8f10
303
java
Java
seata/lagou_parent/lagou_storage/src/main/java/com/lagou/storage/mapper/StorageMapper.java
langkemaoxin/spring-cloud-demo
df9d2c363e19ef59ee3bad23b52a3a9d9522b16d
[ "Apache-2.0" ]
1
2021-01-28T08:49:13.000Z
2021-01-28T08:49:13.000Z
seata/lagou_parent/lagou_storage/src/main/java/com/lagou/storage/mapper/StorageMapper.java
langkemaoxin/spring-cloud-demo
df9d2c363e19ef59ee3bad23b52a3a9d9522b16d
[ "Apache-2.0" ]
null
null
null
seata/lagou_parent/lagou_storage/src/main/java/com/lagou/storage/mapper/StorageMapper.java
langkemaoxin/spring-cloud-demo
df9d2c363e19ef59ee3bad23b52a3a9d9522b16d
[ "Apache-2.0" ]
1
2021-04-13T07:37:06.000Z
2021-04-13T07:37:06.000Z
27.545455
60
0.838284
5,063
package com.lagou.storage.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.lagou.storage.entity.Storage; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; @Repository public interface StorageMapper extends BaseMapper<Storage> { }
3e0bf51205c47069922df15bb09addda8a07a449
4,117
java
Java
src/test/java/com/github/texxel/data/ClassMapTest.java
Texxel/DataSerialiser
e2efea3e7ab0b004e3135d4ac86eb3cffb513980
[ "MIT" ]
null
null
null
src/test/java/com/github/texxel/data/ClassMapTest.java
Texxel/DataSerialiser
e2efea3e7ab0b004e3135d4ac86eb3cffb513980
[ "MIT" ]
null
null
null
src/test/java/com/github/texxel/data/ClassMapTest.java
Texxel/DataSerialiser
e2efea3e7ab0b004e3135d4ac86eb3cffb513980
[ "MIT" ]
null
null
null
30.051095
66
0.584892
5,064
package com.github.texxel.data; import com.github.texxel.data.ClassMap; import com.github.texxel.data.PData; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ClassMapTest { // Create some classes to test with // // I:Alive I:Falloffable // | | // C:Animal I:Thing I:Mountable // +--------+-------+ | | // C:Moose C:Squid C:Horse ---> I:Rideable // interface Alive {}; interface Falloffable {}; interface Mountable extends Falloffable {}; interface Thing {}; interface Rideable extends Thing {}; class Animal implements Alive {} class Squid extends Animal {}; class Moose extends Animal {}; class Horse extends Animal implements Rideable, Mountable {}; @Test public void testDirectPut() { ClassMap<Animal, String> map = new ClassMap<>(); map.put( Squid.class, "squid" ); map.put( Moose.class, "moose" ); assertEquals( "squid", map.get( Squid.class ) ); assertEquals( "moose", map.get( Moose.class ) ); } @Test public void testClassHeirachicalPut() { ClassMap<Animal, String> map = new ClassMap<>(); map.put( Squid.class, "squid" ); map.put( Animal.class, "animal" ); assertEquals( "squid", map.get( Squid.class ) ); assertEquals( "animal", map.get( Moose.class ) ); } @Test public void testInterfaceHeirachicalPut() { ClassMap<Object, String> map = new ClassMap<>(); map.put( Squid.class, "squid" ); map.put( Rideable.class, "rideable" ); assertEquals( "squid", map.get( Squid.class ) ); assertEquals( "rideable", map.get( Horse.class ) ); } @Test public void testWalksInterfacesOfInterfaces() { ClassMap<Object, String> map = new ClassMap<>(); map.put(Falloffable.class, "fall"); assertEquals("fall", map.get(Horse.class)); } @Test public void testWalksInterfacesOfParentClasses() { ClassMap<Object, String> map = new ClassMap<>(); map.put(Alive.class, "alive"); assertEquals("alive", map.get(Horse.class)); } @Test public void testClassHierarchyBeforeInterface() { ClassMap<Object, String> map = new ClassMap<>(); map.put( Rideable.class, "rideable" ); map.put( Animal.class, "animal" ); assertEquals( "animal", map.get( Horse.class ) ); } @Test public void testDirectInterfaceBeforeHighInterface() { ClassMap<Object, String> map = new ClassMap<>(); map.put(Rideable.class, "rideable" ); map.put(Thing.class, "thing"); assertEquals("rideable", map.get(Horse.class)); } @Test public void testChildInterfacesBeforeParentInterfaces() { ClassMap<Object, String> map = new ClassMap<>(); map.put(Falloffable.class, "fall" ); map.put(Thing.class, "thing"); assertEquals("thing", map.get(Horse.class)); } @Test public void testClassInterfacesBeforeParentClassInterfaces() { ClassMap<Object, String> map = new ClassMap<>(); map.put(Falloffable.class, "fall" ); map.put(Alive.class, "alive"); assertEquals("fall", map.get(Horse.class)); } @Test public void testArraysAreObjectsToo() { ClassMap<Object, String> map = new ClassMap<>(); map.put(Object.class, "object"); map.put(Object[].class, "object[]"); map.put(int[][].class, "int[][]"); // maybe int[][] should go to int[] ? assertEquals("object", map.get(float[][].class)); assertEquals("int[][]", map.get(int[][].class)); assertEquals("object", map.get(int[].class)); } @Test public void testEnumsExtendEnums() { ClassMap<Object, String> map = new ClassMap<>(); map.put(Object.class, "object"); map.put(Enum.class, "enum"); Class testEnum = PData.Type.class; assertEquals("enum", map.get(testEnum)); } }
3e0bf54a0044dda0460f28e8eec2a9246b99b02f
1,241
java
Java
src/main/java/com/github/alex1304/ultimategdbot/gdplugin/command/LevelCommand.java
ultimategdbot/ultimategdbot-gd-plugin
2ddad6a68201d3d7e582dece481850efe94a350e
[ "MIT" ]
3
2020-07-24T21:38:27.000Z
2020-08-14T23:34:31.000Z
src/main/java/com/github/alex1304/ultimategdbot/gdplugin/command/LevelCommand.java
ultimategdbot/ultimategdbot-gd-plugin
2ddad6a68201d3d7e582dece481850efe94a350e
[ "MIT" ]
5
2020-04-10T17:39:33.000Z
2020-07-02T16:51:49.000Z
src/main/java/com/github/alex1304/ultimategdbot/gdplugin/command/LevelCommand.java
ultimategdbot/ultimategdbot-gd-plugin
2ddad6a68201d3d7e582dece481850efe94a350e
[ "MIT" ]
1
2020-07-29T06:53:25.000Z
2020-07-29T06:53:25.000Z
37.606061
105
0.792103
5,065
package com.github.alex1304.ultimategdbot.gdplugin.command; import com.github.alex1304.jdash.util.LevelSearchFilters; import com.github.alex1304.ultimategdbot.api.command.CommandFailedException; import com.github.alex1304.ultimategdbot.api.command.Context; import com.github.alex1304.ultimategdbot.api.command.annotated.CommandAction; import com.github.alex1304.ultimategdbot.api.command.annotated.CommandDescriptor; import com.github.alex1304.ultimategdbot.api.command.annotated.CommandDoc; import com.github.alex1304.ultimategdbot.api.service.Root; import com.github.alex1304.ultimategdbot.gdplugin.GDService; import reactor.core.publisher.Mono; @CommandDescriptor( aliases = "level", shortDescription = "tr:GDStrings/level_desc" ) public final class LevelCommand { @Root private GDService gd; @CommandAction @CommandDoc("tr:GDStrings/level_run") public Mono<Void> run(Context ctx, String query) { if (!query.matches("[a-zA-Z0-9 _-]+")) { return Mono.error(new CommandFailedException(ctx.translate("GDStrings", "error_invalid_characters"))); } return gd.level().searchAndSend(ctx, ctx.translate("GDStrings", "search_results", query), () -> gd.client().searchLevels(query, LevelSearchFilters.create(), 0)); } }
3e0bf55a6f07d4ad3337349e855487f61ac88fbc
2,013
java
Java
base-adapter/src/main/java/com/king/base/adapter/HolderAdapter.java
LeeQiuuu/BBWY
310aa49e69454d44d50d1ddb240429f4e8fdc4c1
[ "Apache-2.0" ]
278
2016-09-18T06:36:49.000Z
2022-02-10T16:34:24.000Z
base-adapter/src/main/java/com/king/base/adapter/HolderAdapter.java
LeeQiuuu/BBWY
310aa49e69454d44d50d1ddb240429f4e8fdc4c1
[ "Apache-2.0" ]
2
2017-11-28T06:42:50.000Z
2018-08-29T03:05:29.000Z
base-adapter/src/main/java/com/king/base/adapter/HolderAdapter.java
LeeQiuuu/BBWY
310aa49e69454d44d50d1ddb240429f4e8fdc4c1
[ "Apache-2.0" ]
50
2017-04-13T08:13:08.000Z
2020-11-22T16:44:23.000Z
24.597561
108
0.723847
5,066
/* Copyright © 2015, 2016 Jenly Yu <a href="mailto:dycjh@example.com">Jenly</a> 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.king.base.adapter; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * * 通用适配器(适合一些常规的适配器) * @author Jenly <a href="mailto:dycjh@example.com">Jenly</a> * * @param <T> * 实体对象 * @param <H> * ViewHolder */ public abstract class HolderAdapter<T,H> extends AbstractAdapter<T>{ public HolderAdapter(Context context, List<T> listData) { super(context, listData); } @Override public View getView(int position, View convertView, ViewGroup parent) { H holder; T item = getListData().get(position); if(convertView==null){ convertView = buildConvertView(getLayoutInflater(),item,position,parent); holder = buildHolder(convertView,item,position); convertView.setTag(holder); }else{ holder = (H)convertView.getTag(); } bindViewDatas(holder,item,position); return convertView; } /** * 建立convertView * @param layoutInflater * @return */ public abstract View buildConvertView(LayoutInflater layoutInflater,T item,int position, ViewGroup parent); /** * 建立视图Holder * @param convertView * @return */ public abstract H buildHolder(View convertView,T item,int position); /** * 绑定数据 * @param holder * @param item * @param position */ public abstract void bindViewDatas(H holder,T item,int position); }
3e0bf63569f7ac2b0ac59f74a0f78faf37af17b9
27,541
java
Java
services/src/atdd-staging/src/main/java/org/openkilda/atdd/staging/steps/FlowCrudSteps.java
mikalstill/open-kilda
39a2e4fd94d96a0dfa5456d22acfbdd8f3d88b34
[ "Apache-2.0" ]
null
null
null
services/src/atdd-staging/src/main/java/org/openkilda/atdd/staging/steps/FlowCrudSteps.java
mikalstill/open-kilda
39a2e4fd94d96a0dfa5456d22acfbdd8f3d88b34
[ "Apache-2.0" ]
null
null
null
services/src/atdd-staging/src/main/java/org/openkilda/atdd/staging/steps/FlowCrudSteps.java
mikalstill/open-kilda
39a2e4fd94d96a0dfa5456d22acfbdd8f3d88b34
[ "Apache-2.0" ]
null
null
null
45.749169
119
0.658437
5,067
/* Copyright 2018 Telstra Open Source * * 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.openkilda.atdd.staging.steps; import static com.nitorcreations.Matchers.reflectEquals; import static java.lang.String.format; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.everyItem; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isIn; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; 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.assertTrue; import static org.junit.Assert.fail; import static org.openkilda.model.MeterId.MAX_SYSTEM_RULE_METER_ID; import org.openkilda.atdd.staging.helpers.FlowSet; import org.openkilda.atdd.staging.helpers.TopologyUnderTest; import org.openkilda.atdd.staging.service.flowmanager.FlowManager; import org.openkilda.messaging.info.event.IslInfoData; import org.openkilda.messaging.model.FlowDto; import org.openkilda.messaging.model.FlowPairDto; import org.openkilda.messaging.payload.flow.FlowIdStatusPayload; import org.openkilda.messaging.payload.flow.FlowPathPayload; import org.openkilda.messaging.payload.flow.FlowPayload; import org.openkilda.messaging.payload.flow.FlowState; import org.openkilda.messaging.payload.flow.PathNodePayload; import org.openkilda.model.SwitchId; import org.openkilda.northbound.dto.flows.FlowValidationDto; import org.openkilda.testing.model.topology.TopologyDefinition; import org.openkilda.testing.model.topology.TopologyDefinition.Switch; import org.openkilda.testing.service.database.Database; import org.openkilda.testing.service.floodlight.FloodlightService; import org.openkilda.testing.service.floodlight.model.MeterEntry; import org.openkilda.testing.service.floodlight.model.MetersEntriesMap; import org.openkilda.testing.service.northbound.NorthboundService; import org.openkilda.testing.service.traffexam.FlowNotApplicableException; import org.openkilda.testing.service.traffexam.OperationalException; import org.openkilda.testing.service.traffexam.TraffExamService; import org.openkilda.testing.service.traffexam.model.Exam; import org.openkilda.testing.service.traffexam.model.ExamReport; import org.openkilda.testing.service.traffexam.model.ExamResources; import org.openkilda.testing.tools.FlowTrafficExamBuilder; import org.openkilda.testing.tools.SoftAssertions; import com.google.common.collect.ContiguousSet; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.Range; import com.google.common.collect.RangeSet; import com.google.common.collect.TreeRangeSet; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import cucumber.api.java8.En; import lombok.extern.slf4j.Slf4j; import net.jodah.failsafe.Failsafe; import net.jodah.failsafe.RetryPolicy; import org.apache.commons.collections4.ListValuedMap; import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Lazy; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; @Slf4j public class FlowCrudSteps implements En { @Autowired private NorthboundService northboundService; @Autowired private FloodlightService floodlightService; @Autowired private Database db; @Autowired private TopologyDefinition topologyDefinition; @Autowired @Lazy private TraffExamService traffExam; @Autowired private FlowManager flowManager; @Autowired @Qualifier("topologyUnderTest") private TopologyUnderTest topologyUnderTest; private Set<FlowPayload> flows; private Set<FlowPathPayload> flowPaths = new HashSet<>(); private FlowPayload flowResponse; @Given("^flows defined over active switches in the reference topology$") public void defineFlowsOverActiveSwitches() { flows = flowManager.allActiveSwitchesFlows(); } @Given("Create (\\d+) flows? with A Switch used and at least (\\d+) alternate paths? between source and " + "destination switch and (\\d+) bandwidth") public void flowsWithAlternatePaths(int flowsAmount, int alternatePaths, int bw) { Map<FlowPayload, List<TopologyDefinition.Isl>> flowIsls = topologyUnderTest.getFlowIsls(); flowIsls.putAll(flowManager.createFlowsWithASwitch(flowsAmount, alternatePaths, bw)); //temporary resaving flows before refactoring all methods to work with topologyUnderTest flows = flowIsls.keySet(); flows.forEach(flow -> flowPaths.add(northboundService.getFlowPath(flow.getId()))); } @And("^flow paths? (?:is|are) changed") public void flowPathIsChanged() { Set<FlowPathPayload> actualFlowPaths = new HashSet<>(); flows.forEach(flow -> actualFlowPaths.add(northboundService.getFlowPath(flow.getId()))); assertThat(actualFlowPaths, everyItem(not(isIn(flowPaths)))); // Save actual flow paths flowPaths = actualFlowPaths; } @And("^flow paths? (?:is|are) unchanged") public void flowPathIsUnchanged() { Set<FlowPathPayload> actualFlowPaths = new HashSet<>(); flows.forEach(flow -> actualFlowPaths.add(northboundService.getFlowPath(flow.getId()))); assertThat(actualFlowPaths, everyItem(isIn(flowPaths))); } @And("Create defined flows?") public void createFlows() { eachFlowIsCreatedAndStoredInTopologyEngine(); eachFlowIsInUpState(); } @And("^each flow has unique flow_id$") public void setUniqueFlowIdToEachFlow() { flows.forEach(flow -> flow.setId(format("%s-%s", flow.getId(), UUID.randomUUID().toString()))); } @And("^(?:each )?flow has max bandwidth set to (\\d+)$") public void setBandwidthToEachFlow(int bandwidth) { flows.forEach(flow -> flow.setMaximumBandwidth(bandwidth)); } @When("^initialize creation of given flows$") public void creationRequestForEachFlowIsSuccessful() { for (FlowPayload flow : flows) { FlowPayload result = northboundService.addFlow(flow); assertThat(format("A flow creation request for '%s' failed.", flow.getId()), result, reflectEquals(flow, "lastUpdated", "status")); assertThat(format("Flow status for '%s' was not set to '%s'. Received status: '%s'", flow.getId(), FlowState.IN_PROGRESS, result.getStatus()), result.getStatus(), equalTo(FlowState.IN_PROGRESS.toString())); assertThat(format("The flow '%s' is missing lastUpdated field", flow.getId()), result, hasProperty("lastUpdated", notNullValue())); } } @Then("^each flow is created and stored in TopologyEngine$") public void eachFlowIsCreatedAndStoredInTopologyEngine() { List<FlowDto> expextedFlows = flows.stream() .map(flow -> new FlowDto(flow.getId(), flow.getMaximumBandwidth(), flow.isIgnoreBandwidth(), flow.isPeriodicPings(), 0, flow.getDescription(), null, flow.getSource().getDatapath(), flow.getDestination().getDatapath(), flow.getSource().getPortNumber(), flow.getDestination().getPortNumber(), flow.getSource().getVlanId(), flow.getDestination().getVlanId(), 0, 0, null, null)) .collect(toList()); for (FlowDto expectedFlow : expextedFlows) { FlowPairDto<FlowDto, FlowDto> flowPair = Failsafe.with(retryPolicy() .retryWhen(null)) .get(() -> db.getFlow(expectedFlow.getFlowId())); assertNotNull(format("The flow '%s' is missing in TopologyEngine.", expectedFlow.getFlowId()), flowPair); assertThat(format("The flow '%s' in TopologyEngine is different from defined.", expectedFlow.getFlowId()), flowPair.getLeft(), is(equalTo(expectedFlow))); } } @And("^(?:each )?flow is in UP state$") public void eachFlowIsInUpState() { eachFlowIsUp(flows); } private void eachFlowIsUp(Set<FlowPayload> flows) { for (FlowPayload flow : flows) { FlowIdStatusPayload status = Failsafe.with(retryPolicy() .retryIf(p -> p == null || ((FlowIdStatusPayload) p).getStatus() != FlowState.UP)) .get(() -> northboundService.getFlowStatus(flow.getId())); assertNotNull(format("The flow status for '%s' can't be retrived from Northbound.", flow.getId()), status); assertThat(format("The flow '%s' in Northbound is different from defined.", flow.getId()), status, hasProperty("id", equalTo(flow.getId()))); assertThat(format("The flow '%s' has wrong status in Northbound.", flow.getId()), status, hasProperty("status", equalTo(FlowState.UP))); } } @And("^each flow can be read from Northbound$") public void eachFlowCanBeReadFromNorthbound() { for (FlowPayload flow : flows) { FlowPayload result = northboundService.getFlow(flow.getId()); assertNotNull(format("The flow '%s' is missing in Northbound.", flow.getId()), result); assertEquals(format("The flow '%s' in Northbound is different from defined.", flow.getId()), flow.getId(), result.getId()); } } @And("^(?:each )?flow is valid per Northbound validation$") public void eachFlowIsValid() { flows.forEach(flow -> { List<FlowValidationDto> validations = northboundService.validateFlow(flow.getId()); validations.forEach(flowValidation -> { assertEquals(flow.getId(), flowValidation.getFlowId()); assertTrue(format("The flow '%s' has discrepancies: %s", flow.getId(), flowValidation.getDiscrepancies()), flowValidation.getDiscrepancies().isEmpty()); assertTrue(format("The flow '%s' didn't pass validation.", flow.getId()), flowValidation.getAsExpected()); }); }); } @And("^(?:each )?flow has traffic going with bandwidth not less than (\\d+) and not greater than (\\d+)$") public void eachFlowHasTrafficGoingWithBandwidthNotLessThan(int bandwidthLowLimit, int bandwidthHighLimit) throws Throwable { List<Exam> examsInProgress = buildAndStartTraffExams(); SoftAssertions softAssertions = new SoftAssertions(); List<String> issues = new ArrayList<>(); for (Exam exam : examsInProgress) { String flowId = exam.getFlow().getId(); ExamReport report = traffExam.waitExam(exam); softAssertions.checkThat(format("The flow %s had errors: %s", flowId, report.getErrors()), report.hasError(), is(false)); softAssertions.checkThat(format("The flow %s had no traffic.", flowId), report.hasTraffic(), is(true)); softAssertions.checkThat(format("The flow %s had unexpected bandwidth: %s", flowId, report.getBandwidth()), report.getBandwidth().getKbps() > bandwidthLowLimit && report.getBandwidth().getKbps() < bandwidthHighLimit, is(true)); } softAssertions.verify(); } @And("^each flow has no traffic$") public void eachFlowHasNoTraffic() { List<Exam> examsInProgress = buildAndStartTraffExams(); List<ExamReport> hasTraffic = examsInProgress.stream() .map(exam -> traffExam.waitExam(exam)) .filter(ExamReport::hasTraffic) .collect(toList()); assertThat("Detected unexpected traffic.", hasTraffic, empty()); } private List<Exam> buildAndStartTraffExams() { FlowTrafficExamBuilder examBuilder = new FlowTrafficExamBuilder(topologyDefinition, traffExam); List<Exam> result = flows.stream() .flatMap(flow -> { try { // Instruct TraffGen to produce traffic with maximum bandwidth. return Stream.of(examBuilder.buildExam(flow, 0)); } catch (FlowNotApplicableException ex) { log.info("Skip traffic exam. {}", ex.getMessage()); return Stream.empty(); } }) .peek(exam -> { try { ExamResources resources = traffExam.startExam(exam); exam.setResources(resources); } catch (OperationalException ex) { log.error("Unable to start traffic exam for {}.", exam.getFlow(), ex); fail(ex.getMessage()); } }) .collect(toList()); log.info("{} of {} flow's traffic examination have been started", result.size(), flows.size()); return result; } @Then("^each flow can be updated with (\\d+) max bandwidth( and new vlan)?$") public void eachFlowCanBeUpdatedWithBandwidth(int bandwidth, String newVlanStr) { final boolean newVlan = newVlanStr != null; for (FlowPayload flow : flows) { flow.setMaximumBandwidth(bandwidth); if (newVlan) { flow.getDestination().setVlanId(getAllowedVlan(flows, flow.getDestination().getSwitchDpId())); flow.getSource().setVlanId(getAllowedVlan(flows, flow.getSource().getSwitchDpId())); } FlowPayload result = northboundService.updateFlow(flow.getId(), flow); assertThat(format("A flow update request for '%s' failed.", flow.getId()), result, reflectEquals(flow, "lastUpdated", "status")); } } private int getAllowedVlan(Set<FlowPayload> flows, SwitchId switchDpId) { RangeSet<Integer> allocatedVlans = TreeRangeSet.create(); flows.forEach(f -> { allocatedVlans.add(Range.singleton(f.getSource().getVlanId())); allocatedVlans.add(Range.singleton(f.getDestination().getVlanId())); }); RangeSet<Integer> availableVlansRange = TreeRangeSet.create(); Switch theSwitch = topologyDefinition.getSwitches().stream() .filter(sw -> sw.getDpId().equals(switchDpId)).findFirst().get(); theSwitch.getOutPorts().forEach(port -> availableVlansRange.addAll(port.getVlanRange())); availableVlansRange.removeAll(allocatedVlans); return availableVlansRange.asRanges().stream() .flatMap(range -> ContiguousSet.create(range, DiscreteDomain.integers()).stream()) .findFirst().get(); } @And("^each flow has meters installed with (\\d+) max bandwidth$") public void eachFlowHasMetersInstalledWithBandwidth(long bandwidth) { for (FlowPayload flow : flows) { FlowPairDto<FlowDto, FlowDto> flowPair = db.getFlow(flow.getId()); try { MetersEntriesMap forwardSwitchMeters = floodlightService .getMeters(flowPair.getLeft().getSourceSwitch()); int forwardMeterId = flowPair.getLeft().getMeterId(); assertThat(forwardSwitchMeters, hasKey(forwardMeterId)); MeterEntry forwardMeter = forwardSwitchMeters.get(forwardMeterId); assertThat(forwardMeter.getEntries(), contains(hasProperty("rate", equalTo(bandwidth)))); MetersEntriesMap reverseSwitchMeters = floodlightService .getMeters(flowPair.getRight().getSourceSwitch()); int reverseMeterId = flowPair.getRight().getMeterId(); assertThat(reverseSwitchMeters, hasKey(reverseMeterId)); MeterEntry reverseMeter = reverseSwitchMeters.get(reverseMeterId); assertThat(reverseMeter.getEntries(), contains(hasProperty("rate", equalTo(bandwidth)))); } catch (UnsupportedOperationException ex) { //TODO: a workaround for not implemented dumpMeters on OF_12 switches. log.warn("Switch doesn't support dumping of meters. {}", ex.getMessage()); } } } @And("^all active switches have no excessive meters installed$") public void noExcessiveMetersInstalledOnActiveSwitches() { ListValuedMap<SwitchId, Integer> switchMeters = new ArrayListValuedHashMap<>(); for (FlowPayload flow : flows) { FlowPairDto<FlowDto, FlowDto> flowPair = db.getFlow(flow.getId()); if (flowPair != null) { switchMeters.put(flowPair.getLeft().getSourceSwitch(), flowPair.getLeft().getMeterId()); switchMeters.put(flowPair.getRight().getSourceSwitch(), flowPair.getRight().getMeterId()); } } List<TopologyDefinition.Switch> switches = topologyDefinition.getActiveSwitches(); switches.forEach(sw -> { List<Integer> expectedMeters = switchMeters.get(sw.getDpId()); try { List<Integer> actualMeters = floodlightService.getMeters(sw.getDpId()).values().stream() .map(MeterEntry::getMeterId) .filter(meterId -> meterId > MAX_SYSTEM_RULE_METER_ID) .collect(toList()); if (!expectedMeters.isEmpty() || !actualMeters.isEmpty()) { assertThat(format("Meters of switch %s don't match expected.", sw), actualMeters, containsInAnyOrder(expectedMeters)); } } catch (UnsupportedOperationException ex) { //TODO: a workaround for not implemented dumpMeters on OF_12 switches. log.warn("Switch doesn't support dumping of meters. {}", ex.getMessage()); } }); } @Then("^each flow can be deleted$") public void eachFlowCanBeDeleted() { List<String> deletedFlowIds = new ArrayList<>(); for (FlowPayload flow : flows) { FlowPayload result = northboundService.deleteFlow(flow.getId()); if (result != null) { deletedFlowIds.add(result.getId()); } } assertThat("Deleted flows from Northbound don't match expected", deletedFlowIds, containsInAnyOrder( flows.stream().map(flow -> equalTo(flow.getId())).collect(toList()))); } @And("^each flow can not be read from Northbound$") public void eachFlowCanNotBeReadFromNorthbound() { for (FlowPayload flow : flows) { FlowPayload result = Failsafe.with(retryPolicy() .abortWhen(null) .retryIf(Objects::nonNull)) .get(() -> northboundService.getFlow(flow.getId())); assertNull(format("The flow '%s' exists.", flow.getId()), result); } } @And("^each flow can not be read from TopologyEngine$") public void eachFlowCanNotBeReadFromTopologyEngine() { for (FlowPayload flow : flows) { FlowPairDto<FlowDto, FlowDto> result = Failsafe.with(retryPolicy() .abortWhen(null) .retryIf(Objects::nonNull)) .get(() -> db.getFlow(flow.getId())); assertNull(format("The flow '%s' exists.", flow.getId()), result); } } @And("^create flow between '(.*)' and '(.*)' and alias it as '(.*)'$") public void createFlowBetween(String srcAlias, String dstAlias, String flowAlias) { Switch srcSwitch = topologyUnderTest.getAliasedObject(srcAlias); Switch dstSwitch = topologyUnderTest.getAliasedObject(dstAlias); FlowPayload flow = new FlowSet().buildWithAnyPortsInUniqueVlan("auto" + getTimestamp(), srcSwitch, dstSwitch, 1000); northboundService.addFlow(flow); topologyUnderTest.addAlias(flowAlias, flow); } @And("^'(.*)' flow is in UP state$") public void flowIsUp(String flowAlias) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); eachFlowIsUp(Collections.singleton(flow)); } @When("^request all switch meters for switch '(.*)' and alias results as '(.*)'$") public void requestMeters(String switchAlias, String meterAlias) { Switch sw = topologyUnderTest.getAliasedObject(switchAlias); topologyUnderTest.addAlias(meterAlias, floodlightService.getMeters(sw.getDpId())); } @And("^select first meter of '(.*)' and alias it as '(.*)'$") public void selectFirstMeter(String metersAlias, String newMeterAlias) { MetersEntriesMap meters = topologyUnderTest.getAliasedObject(metersAlias); Entry<Integer, MeterEntry> firstMeter = meters.entrySet().iterator().next(); topologyUnderTest.addAlias(newMeterAlias, firstMeter); } @Then("^meters '(.*)' does not have '(.*)'$") public void doesNotHaveMeter(String metersAlias, String meterAlias) { MetersEntriesMap meters = topologyUnderTest.getAliasedObject(metersAlias); Entry<Integer, MeterEntry> meter = topologyUnderTest.getAliasedObject(meterAlias); assertFalse(meters.containsKey(meter.getKey())); } private RetryPolicy retryPolicy() { return new RetryPolicy() .withDelay(2, TimeUnit.SECONDS) .withMaxRetries(10); } @Given("^random flow aliased as '(.*)'$") public void randomFlowAliasedAsFlow(String flowAlias) { topologyUnderTest.addAlias(flowAlias, flowManager.randomFlow()); } @And("^change bandwidth of (.*) flow to (\\d+)$") public void changeBandwidthOfFlow(String flowAlias, int newBw) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); flow.setMaximumBandwidth(newBw); } @When("^change bandwidth of (.*) flow to '(.*)'$") public void changeBandwidthOfFlow(String flowAlias, String bwAlias) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); long bw = topologyUnderTest.getAliasedObject(bwAlias); flow.setMaximumBandwidth(bw); } @And("^create flow '(.*)'$") public void createFlow(String flowAlias) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); flowResponse = northboundService.addFlow(flow); } @And("^get available bandwidth and maximum speed for flow (.*) and alias them as '(.*)' " + "and '(.*)' respectively$") public void getAvailableBandwidthAndSpeed(String flowAlias, String bwAlias, String speedAlias) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); List<PathNodePayload> flowPath = northboundService.getFlowPath(flow.getId()).getForwardPath(); List<IslInfoData> allLinks = northboundService.getAllLinks(); long minBw = Long.MAX_VALUE; long minSpeed = Long.MAX_VALUE; /* Take flow path and all links. Now for every pair in flow path find a link. Take minimum available bandwidth and minimum available speed from those links (flow's speed and left bandwidth depends on the weakest isl) */ for (int i = 1; i < flowPath.size(); i++) { PathNodePayload from = flowPath.get(i - 1); PathNodePayload to = flowPath.get(i); IslInfoData isl = allLinks.stream().filter(link -> link.getSource().getSwitchId().equals(from.getSwitchId()) && link.getDestination().getSwitchId().equals(to.getSwitchId())) .findFirst().get(); minBw = Math.min(isl.getAvailableBandwidth(), minBw); minSpeed = Math.min(isl.getSpeed(), minSpeed); } topologyUnderTest.addAlias(bwAlias, minBw); topologyUnderTest.addAlias(speedAlias, minSpeed); } @And("^update flow (.*)$") public void updateFlow(String flowAlias) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); flowResponse = northboundService.updateFlow(flow.getId(), flow); } @When("^get info about flow (.*)$") public void getInfoAboutFlow(String flowAlias) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); flowResponse = northboundService.getFlow(flow.getId()); } @Then("^response flow has bandwidth equal to '(.*)'$") public void responseFlowHasBandwidth(String bwAlias) { long expectedBw = topologyUnderTest.getAliasedObject(bwAlias); assertThat(flowResponse.getMaximumBandwidth(), equalTo(expectedBw)); } @Then("^response flow has bandwidth equal to (\\d+)$") public void responseFlowHasBandwidth(long expectedBw) { assertThat(flowResponse.getMaximumBandwidth(), equalTo(expectedBw)); } @And("^delete flow (.*)$") public void deleteFlow(String flowAlias) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); northboundService.deleteFlow(flow.getId()); } @And("^get path of '(.*)' and alias it as '(.*)'$") public void getPathAndAlias(String flowAlias, String pathAlias) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); topologyUnderTest.addAlias(pathAlias, northboundService.getFlowPath(flow.getId())); } @And("^(.*) flow's path equals to '(.*)'$") public void verifyFlowPath(String flowAlias, String pathAlias) { FlowPayload flow = topologyUnderTest.getAliasedObject(flowAlias); FlowPathPayload expectedPath = topologyUnderTest.getAliasedObject(pathAlias); FlowPathPayload actualPath = northboundService.getFlowPath(flow.getId()); assertThat(actualPath, equalTo(expectedPath)); } private String getTimestamp() { return new SimpleDateFormat("ddMMMHHmm", Locale.US).format(new Date()); } }
3e0bf64b2ca6eb89eedf405fe789e87adbbe1faf
1,139
java
Java
tests/junit-functional/org/jgroups/tests/LongMessageTest.java
savitha-ping/JGroups
af9eb7541b1c9e16118373fbe4866d4e85f80a15
[ "Apache-2.0" ]
704
2015-01-07T16:18:33.000Z
2022-03-29T14:09:28.000Z
tests/junit-functional/org/jgroups/tests/LongMessageTest.java
savitha-ping/JGroups
af9eb7541b1c9e16118373fbe4866d4e85f80a15
[ "Apache-2.0" ]
147
2015-01-07T18:32:53.000Z
2022-03-21T07:52:37.000Z
tests/junit-functional/org/jgroups/tests/LongMessageTest.java
savitha-ping/JGroups
af9eb7541b1c9e16118373fbe4866d4e85f80a15
[ "Apache-2.0" ]
371
2015-01-05T23:16:40.000Z
2022-03-26T09:19:00.000Z
24.76087
55
0.624232
5,068
package org.jgroups.tests; import org.jgroups.Global; import org.jgroups.LongMessage; import org.testng.annotations.Test; /** * @author Bela Ban * @since 5.0.0 */ @Test(groups=Global.FUNCTIONAL) public class LongMessageTest extends MessageTestBase { public void testConstructor() { LongMessage msg=new LongMessage().setValue(50); System.out.println("msg = " + msg); assert msg.getValue() == 50; } public void testGetUndefinedValue() { LongMessage msg=new LongMessage(); long val=msg.getValue(); assert val == 0; } public void testGetObject() { LongMessage msg=new LongMessage().setValue(22); long val=msg.getObject(); assert val == 22; } public void testSetObject() { LongMessage msg=new LongMessage(); msg.setObject(22); assert msg.getValue() == 22; msg.setObject(23L); assert msg.getValue() == 23; assert msg.getObject() instanceof Long; } public void testSize() throws Exception { LongMessage msg=new LongMessage().setValue(22); _testSize(msg); } }
3e0bf6ad4eb1fd82ba65be5b900870771c20791d
2,166
java
Java
app/src/main/java/com/num/model/WarmupExperiment.java
msp8955/MySpeedTest
fff21a9dddc33db12ea230cc23967c52e2893d98
[ "Apache-1.1" ]
3
2015-10-13T18:36:05.000Z
2022-03-30T09:10:13.000Z
app/src/main/java/com/num/model/WarmupExperiment.java
noise-lab/myspeedtest
4793b1dd5f4f458ef09ac6224e9228728050f30a
[ "Apache-1.1" ]
6
2015-10-12T22:59:06.000Z
2016-03-08T16:53:11.000Z
app/src/main/java/com/num/model/WarmupExperiment.java
noise-lab/myspeedtest
4793b1dd5f4f458ef09ac6224e9228728050f30a
[ "Apache-1.1" ]
1
2016-01-29T00:04:16.000Z
2016-01-29T00:04:16.000Z
28.12987
64
0.578024
5,069
package com.num.model; import com.num.Constants; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class WarmupExperiment implements BaseModel { private double lowest, highest, timeGap; private String version; private Address address; private int totalCount; private List<WarmupPing> sequence; public WarmupExperiment() { lowest = -1; highest = -1; version = Constants.PING_SEQUENCE_VERSION; timeGap = Constants.PING_WARMUP_SEQUENCE_GAP; address = Constants.PING_SEQUENCE_ADDRESS; totalCount = Constants.PING_SEQUENCE_TOTAL; sequence = new ArrayList<>(); } @Override public JSONObject toJSON() { JSONObject json = new JSONObject(); try { json.putOpt("highest", highest); json.putOpt("lowest", lowest); json.putOpt("version", version); json.putOpt("total_count", totalCount); json.putOpt("time_gap", timeGap); json.putOpt("dstip", address.getIp()); JSONArray array = new JSONArray(); for(WarmupPing ping : sequence) { array.put(ping.toJSON()); } json.putOpt("sequence", array); } catch (JSONException e) { e.printStackTrace(); } return json; } private class WarmupPing implements BaseModel { private double value; private int sequenceCount; private double period; public WarmupPing(double value, int count, double gap) { this.value = value; this.sequenceCount = count; this.period = (count-1)*gap; } @Override public JSONObject toJSON() { JSONObject json = new JSONObject(); try { json.putOpt("value", value); json.putOpt("sequence", sequence); json.putOpt("period", period); } catch (JSONException e) { e.printStackTrace(); } return json; } } }
3e0bf70ce3885ea0780706952269f98a3fbe2444
1,583
java
Java
jena-core/src/main/java/org/apache/jena/shared/ConfigException.java
costas80/jena
7d146c5c265196c9c2740948fd1cd22b21aca033
[ "Apache-2.0" ]
null
null
null
jena-core/src/main/java/org/apache/jena/shared/ConfigException.java
costas80/jena
7d146c5c265196c9c2740948fd1cd22b21aca033
[ "Apache-2.0" ]
1
2022-02-05T16:08:39.000Z
2022-02-05T16:08:41.000Z
jena-core/src/main/java/org/apache/jena/shared/ConfigException.java
costas80/jena
7d146c5c265196c9c2740948fd1cd22b21aca033
[ "Apache-2.0" ]
1
2020-06-11T12:26:06.000Z
2020-06-11T12:26:06.000Z
26.830508
75
0.677195
5,070
/* * 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.jena.shared; /** * An Exception indicating that Jena is not working * because it is not correctly configured. For example, * the classpath is not set up correctly for the desired * functionality. */ public class ConfigException extends JenaException { /** * @param message */ public ConfigException(String message) { super(message); } /** * */ public ConfigException() { super(); } /** * @param cause */ public ConfigException(Throwable cause) { super("Jena not correctly configured: ",cause); } /** * @param message * @param cause */ public ConfigException(String message, Throwable cause) { super(message, cause); } }
3e0bf75f97e68a717a828409b194c8ab8d152193
396
java
Java
mirs-framework-elasticsearch/src/main/java/com/github/mirs/banxiaoxiao/framework/elasticsearch/enable/ElasticsearchEnable.java
git-jinlong/mirs-framework
6bb197718926ec99144d41cc43b90cc5b3d3157e
[ "Apache-2.0" ]
1
2021-07-23T08:28:32.000Z
2021-07-23T08:28:32.000Z
mirs-framework-elasticsearch/src/main/java/com/github/mirs/banxiaoxiao/framework/elasticsearch/enable/ElasticsearchEnable.java
git-jinlong/mirs-framework
6bb197718926ec99144d41cc43b90cc5b3d3157e
[ "Apache-2.0" ]
null
null
null
mirs-framework-elasticsearch/src/main/java/com/github/mirs/banxiaoxiao/framework/elasticsearch/enable/ElasticsearchEnable.java
git-jinlong/mirs-framework
6bb197718926ec99144d41cc43b90cc5b3d3157e
[ "Apache-2.0" ]
null
null
null
20.842105
73
0.790404
5,071
package com.github.mirs.banxiaoxiao.framework.elasticsearch.enable; import com.github.mirs.banxiaoxiao.framework.core.boot.EnableInitializer; import java.lang.annotation.*; /** * @author: bc * @date: 2021-07-16 16:36 **/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @EnableInitializer(ElasticsearchInitializer.class) public @interface ElasticsearchEnable { }
3e0bf86afd5a4a6a61e7df7ffc8ea4c84d198cfb
397
java
Java
src/com/pugetworks/utils/GoogleAnalytics.java
paulin/whereuat
679cf35c2f2a1070ce5e504f8900d6229ba4f5f5
[ "Apache-2.0" ]
null
null
null
src/com/pugetworks/utils/GoogleAnalytics.java
paulin/whereuat
679cf35c2f2a1070ce5e504f8900d6229ba4f5f5
[ "Apache-2.0" ]
null
null
null
src/com/pugetworks/utils/GoogleAnalytics.java
paulin/whereuat
679cf35c2f2a1070ce5e504f8900d6229ba4f5f5
[ "Apache-2.0" ]
null
null
null
24.8125
72
0.7733
5,072
package com.pugetworks.utils; /** * Codes for Google Analytics * @author paulin42 * */ public class GoogleAnalytics { public static final String GA_KEY = "UA-41257127-1"; public static final String LOCATION_MESSAGE_SENT = "LOCATION_MSG_SENT"; public static final String RESPONSE_MESSAGE_SENT = "RESPONSE_MSG_SENT"; public static final String INVITE_MESSAGE_SENT = "INVITE_MSG_SENT"; }
3e0bf8825b99772c6c50504abd0e5f17ace74594
2,230
java
Java
coeus-impl/src/main/java/org/kuali/coeus/common/framework/auth/docperm/DocumentAccess.java
sonamuthu/kc
3b8beb0dd656df32e155ace4711083be42ddd4fd
[ "ECL-2.0" ]
null
null
null
coeus-impl/src/main/java/org/kuali/coeus/common/framework/auth/docperm/DocumentAccess.java
sonamuthu/kc
3b8beb0dd656df32e155ace4711083be42ddd4fd
[ "ECL-2.0" ]
null
null
null
coeus-impl/src/main/java/org/kuali/coeus/common/framework/auth/docperm/DocumentAccess.java
sonamuthu/kc
3b8beb0dd656df32e155ace4711083be42ddd4fd
[ "ECL-2.0" ]
null
null
null
25.340909
111
0.699552
5,073
package org.kuali.coeus.common.framework.auth.docperm; import org.kuali.coeus.sys.api.model.DocumentNumbered; import org.kuali.coeus.sys.api.model.Identifiable; import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase; import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity(name = "DOCUMENT_ACCESS") public class DocumentAccess extends KcPersistableBusinessObjectBase implements Identifiable, DocumentNumbered { @PortableSequenceGenerator(name = "SEQ_DOCUMENT_ACCESS_ID") @GeneratedValue(generator = "SEQ_DOCUMENT_ACCESS_ID") @Id @Column(name = "DOC_ACCESS_ID") private String id; @Column(name = "DOC_HDR_ID", length=14) private String documentNumber; @Column(name = "PRNCPL_ID") private String principalId; @Column(name = "ROLE_NM") private String roleName; @Column(name = "NMSPC_CD") private String namespaceCode; public DocumentAccess() { super(); } public DocumentAccess(String documentNumber, String principalId, String roleName, String namespaceCode) { this.documentNumber = documentNumber; this.principalId = principalId; this.roleName = roleName; this.namespaceCode = namespaceCode; } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getDocumentNumber() { return documentNumber; } public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } public String getPrincipalId() { return principalId; } public void setPrincipalId(String principalId) { this.principalId = principalId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getNamespaceCode() { return namespaceCode; } public void setNamespaceCode(String namespaceCode) { this.namespaceCode = namespaceCode; } }
3e0bf98f56ce02963fca4c8089a27b5765a622d3
1,381
java
Java
BBS/src/com/ekunt/bbs/utils/DB.java
E-Kunt/Struts2-Demos
5009b095242ffedade557be13d64888503054d07
[ "Apache-2.0" ]
1
2016-09-07T07:36:50.000Z
2016-09-07T07:36:50.000Z
BBS/src/com/ekunt/bbs/utils/DB.java
E-Kunt/Struts2-Demos
5009b095242ffedade557be13d64888503054d07
[ "Apache-2.0" ]
null
null
null
BBS/src/com/ekunt/bbs/utils/DB.java
E-Kunt/Struts2-Demos
5009b095242ffedade557be13d64888503054d07
[ "Apache-2.0" ]
null
null
null
20.308824
86
0.618392
5,074
package com.ekunt.bbs.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DB { public static Connection createConn() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs", "root", "tiger"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static PreparedStatement prepare(Connection conn, String sql) { PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); } catch (SQLException e) { e.printStackTrace(); } return ps; } public static void close(Connection conn) { try { if(conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } public static void close(Statement stmt) { try { if(stmt != null) { stmt.close(); stmt = null; } } catch (SQLException e) { e.printStackTrace(); } } public static void close(ResultSet rs) { try { if(rs != null) { rs.close(); rs = null; } } catch (SQLException e) { e.printStackTrace(); } } }
3e0bf9933a4a39b0028b9004295d941488e0ca7e
269
java
Java
brein-api-library-android/src/test/java/com/brein/TestAllSuite.java
Breinify/brein-api-library-android
5250b789ae59f7b46923bc0335fedd46e4386618
[ "MIT" ]
2
2017-03-23T00:23:02.000Z
2017-04-19T10:14:43.000Z
brein-api-library-android/src/test/java/com/brein/TestAllSuite.java
Breinify/brein-api-library-android
5250b789ae59f7b46923bc0335fedd46e4386618
[ "MIT" ]
null
null
null
brein-api-library-android/src/test/java/com/brein/TestAllSuite.java
Breinify/brein-api-library-android
5250b789ae59f7b46923bc0335fedd46e4386618
[ "MIT" ]
1
2019-11-06T05:44:06.000Z
2019-11-06T05:44:06.000Z
16.8125
37
0.710037
5,075
package com.brein; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * Test suite for all java api tests */ @RunWith(Suite.class) @Suite.SuiteClasses({ TestSuite.class, TestIntegrationSuite.class }) public class TestAllSuite { }
3e0bfafeba19f42449c456780520374ce6fa24bc
4,923
java
Java
src/main/java/com/mastercard/developer/loyalty_airport_client/model/Lounge.java
Mastercard/loyalty-airport-ref
61e1db3c5ec9550f505de70e81c355d3b0302435
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mastercard/developer/loyalty_airport_client/model/Lounge.java
Mastercard/loyalty-airport-ref
61e1db3c5ec9550f505de70e81c355d3b0302435
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mastercard/developer/loyalty_airport_client/model/Lounge.java
Mastercard/loyalty-airport-ref
61e1db3c5ec9550f505de70e81c355d3b0302435
[ "Apache-2.0" ]
1
2020-07-17T21:25:53.000Z
2020-07-17T21:25:53.000Z
30.9625
464
0.7283
5,076
/* * Copyright (c) 2019 Mastercard 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. * * Loyalty Airport Experience API * The Loyalty Airport Lounge APIs offers cardholders, via their issuers, the ability to access the Mastercard Airport Lounge service through this digital channel. Cardholders can search for airport lounges, get airport lounge details, access airport lounges via their personalized Digital Membership Card, and access their lounge history. These APIs can be used to build a rich, interactive airport experience within the issuer's existing mobile application. * * OpenAPI spec version: 1.0.0 * Contact: kenaa@example.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.mastercard.developer.loyalty_airport_client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Lounge */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-12-26T11:53:43.013-06:00[America/Chicago]") public class Lounge { public static final String SERIALIZED_NAME_LOUNGE_CODE = "loungeCode"; @SerializedName(SERIALIZED_NAME_LOUNGE_CODE) private String loungeCode; public static final String SERIALIZED_NAME_LOUNGE_NAME = "loungeName"; @SerializedName(SERIALIZED_NAME_LOUNGE_NAME) private String loungeName; public static final String SERIALIZED_NAME_AIRPORT_TERMINAL = "airportTerminal"; @SerializedName(SERIALIZED_NAME_AIRPORT_TERMINAL) private String airportTerminal; public Lounge loungeCode(String loungeCode) { this.loungeCode = loungeCode; return this; } /** * Airport lounge unique code * @return loungeCode **/ @ApiModelProperty(example = "LGW1", value = "Airport lounge unique code") public String getLoungeCode() { return loungeCode; } public void setLoungeCode(String loungeCode) { this.loungeCode = loungeCode; } public Lounge loungeName(String loungeName) { this.loungeName = loungeName; return this; } /** * Airport lounge name * @return loungeName **/ @ApiModelProperty(example = "No1 Lounge, Gatwick", value = "Airport lounge name") public String getLoungeName() { return loungeName; } public void setLoungeName(String loungeName) { this.loungeName = loungeName; } public Lounge airportTerminal(String airportTerminal) { this.airportTerminal = airportTerminal; return this; } /** * Airport lounge terminal location * @return airportTerminal **/ @ApiModelProperty(example = "3", value = "Airport lounge terminal location") public String getAirportTerminal() { return airportTerminal; } public void setAirportTerminal(String airportTerminal) { this.airportTerminal = airportTerminal; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Lounge lounge = (Lounge) o; return Objects.equals(this.loungeCode, lounge.loungeCode) && Objects.equals(this.loungeName, lounge.loungeName) && Objects.equals(this.airportTerminal, lounge.airportTerminal); } @Override public int hashCode() { return Objects.hash(loungeCode, loungeName, airportTerminal); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Lounge {\n"); sb.append(" loungeCode: ").append(toIndentedString(loungeCode)).append("\n"); sb.append(" loungeName: ").append(toIndentedString(loungeName)).append("\n"); sb.append(" airportTerminal: ").append(toIndentedString(airportTerminal)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e0bfbf504e3dbd0a744fb1f53b9b87741e8f1cb
1,595
java
Java
java/test/java/com/google/mr4c/serialize/bean/metadata/MetadataListBeanTest.java
icarazob/mr4c
fe367fac1d634fe5cea477e14ba39d0df630255f
[ "Apache-2.0" ]
1,062
2015-02-18T18:26:33.000Z
2022-03-23T10:16:07.000Z
java/test/java/com/google/mr4c/serialize/bean/metadata/MetadataListBeanTest.java
icarazob/mr4c
fe367fac1d634fe5cea477e14ba39d0df630255f
[ "Apache-2.0" ]
22
2015-02-24T03:09:18.000Z
2020-07-04T05:53:10.000Z
java/test/java/com/google/mr4c/serialize/bean/metadata/MetadataListBeanTest.java
icarazob/mr4c
fe367fac1d634fe5cea477e14ba39d0df630255f
[ "Apache-2.0" ]
315
2015-02-18T22:29:52.000Z
2022-01-24T06:29:40.000Z
27.982456
76
0.739185
5,077
/** * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mr4c.serialize.bean.metadata; import com.google.mr4c.metadata.MetadataArray; import com.google.mr4c.metadata.MetadataField; import com.google.mr4c.metadata.MetadataList; import com.google.mr4c.metadata.PrimitiveType; import java.util.Arrays; import org.junit.*; import static org.junit.Assert.*; public class MetadataListBeanTest { private MetadataList m_list; @Before public void setUp() { buildList(); } private void buildList() { m_list = new MetadataList( Arrays.asList( new MetadataField(new Integer(234), PrimitiveType.INTEGER), new MetadataField(new Double(88.77), PrimitiveType.DOUBLE), new MetadataField("yo yo yo", PrimitiveType.STRING), new MetadataArray(Arrays.asList(33,44,55), PrimitiveType.INTEGER) ) ); } @Test public void testList() { MetadataListBean bean = MetadataListBean.instance(m_list); MetadataList list2 = bean.toMetadataElement(); assertEquals(m_list, list2); } }
3e0bfc62787b4a991536e2ae041226222321c16b
1,454
java
Java
XXE-testbed/src/testcases/CWE611_XML_External_Entities_XMLReader/CWE611_XML_External_Entities__XMLReader_05.java
Berger-and-Molland/xxe-autofix-tool
dda05c0436fc1bc1dfa4242f32c5dde18307665d
[ "MIT" ]
null
null
null
XXE-testbed/src/testcases/CWE611_XML_External_Entities_XMLReader/CWE611_XML_External_Entities__XMLReader_05.java
Berger-and-Molland/xxe-autofix-tool
dda05c0436fc1bc1dfa4242f32c5dde18307665d
[ "MIT" ]
null
null
null
XXE-testbed/src/testcases/CWE611_XML_External_Entities_XMLReader/CWE611_XML_External_Entities__XMLReader_05.java
Berger-and-Molland/xxe-autofix-tool
dda05c0436fc1bc1dfa4242f32c5dde18307665d
[ "MIT" ]
null
null
null
32.311111
101
0.69945
5,078
package testcases.CWE611_XML_External_Entities_XMLReader; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; public class CWE611_XML_External_Entities__XMLReader_05{ private boolean privateTrue = true; public String bad(String filePath) throws Throwable { if(privateTrue) { InputSource inputSource = new InputSource(filePath); XMLReader reader = XMLReaderFactory.createXMLReader(); PrintHandler handler = new PrintHandler(); reader.setContentHandler(handler); reader.parse(inputSource); return handler.getRes(); } return null; } public String good(String filePath) throws Throwable { if(privateTrue) { InputSource inputSource = new InputSource(filePath); XMLReader reader = XMLReaderFactory.createXMLReader(); PrintHandler handler = new PrintHandler(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setContentHandler(handler); reader.parse(inputSource); return handler.getRes(); } return null; } }
3e0bfd2deacaeaeb07c089feec902c679b6b0722
288
java
Java
src/main/java/com/example/customer/customerService/Exceptions/AddressNotExists.java
germansanz93/customer-service
6b54f20fd27c0b56b92f40ef61e06478635a96d6
[ "MIT" ]
null
null
null
src/main/java/com/example/customer/customerService/Exceptions/AddressNotExists.java
germansanz93/customer-service
6b54f20fd27c0b56b92f40ef61e06478635a96d6
[ "MIT" ]
null
null
null
src/main/java/com/example/customer/customerService/Exceptions/AddressNotExists.java
germansanz93/customer-service
6b54f20fd27c0b56b92f40ef61e06478635a96d6
[ "MIT" ]
3
2021-11-26T17:08:17.000Z
2021-11-26T17:33:04.000Z
22.153846
56
0.739583
5,079
package com.example.customer.customerService.Exceptions; import lombok.extern.slf4j.Slf4j; @Slf4j public class AddressNotExists extends RuntimeException{ public AddressNotExists(String mensaje ) { super (mensaje); log.error("Address not exist exceptions"); } }
3e0bfeac98c0a938636f63ba8cd9e3f6758d7624
715
java
Java
app/src/main/java/kj/dph/lib/retrofit/downlaod/DownLoadListener/DownloadInterceptor.java
dphAndroid/dph_kjj
d9239fbfe3d82e5db3ce504ff82a287e45fcbbdb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/kj/dph/lib/retrofit/downlaod/DownLoadListener/DownloadInterceptor.java
dphAndroid/dph_kjj
d9239fbfe3d82e5db3ce504ff82a287e45fcbbdb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/kj/dph/lib/retrofit/downlaod/DownLoadListener/DownloadInterceptor.java
dphAndroid/dph_kjj
d9239fbfe3d82e5db3ce504ff82a287e45fcbbdb
[ "Apache-2.0" ]
null
null
null
24.655172
82
0.71049
5,080
package kj.dph.lib.retrofit.downlaod.DownLoadListener; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.Response; /** * 成功回调处理 * Created by WZG on 2016/10/20. */ public class DownloadInterceptor implements Interceptor { private DownloadProgressListener listener; public DownloadInterceptor(DownloadProgressListener listener) { this.listener = listener; } @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new DownloadResponseBody(originalResponse.body(), listener)) .build(); } }
3e0bff01084d5d7584dd9bb7ec50816a36485c31
422
java
Java
src/main/java/de/melsicon/kafka/sensors/serialization/confluent/SpecificSerdesFactory.java
melsicon/kafka-sensors
db8d23d0bcf1d7511125921d7ddee748957c0ce1
[ "Apache-2.0" ]
8
2019-11-21T08:27:08.000Z
2021-05-23T06:50:03.000Z
src/main/java/de/melsicon/kafka/sensors/serialization/confluent/SpecificSerdesFactory.java
melsicon/kafka-sensors
db8d23d0bcf1d7511125921d7ddee748957c0ce1
[ "Apache-2.0" ]
1
2021-08-25T05:11:09.000Z
2021-08-25T05:11:09.000Z
src/main/java/de/melsicon/kafka/sensors/serialization/confluent/SpecificSerdesFactory.java
melsicon/kafka-sensors
db8d23d0bcf1d7511125921d7ddee748957c0ce1
[ "Apache-2.0" ]
1
2020-02-03T12:55:50.000Z
2020-02-03T12:55:50.000Z
35.166667
88
0.85782
5,081
package de.melsicon.kafka.sensors.serialization.confluent; import dagger.assisted.AssistedFactory; import de.melsicon.kafka.sensors.avro.SensorState; import de.melsicon.kafka.sensors.avro.SensorStateWithDuration; import de.melsicon.kafka.sensors.serde.SensorStateMapper; @AssistedFactory public interface SpecificSerdesFactory { SpecificSerdes create(SensorStateMapper<SensorState, SensorStateWithDuration> mapper); }
3e0bff5948a1a78630e68e16d14b10ec188bf551
6,808
java
Java
C Locker/src/com/ccs/lockscreen/data/DataRSS.java
astoncheah/CLocker
9ad6b298263a366847dcf9fb9329a456c8f72597
[ "MIT" ]
1
2018-05-31T03:19:45.000Z
2018-05-31T03:19:45.000Z
C Locker/src/com/ccs/lockscreen/data/DataRSS.java
astoncheah/CLocker
9ad6b298263a366847dcf9fb9329a456c8f72597
[ "MIT" ]
null
null
null
C Locker/src/com/ccs/lockscreen/data/DataRSS.java
astoncheah/CLocker
9ad6b298263a366847dcf9fb9329a456c8f72597
[ "MIT" ]
null
null
null
35.092784
214
0.548619
5,082
package com.ccs.lockscreen.data; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class DataRSS extends SQLiteOpenHelper{ private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "rssManager"; private static final String TABLE_RSS = "rssTable"; private static final String KEY_ID = "id"; private static final String KEY_SOURCE = "rssSource"; private static final String KEY_TITLE = "rssTitle"; private static final String KEY_PUB_DATE = "rssPubDate"; private static final String KEY_DESC = "rssDesc"; private static final String KEY_CONTENT = "rssContent"; private static final String KEY_CATEGORY = "rssCategory"; private static final String KEY_LINK = "rssLink"; public DataRSS(Context context){ super(context,DATABASE_NAME,null,DATABASE_VERSION); } public void addRSS(InfoRSS rss){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_SOURCE,rss.getRssSource()); values.put(KEY_TITLE,rss.getRssTitle()); values.put(KEY_PUB_DATE,rss.getRssPubDate()); values.put(KEY_DESC,rss.getRssDesc()); values.put(KEY_CONTENT,rss.getRssContent()); values.put(KEY_CATEGORY,rss.getRssCategory()); values.put(KEY_LINK,rss.getRssLink()); db.insert(TABLE_RSS,null,values); db.close(); } @Override public void onCreate(SQLiteDatabase db){ String CREATE_CONTACTS_TABLE = "CREATE TABLE "+TABLE_RSS+ "("+ KEY_ID+" INTEGER PRIMARY KEY,"+ KEY_SOURCE+" TEXT,"+ KEY_TITLE+" TEXT,"+ KEY_PUB_DATE+" TEXT,"+ KEY_DESC+" TEXT,"+ KEY_CONTENT+" TEXT,"+ KEY_CATEGORY+" TEXT,"+ KEY_LINK+" TEXT"+ ")"; db.execSQL(CREATE_CONTACTS_TABLE); } public InfoRSS getRSS(int id){ SQLiteDatabase db = null; Cursor cursor = null; InfoRSS rss = null; try{ db = this.getReadableDatabase(); String[] columns = new String[]{KEY_ID,KEY_SOURCE,KEY_TITLE,KEY_PUB_DATE,KEY_DESC,KEY_CONTENT,KEY_CATEGORY,KEY_LINK}; String[] selection = new String[]{String.valueOf(id)}; cursor = db.query(TABLE_RSS,columns,KEY_ID+"=?",selection,null,null,null,null); try{ if(cursor!=null){ cursor.moveToFirst(); }else{ return null; } rss = new InfoRSS(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getString(7)); }finally{ if(db!=null){ db.close(); db = null; } cursor.close(); } return rss; }catch(Exception e){ if(db!=null){ db.close(); db = null; } if(cursor!=null){ cursor.close(); cursor = null; } if(rss!=null){ rss = null; } return null; } } @Override public void onUpgrade(SQLiteDatabase db,int arg1,int arg2){ // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS "+TABLE_RSS); // Create tables again onCreate(db); } public List<InfoRSS> getAllRSS(){ List<InfoRSS> rssList = new ArrayList<InfoRSS>(); // Select All Query String selectQuery = "SELECT * FROM "+TABLE_RSS; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery,null); try{ if(cursor.moveToFirst()){ do{ InfoRSS rss = new InfoRSS(); rss.setId(Integer.parseInt(cursor.getString(0))); rss.setRssSource(cursor.getString(1)); rss.setRssTitle(cursor.getString(2)); rss.setRssPubDate(cursor.getString(3)); rss.setRssDesc(cursor.getString(4)); rss.setRssContent(cursor.getString(5)); rss.setRssCategory(cursor.getString(6)); rss.setRssLink(cursor.getString(7)); rssList.add(rss); }while(cursor.moveToNext()); } }finally{ if(db!=null){ db.close(); db = null; } if(cursor!=null){ cursor.close(); cursor = null; } } return rssList; } public int getRSSCount(){ int count = 0; String countQuery = "SELECT * FROM "+TABLE_RSS; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery,null); if(cursor!=null && !cursor.isClosed()){ try{ count = cursor.getCount(); }finally{ cursor.close(); } } return count; } public int updateRSS(InfoRSS rss){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_SOURCE,rss.getRssSource()); values.put(KEY_TITLE,rss.getRssTitle()); values.put(KEY_PUB_DATE,rss.getRssPubDate()); values.put(KEY_DESC,rss.getRssDesc()); values.put(KEY_CONTENT,rss.getRssContent()); values.put(KEY_CATEGORY,rss.getRssCategory()); values.put(KEY_LINK,rss.getRssLink()); // updating row return db.update(TABLE_RSS,values,KEY_ID+" = ?",new String[]{String.valueOf(rss.getId())}); } public void deleteRSS(InfoRSS rss){ SQLiteDatabase db = this.getWritableDatabase(); String[] str = new String[]{String.valueOf(rss.getId())}; //set null in "whereClause" to delete all row! db.delete(TABLE_RSS,KEY_ID+" = ?",str); db.close(); } public void deleteAllRSS(){ SQLiteDatabase db = this.getWritableDatabase(); //set null in "whereClause" to delete all row! db.delete(TABLE_RSS,null,null); db.close(); } }
3e0bffc88862a16363781a335037e5738aa4ef62
2,694
java
Java
java/mobileid-client-usage/src/main/java/ch/swisscom/mid/client/samples/AsyncSignature.java
bmocanu-inc/mobileid-client
81cd87928d5286815ce3fcf9c6e5020a6c8be482
[ "Apache-2.0" ]
null
null
null
java/mobileid-client-usage/src/main/java/ch/swisscom/mid/client/samples/AsyncSignature.java
bmocanu-inc/mobileid-client
81cd87928d5286815ce3fcf9c6e5020a6c8be482
[ "Apache-2.0" ]
null
null
null
java/mobileid-client-usage/src/main/java/ch/swisscom/mid/client/samples/AsyncSignature.java
bmocanu-inc/mobileid-client
81cd87928d5286815ce3fcf9c6e5020a6c8be482
[ "Apache-2.0" ]
1
2021-03-16T07:20:09.000Z
2021-03-16T07:20:09.000Z
42.761905
99
0.699703
5,083
/* * Copyright 2021 Swisscom (Schweiz) AG * * 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 ch.swisscom.mid.client.samples; import ch.swisscom.mid.client.MIDClient; import ch.swisscom.mid.client.config.ClientConfiguration; import ch.swisscom.mid.client.impl.MIDClientImpl; import ch.swisscom.mid.client.model.SignatureProfiles; import ch.swisscom.mid.client.model.SignatureRequest; import ch.swisscom.mid.client.model.SignatureResponse; import ch.swisscom.mid.client.model.StatusCode; import ch.swisscom.mid.client.model.SubscriberInfoAdditionalService; import ch.swisscom.mid.client.model.UserLanguage; import static ch.swisscom.mid.client.samples.Utils.prettyPrintTheException; public class AsyncSignature { public static void main(String[] args) { // edit the config here with your data ClientConfiguration clientConfig = Utils.buildClientConfig(); MIDClient client = new MIDClientImpl(clientConfig); SignatureRequest request = new SignatureRequest(); request.setUserLanguage(UserLanguage.ENGLISH); // edit this value accordingly request.getDataToBeSigned().setData("ApplicationProvider.com: Please sign this document"); // edit this value accordingly request.getMobileUser().setMsisdn("41790000000"); request.setSignatureProfile(SignatureProfiles.DEFAULT_PROFILE); request.addAdditionalService(new SubscriberInfoAdditionalService()); try { SignatureResponse response = client.requestAsyncSignature(request); while (response.getStatus().getStatusCode() == StatusCode.REQUEST_OK || response.getStatus().getStatusCode() == StatusCode.OUTSTANDING_TRANSACTION) { System.out.println("Pending: " + response); response = client.pollForSignatureStatus(response.getTracking()); Thread.sleep(1000); } System.out.println(response.toString()); } catch (Exception e) { System.out.println(prettyPrintTheException(e)); } finally { client.close(); } } }
3e0bfffe73d1ef3fea06d4066323b70042c2dc54
362
java
Java
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/ErrorWebExceptionHandler.java
yangfancoming/spring-boot-build
3d4b8cbb8fea3e68617490609a68ded8f034bc67
[ "Apache-2.0" ]
null
null
null
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/ErrorWebExceptionHandler.java
yangfancoming/spring-boot-build
3d4b8cbb8fea3e68617490609a68ded8f034bc67
[ "Apache-2.0" ]
8
2020-01-31T18:21:07.000Z
2022-03-08T21:12:35.000Z
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/ErrorWebExceptionHandler.java
yangfancoming/spring-boot-build
3d4b8cbb8fea3e68617490609a68ded8f034bc67
[ "Apache-2.0" ]
null
null
null
20.111111
87
0.779006
5,084
package org.springframework.boot.web.reactive.error; import org.springframework.web.server.WebExceptionHandler; /** * Marker interface that indicates that a {@link WebExceptionHandler} is used to render * errors. * * @author Brian Clozel * @since 2.0.0 */ @FunctionalInterface public interface ErrorWebExceptionHandler extends WebExceptionHandler { }
3e0c005e73372806d61f3e290ee944ab342e939e
2,524
java
Java
wava-common/src/main/java/me/wener/wava/util/Chinesese.java
wenerme/wava
9af65e26b8dcb4e561f06eab86701b6f7c896446
[ "Apache-2.0" ]
null
null
null
wava-common/src/main/java/me/wener/wava/util/Chinesese.java
wenerme/wava
9af65e26b8dcb4e561f06eab86701b6f7c896446
[ "Apache-2.0" ]
null
null
null
wava-common/src/main/java/me/wener/wava/util/Chinesese.java
wenerme/wava
9af65e26b8dcb4e561f06eab86701b6f7c896446
[ "Apache-2.0" ]
null
null
null
26.291667
93
0.715135
5,085
package me.wener.wava.util; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; /** * * * <ul> * <li>Common word * <li>CharMatcher * <li>Splitter & Joiner * </ul> * * @author <a href=http://github.com/wenerme>wener</a> * @see <a href="https://zh.wikipedia.org/wiki/中文数字">Wikipedia: 中文数字</a> * @since 2017/4/24 */ public interface Chinesese { /** 中文逗号 */ static char comma() { return Holder.COMMA; } /** 小写的中文数字 */ static String upperNumerals() { return Holder.UPPER_NUMERALS; } /** 大写的中文数字 */ static String lowerNumerals() { return Holder.LOWER_NUMERALS; } /** 中文数字 */ static String numerals() { return Holder.NUMERALS; } /** 判断字符是否为中文 */ static boolean isChinese(int c) { return Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN; } /** 判断字符串是否为中文 */ static boolean isChinese(CharSequence s) { return s.codePoints().allMatch(Chinesese::isChinese); } static CharMatcher upperNumeralsMatcher() { return Holder.UPPER_NUMERALS_MATCHER; } static CharMatcher lowerNumeralsMatcher() { return Holder.LOWER_NUMERALS_MATCHER; } static CharMatcher numeralsMatcher() { return Holder.NUMERALS_MATCHER; } static CharMatcher unicodeScriptMatcher(Character.UnicodeScript unicodeScript) { //noinspection ConstantConditions v will never be null return CharMatcher.forPredicate(v -> Character.UnicodeScript.of(v) == unicodeScript); } static CharMatcher hanUnicodeScriptMatcher() { return Holder.HAN_MATCHER; } static Splitter commaSplitter() { return Holder.SP_COMMA; } static Joiner commaJoiner() { return Holder.JO_COMMA; } final class Holder { static final String UPPER_NUMERALS = "零壹贰叁肆伍陆柒捌玖拾佰仟萬億"; static final CharMatcher UPPER_NUMERALS_MATCHER = CharMatcher.anyOf(UPPER_NUMERALS); static final String LOWER_NUMERALS = "〇一二三四五六七八九十百千万亿"; static final String NUMERALS = UPPER_NUMERALS.concat(LOWER_NUMERALS); static final CharMatcher LOWER_NUMERALS_MATCHER = CharMatcher.anyOf(LOWER_NUMERALS); static final CharMatcher NUMERALS_MATCHER = CharMatcher.anyOf(NUMERALS); static final CharMatcher HAN_MATCHER = unicodeScriptMatcher(Character.UnicodeScript.HAN); static final char COMMA = ','; static final Splitter SP_COMMA = Splitter.on(Chinesese.comma()).omitEmptyStrings().trimResults(); static final Joiner JO_COMMA = Joiner.on(Chinesese.comma()); } }
3e0c0070d951bd45bc1c49cfe394e74c8460dcad
477
java
Java
database/dao-client/src/main/java/br/com/strn/ec/database/dao/client/CategoryShopDAO.java
IvoSestren/strn-ec
a21f8d6a36979b211525249c20084425ebd4e2ab
[ "Unlicense" ]
null
null
null
database/dao-client/src/main/java/br/com/strn/ec/database/dao/client/CategoryShopDAO.java
IvoSestren/strn-ec
a21f8d6a36979b211525249c20084425ebd4e2ab
[ "Unlicense" ]
null
null
null
database/dao-client/src/main/java/br/com/strn/ec/database/dao/client/CategoryShopDAO.java
IvoSestren/strn-ec
a21f8d6a36979b211525249c20084425ebd4e2ab
[ "Unlicense" ]
null
null
null
21.681818
63
0.698113
5,086
package br.com.strn.ec.database.dao.client; import br.com.strn.ec.database.dao.GenericDAO; import br.com.strn.ec.database.entities.client.CategoryShop; import org.hibernate.Session; import javax.inject.Inject; public class CategoryShopDAO extends GenericDAO<CategoryShop> { /** * @deprecated CDI eyes only */ protected CategoryShopDAO() { this(null); } @Inject public CategoryShopDAO(Session session) { super(session); } }
3e0c00848129a4e4d1ebe74462ccedcec174d7c5
3,094
java
Java
scm.common/src/main/java/pers/zcc/scm/common/frame/CORSFilter.java
zhangchangchun3009/scm
a10f6eb20f821056cf443c56647815cc51acea91
[ "Apache-2.0" ]
null
null
null
scm.common/src/main/java/pers/zcc/scm/common/frame/CORSFilter.java
zhangchangchun3009/scm
a10f6eb20f821056cf443c56647815cc51acea91
[ "Apache-2.0" ]
null
null
null
scm.common/src/main/java/pers/zcc/scm/common/frame/CORSFilter.java
zhangchangchun3009/scm
a10f6eb20f821056cf443c56647815cc51acea91
[ "Apache-2.0" ]
null
null
null
37.277108
144
0.681642
5,087
package pers.zcc.scm.common.frame; import java.io.IOException; import java.util.Collection; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.http.HttpHeaders; /** * The Class CORSFilter. */ /** * @author zhangchangchun * @since 2021年7月8日 */ public class CORSFilter implements Filter { private static String origin; @Override public void init(FilterConfig filterConfig) throws ServletException { origin = filterConfig.getInitParameter("origin"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String requestOrigin = httpServletRequest.getHeader("origin"); if (origin == null || "".equals(origin)) { origin = requestOrigin; } if (origin == null || "".equals(origin)) { origin = "*"; } httpServletResponse.addHeader("Access-Control-Allow-Origin", origin); httpServletResponse.addHeader("Access-Control-Allow-Headers", "Accept, Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type"); httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true"); httpServletResponse.addHeader("Access-Control-Max-Age", "600"); final Collection<String> cookiesHeaders = httpServletResponse.getHeaders(HttpHeaders.SET_COOKIE); boolean firstHeader = true; for (final String cookieHeader : cookiesHeaders) { if (StringUtils.isEmpty(cookieHeader)) { continue; } String customizedCookieHeader = ""; StringBuilder sb = new StringBuilder(); customizedCookieHeader = sb.append(cookieHeader).append(";SameSite=None;Secure").toString(); if (firstHeader) { httpServletResponse.setHeader(HttpHeaders.SET_COOKIE, customizedCookieHeader); firstHeader = false; } else { httpServletResponse.addHeader(HttpHeaders.SET_COOKIE, customizedCookieHeader); } } String method = ((HttpServletRequest) request).getMethod(); if (method.equals("OPTIONS")) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); return; } else { chain.doFilter(httpServletRequest, httpServletResponse); } } @Override public void destroy() { } }
3e0c0123a902511b8cf7bf21388d5d220d569e57
486
java
Java
mall-admin/src/main/java/cn/fxpaul/modules/app/form/LoginForm.java
FXPaUl-only/mall
316e2e4ba5f86d250fd6dc827b3856ca6a878f8a
[ "Apache-2.0" ]
null
null
null
mall-admin/src/main/java/cn/fxpaul/modules/app/form/LoginForm.java
FXPaUl-only/mall
316e2e4ba5f86d250fd6dc827b3856ca6a878f8a
[ "Apache-2.0" ]
2
2021-04-22T17:07:35.000Z
2021-09-20T20:58:06.000Z
mall-admin/src/main/java/cn/fxpaul/modules/app/form/LoginForm.java
FXPaUl-only/malltest
2df1491a3ba3650c930ae0115d1a92ef945af480
[ "Apache-2.0" ]
null
null
null
18
47
0.716049
5,088
package cn.fxpaul.modules.app.form; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotBlank; /** * 登录表单 * * @author FXPaul */ @Data @ApiModel(value = "登录表单") public class LoginForm { @ApiModelProperty(value = "手机号") @NotBlank(message="手机号不能为空") private String mobile; @ApiModelProperty(value = "密码") @NotBlank(message="密码不能为空") private String password; }
3e0c0205c94673c630c34cc07351f847caa557da
424
java
Java
module_message/src/main/java/com/alpha/module_message/MessageViewDelegate.java
weixingtai/FrameworkAlpha
6437a4cb3b8ef28d5ad2859a886b72e416da8375
[ "MIT" ]
null
null
null
module_message/src/main/java/com/alpha/module_message/MessageViewDelegate.java
weixingtai/FrameworkAlpha
6437a4cb3b8ef28d5ad2859a886b72e416da8375
[ "MIT" ]
null
null
null
module_message/src/main/java/com/alpha/module_message/MessageViewDelegate.java
weixingtai/FrameworkAlpha
6437a4cb3b8ef28d5ad2859a886b72e416da8375
[ "MIT" ]
null
null
null
22.315789
59
0.740566
5,089
package com.alpha.module_message; import android.view.View; import com.alpha.module_common.base.BaseFragment; import com.alpha.module_common.base.IViewDelegate; public class MessageViewDelegate implements IViewDelegate { @Override public BaseFragment getFragment(String name) { return MessageFragment.getInstance(); } @Override public View getView(String name) { return null; } }
3e0c0234396f3a2a347a46788feca0dec4e82386
12,589
java
Java
components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointConfigurer.java
LittleEntity/camel
da0d257a983859c25add75047498aa2aa319d7e2
[ "Apache-2.0" ]
4,262
2015-01-01T15:28:37.000Z
2022-03-31T04:46:41.000Z
components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointConfigurer.java
LittleEntity/camel
da0d257a983859c25add75047498aa2aa319d7e2
[ "Apache-2.0" ]
3,408
2015-01-03T02:11:17.000Z
2022-03-31T20:07:56.000Z
components/camel-grpc/src/generated/java/org/apache/camel/component/grpc/GrpcEndpointConfigurer.java
LittleEntity/camel
da0d257a983859c25add75047498aa2aa319d7e2
[ "Apache-2.0" ]
5,505
2015-01-02T14:58:12.000Z
2022-03-30T19:23:41.000Z
61.11165
183
0.725475
5,090
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.grpc; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.ExtendedPropertyConfigurerGetter; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.spi.ConfigurerStrategy; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class GrpcEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { GrpcEndpoint target = (GrpcEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "authenticationtype": case "authenticationType": target.getConfiguration().setAuthenticationType(property(camelContext, org.apache.camel.component.grpc.GrpcAuthType.class, value)); return true; case "autodiscoverclientinterceptors": case "autoDiscoverClientInterceptors": target.getConfiguration().setAutoDiscoverClientInterceptors(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "consumerstrategy": case "consumerStrategy": target.getConfiguration().setConsumerStrategy(property(camelContext, org.apache.camel.component.grpc.GrpcConsumerStrategy.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "flowcontrolwindow": case "flowControlWindow": target.getConfiguration().setFlowControlWindow(property(camelContext, int.class, value)); return true; case "forwardoncompleted": case "forwardOnCompleted": target.getConfiguration().setForwardOnCompleted(property(camelContext, boolean.class, value)); return true; case "forwardonerror": case "forwardOnError": target.getConfiguration().setForwardOnError(property(camelContext, boolean.class, value)); return true; case "jwtalgorithm": case "jwtAlgorithm": target.getConfiguration().setJwtAlgorithm(property(camelContext, org.apache.camel.component.grpc.auth.jwt.JwtAlgorithm.class, value)); return true; case "jwtissuer": case "jwtIssuer": target.getConfiguration().setJwtIssuer(property(camelContext, java.lang.String.class, value)); return true; case "jwtsecret": case "jwtSecret": target.getConfiguration().setJwtSecret(property(camelContext, java.lang.String.class, value)); return true; case "jwtsubject": case "jwtSubject": target.getConfiguration().setJwtSubject(property(camelContext, java.lang.String.class, value)); return true; case "keycertchainresource": case "keyCertChainResource": target.getConfiguration().setKeyCertChainResource(property(camelContext, java.lang.String.class, value)); return true; case "keypassword": case "keyPassword": target.getConfiguration().setKeyPassword(property(camelContext, java.lang.String.class, value)); return true; case "keyresource": case "keyResource": target.getConfiguration().setKeyResource(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "maxconcurrentcallsperconnection": case "maxConcurrentCallsPerConnection": target.getConfiguration().setMaxConcurrentCallsPerConnection(property(camelContext, int.class, value)); return true; case "maxmessagesize": case "maxMessageSize": target.getConfiguration().setMaxMessageSize(property(camelContext, int.class, value)); return true; case "method": target.getConfiguration().setMethod(property(camelContext, java.lang.String.class, value)); return true; case "negotiationtype": case "negotiationType": target.getConfiguration().setNegotiationType(property(camelContext, io.grpc.netty.NegotiationType.class, value)); return true; case "producerstrategy": case "producerStrategy": target.getConfiguration().setProducerStrategy(property(camelContext, org.apache.camel.component.grpc.GrpcProducerStrategy.class, value)); return true; case "routecontrolledstreamobserver": case "routeControlledStreamObserver": target.getConfiguration().setRouteControlledStreamObserver(property(camelContext, boolean.class, value)); return true; case "serviceaccountresource": case "serviceAccountResource": target.getConfiguration().setServiceAccountResource(property(camelContext, java.lang.String.class, value)); return true; case "streamrepliesto": case "streamRepliesTo": target.getConfiguration().setStreamRepliesTo(property(camelContext, java.lang.String.class, value)); return true; case "synchronous": target.getConfiguration().setSynchronous(property(camelContext, boolean.class, value)); return true; case "trustcertcollectionresource": case "trustCertCollectionResource": target.getConfiguration().setTrustCertCollectionResource(property(camelContext, java.lang.String.class, value)); return true; case "useragent": case "userAgent": target.getConfiguration().setUserAgent(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "authenticationtype": case "authenticationType": return org.apache.camel.component.grpc.GrpcAuthType.class; case "autodiscoverclientinterceptors": case "autoDiscoverClientInterceptors": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "consumerstrategy": case "consumerStrategy": return org.apache.camel.component.grpc.GrpcConsumerStrategy.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "flowcontrolwindow": case "flowControlWindow": return int.class; case "forwardoncompleted": case "forwardOnCompleted": return boolean.class; case "forwardonerror": case "forwardOnError": return boolean.class; case "jwtalgorithm": case "jwtAlgorithm": return org.apache.camel.component.grpc.auth.jwt.JwtAlgorithm.class; case "jwtissuer": case "jwtIssuer": return java.lang.String.class; case "jwtsecret": case "jwtSecret": return java.lang.String.class; case "jwtsubject": case "jwtSubject": return java.lang.String.class; case "keycertchainresource": case "keyCertChainResource": return java.lang.String.class; case "keypassword": case "keyPassword": return java.lang.String.class; case "keyresource": case "keyResource": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "maxconcurrentcallsperconnection": case "maxConcurrentCallsPerConnection": return int.class; case "maxmessagesize": case "maxMessageSize": return int.class; case "method": return java.lang.String.class; case "negotiationtype": case "negotiationType": return io.grpc.netty.NegotiationType.class; case "producerstrategy": case "producerStrategy": return org.apache.camel.component.grpc.GrpcProducerStrategy.class; case "routecontrolledstreamobserver": case "routeControlledStreamObserver": return boolean.class; case "serviceaccountresource": case "serviceAccountResource": return java.lang.String.class; case "streamrepliesto": case "streamRepliesTo": return java.lang.String.class; case "synchronous": return boolean.class; case "trustcertcollectionresource": case "trustCertCollectionResource": return java.lang.String.class; case "useragent": case "userAgent": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { GrpcEndpoint target = (GrpcEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "authenticationtype": case "authenticationType": return target.getConfiguration().getAuthenticationType(); case "autodiscoverclientinterceptors": case "autoDiscoverClientInterceptors": return target.getConfiguration().isAutoDiscoverClientInterceptors(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "consumerstrategy": case "consumerStrategy": return target.getConfiguration().getConsumerStrategy(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "flowcontrolwindow": case "flowControlWindow": return target.getConfiguration().getFlowControlWindow(); case "forwardoncompleted": case "forwardOnCompleted": return target.getConfiguration().isForwardOnCompleted(); case "forwardonerror": case "forwardOnError": return target.getConfiguration().isForwardOnError(); case "jwtalgorithm": case "jwtAlgorithm": return target.getConfiguration().getJwtAlgorithm(); case "jwtissuer": case "jwtIssuer": return target.getConfiguration().getJwtIssuer(); case "jwtsecret": case "jwtSecret": return target.getConfiguration().getJwtSecret(); case "jwtsubject": case "jwtSubject": return target.getConfiguration().getJwtSubject(); case "keycertchainresource": case "keyCertChainResource": return target.getConfiguration().getKeyCertChainResource(); case "keypassword": case "keyPassword": return target.getConfiguration().getKeyPassword(); case "keyresource": case "keyResource": return target.getConfiguration().getKeyResource(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "maxconcurrentcallsperconnection": case "maxConcurrentCallsPerConnection": return target.getConfiguration().getMaxConcurrentCallsPerConnection(); case "maxmessagesize": case "maxMessageSize": return target.getConfiguration().getMaxMessageSize(); case "method": return target.getConfiguration().getMethod(); case "negotiationtype": case "negotiationType": return target.getConfiguration().getNegotiationType(); case "producerstrategy": case "producerStrategy": return target.getConfiguration().getProducerStrategy(); case "routecontrolledstreamobserver": case "routeControlledStreamObserver": return target.getConfiguration().isRouteControlledStreamObserver(); case "serviceaccountresource": case "serviceAccountResource": return target.getConfiguration().getServiceAccountResource(); case "streamrepliesto": case "streamRepliesTo": return target.getConfiguration().getStreamRepliesTo(); case "synchronous": return target.getConfiguration().isSynchronous(); case "trustcertcollectionresource": case "trustCertCollectionResource": return target.getConfiguration().getTrustCertCollectionResource(); case "useragent": case "userAgent": return target.getConfiguration().getUserAgent(); default: return null; } } }
3e0c024639a329756c8188de36228f5336589239
1,875
java
Java
chat-core/src/main/java/com/alipay/api/domain/AlipayFundTransThirdpartyRewardCreateModel.java
WangYong1012/DubboChat
696ae599236c56417204324cc12e6e953b0bdb2c
[ "Apache-2.0" ]
null
null
null
chat-core/src/main/java/com/alipay/api/domain/AlipayFundTransThirdpartyRewardCreateModel.java
WangYong1012/DubboChat
696ae599236c56417204324cc12e6e953b0bdb2c
[ "Apache-2.0" ]
null
null
null
chat-core/src/main/java/com/alipay/api/domain/AlipayFundTransThirdpartyRewardCreateModel.java
WangYong1012/DubboChat
696ae599236c56417204324cc12e6e953b0bdb2c
[ "Apache-2.0" ]
null
null
null
17.361111
78
0.7056
5,091
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 外部商户可通过此接口创建支付宝用户的打赏订单,而后通过支付宝快捷支付对此订单进行支付完成打赏。(不支持企业用户) * * @author auto create * @since 1.0, 2016-10-26 18:05:18 */ public class AlipayFundTransThirdpartyRewardCreateModel extends AlipayObject { private static final long serialVersionUID = 6772712551277417924L; /** * 打赏金额,单位:人民币分 */ @ApiField("amount") private String amount; /** * 扩展参数,json格式 */ @ApiField("ext_param") private String extParam; /** * 外部业务号,用于幂等控制 */ @ApiField("out_no") private String outNo; /** * 收款用户的支付宝userId */ @ApiField("receiver_user_id") private String receiverUserId; /** * 场景码,需业务方分配方可使用 */ @ApiField("scene") private String scene; /** * 付款用户的支付宝userId */ @ApiField("sender_user_id") private String senderUserId; /** * 打赏的标题(理由) */ @ApiField("title") private String title; public String getAmount() { return this.amount; } public void setAmount(String amount) { this.amount = amount; } public String getExtParam() { return this.extParam; } public void setExtParam(String extParam) { this.extParam = extParam; } public String getOutNo() { return this.outNo; } public void setOutNo(String outNo) { this.outNo = outNo; } public String getReceiverUserId() { return this.receiverUserId; } public void setReceiverUserId(String receiverUserId) { this.receiverUserId = receiverUserId; } public String getScene() { return this.scene; } public void setScene(String scene) { this.scene = scene; } public String getSenderUserId() { return this.senderUserId; } public void setSenderUserId(String senderUserId) { this.senderUserId = senderUserId; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } }
3e0c02a12b877d848c064faa0f84230b1b93bc63
8,445
java
Java
jupiter-example/src/main/java/org/jupiter/benchmark/unix/domain/BenchmarkClient.java
vip-lic/Jupiter
6bffde84535bc32cb676a99e3b8d7c3e14894747
[ "Apache-2.0" ]
1,608
2015-09-13T10:46:48.000Z
2022-03-22T01:27:04.000Z
jupiter-example/src/main/java/org/jupiter/benchmark/unix/domain/BenchmarkClient.java
Ethan-prog/Jupiter
33ae75e46d81c5edcb0921352adee1151c903507
[ "Apache-2.0" ]
78
2015-10-18T08:59:37.000Z
2022-01-21T07:00:35.000Z
jupiter-example/src/main/java/org/jupiter/benchmark/unix/domain/BenchmarkClient.java
Ethan-prog/Jupiter
33ae75e46d81c5edcb0921352adee1151c903507
[ "Apache-2.0" ]
649
2016-01-17T05:41:45.000Z
2022-03-04T03:28:41.000Z
40.023697
117
0.539017
5,092
/* * Copyright (c) 2015 The Jupiter Project * * Licensed under the Apache License, version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jupiter.benchmark.unix.domain; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicLong; import org.jupiter.common.util.JConstants; import org.jupiter.common.util.Lists; import org.jupiter.common.util.SystemPropertyUtil; import org.jupiter.common.util.internal.logging.InternalLogger; import org.jupiter.common.util.internal.logging.InternalLoggerFactory; import org.jupiter.rpc.DefaultClient; import org.jupiter.rpc.InvokeType; import org.jupiter.rpc.JClient; import org.jupiter.rpc.consumer.ProxyFactory; import org.jupiter.rpc.consumer.future.InvokeFuture; import org.jupiter.rpc.consumer.future.InvokeFutureContext; import org.jupiter.rpc.load.balance.LoadBalancerType; import org.jupiter.serialization.SerializerType; import org.jupiter.transport.UnresolvedAddress; import org.jupiter.transport.UnresolvedDomainAddress; import org.jupiter.transport.netty.JNettyDomainConnector; /** * * 飞行记录: -XX:+UnlockCommercialFeatures -XX:+FlightRecorder * * jupiter * org.jupiter.benchmark.unix.domain * * @author jiachun.fjc */ public class BenchmarkClient { private static final InternalLogger logger = InternalLoggerFactory.getInstance(BenchmarkClient.class); public static void main(String[] args) { // SystemPropertyUtil.setProperty("jupiter.io.codec.low_copy", "true"); int processors = JConstants.AVAILABLE_PROCESSORS; SystemPropertyUtil .setProperty("jupiter.executor.factory.consumer.core.workers", String.valueOf(processors << 1)); SystemPropertyUtil.setProperty("jupiter.tracing.needed", "false"); SystemPropertyUtil.setProperty("jupiter.use.non_blocking_hash", "true"); SystemPropertyUtil .setProperty("jupiter.executor.factory.affinity.thread", "false"); SystemPropertyUtil .setProperty("jupiter.executor.factory.consumer.factory_name", "forkJoin"); final JClient client = new DefaultClient().withConnector(new JNettyDomainConnector(processors) { // @Override // protected ThreadFactory workerThreadFactory(String name) { // return new AffinityNettyThreadFactory(name); // } }); UnresolvedAddress[] addresses = new UnresolvedAddress[processors]; for (int i = 0; i < processors; i++) { addresses[i] = new UnresolvedDomainAddress(UnixDomainPath.PATH); client.connector().connect(addresses[i]); } if (SystemPropertyUtil.getBoolean("jupiter.test.async", true)) { futureCall(client, addresses, processors); } else { syncCall(client, addresses, processors); } } private static void syncCall(JClient client, UnresolvedAddress[] addresses, int processors) { final Service service = ProxyFactory.factory(Service.class) .version("1.0.0") .client(client) .serializerType(SerializerType.PROTO_STUFF) .loadBalancerType(LoadBalancerType.ROUND_ROBIN) .addProviderAddress(addresses) .newProxyInstance(); for (int i = 0; i < 10000; i++) { try { service.hello("jupiter"); } catch (Exception e) { e.printStackTrace(); } } final int t = 50000; final int step = 6; long start = System.currentTimeMillis(); final CountDownLatch latch = new CountDownLatch(processors << step); final AtomicLong count = new AtomicLong(); for (int i = 0; i < (processors << step); i++) { new Thread(() -> { for (int i1 = 0; i1 < t; i1++) { try { service.hello("jupiter"); if (count.getAndIncrement() % 10000 == 0) { logger.warn("count=" + count.get()); } } catch (Exception e) { e.printStackTrace(); } } latch.countDown(); }).start(); } try { latch.await(); logger.warn("count=" + count.get()); } catch (InterruptedException e) { e.printStackTrace(); } long second = (System.currentTimeMillis() - start) / 1000; logger.warn("Request count: " + count.get() + ", time: " + second + " second, qps: " + count.get() / second); } private static void futureCall(JClient client, UnresolvedAddress[] addresses, int processors) { final Service service = ProxyFactory.factory(Service.class) .version("1.0.0") .client(client) .invokeType(InvokeType.ASYNC) .serializerType(SerializerType.PROTO_STUFF) .loadBalancerType(LoadBalancerType.ROUND_ROBIN) .addProviderAddress(addresses) .newProxyInstance(); for (int i = 0; i < 10000; i++) { try { service.hello("jupiter"); InvokeFutureContext.future().getResult(); } catch (Throwable e) { e.printStackTrace(); } } final int t = 80000; long start = System.currentTimeMillis(); final CountDownLatch latch = new CountDownLatch(processors << 4); final AtomicLong count = new AtomicLong(); final int futureSize = 80; for (int i = 0; i < (processors << 4); i++) { new Thread(new Runnable() { List<InvokeFuture<?>> futures = Lists.newArrayListWithCapacity(futureSize); @SuppressWarnings("all") @Override public void run() { for (int i = 0; i < t; i++) { try { service.hello("jupiter"); futures.add(InvokeFutureContext.future()); if (futures.size() == futureSize) { int fSize = futures.size(); for (int j = 0; j < fSize; j++) { try { futures.get(j).getResult(); } catch (Throwable t) { t.printStackTrace(); } } futures.clear(); } if (count.getAndIncrement() % 10000 == 0) { logger.warn("count=" + count.get()); } } catch (Exception e) { e.printStackTrace(); } } if (!futures.isEmpty()) { int fSize = futures.size(); for (int j = 0; j < fSize; j++) { try { futures.get(j).getResult(); } catch (Throwable t) { t.printStackTrace(); } } futures.clear(); } latch.countDown(); } }).start(); } try { latch.await(); logger.warn("count=" + count.get()); } catch (InterruptedException e) { e.printStackTrace(); } long second = (System.currentTimeMillis() - start) / 1000; logger.warn("Request count: " + count.get() + ", time: " + second + " second, qps: " + count.get() / second); } }
3e0c04546f8e40c71a7b65b863246d6334413a6c
875
java
Java
app/src/main/java/com/github/ihal20/drybones/android/preference/BooleanPreference.java
ihal20/DryBones
a1c81c1bb47b2b36d145c0207471a15e198dae8b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/github/ihal20/drybones/android/preference/BooleanPreference.java
ihal20/DryBones
a1c81c1bb47b2b36d145c0207471a15e198dae8b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/github/ihal20/drybones/android/preference/BooleanPreference.java
ihal20/DryBones
a1c81c1bb47b2b36d145c0207471a15e198dae8b
[ "Apache-2.0" ]
null
null
null
24.305556
93
0.733714
5,093
package com.github.ihal20.drybones.android.preference; import android.content.SharedPreferences; public class BooleanPreference { private final SharedPreferences preferences; private final String key; private final boolean defaultValue; public BooleanPreference(SharedPreferences preferences, String key) { this(preferences, key, false); } public BooleanPreference(SharedPreferences preferences, String key, boolean defaultValue) { this.preferences = preferences; this.key = key; this.defaultValue = defaultValue; } public boolean get() { return preferences.getBoolean(key, defaultValue); } public boolean isSet() { return preferences.contains(key); } public void set(boolean value) { preferences.edit().putBoolean(key, value).apply(); } public void delete() { preferences.edit().remove(key).apply(); } }
3e0c049e86f66997c4e72a1cfd6ef60b85e8ac32
407
java
Java
h2o-core/src/main/java/water/util/JSONUtils.java
jbentleyEG/h2o-3
93f1084b5e244beca517b0a1fc8b0c02061d597f
[ "Apache-2.0" ]
2
2019-09-02T15:49:45.000Z
2019-09-02T16:01:58.000Z
h2o-core/src/main/java/water/util/JSONUtils.java
jbentleyEG/h2o-3
93f1084b5e244beca517b0a1fc8b0c02061d597f
[ "Apache-2.0" ]
2
2021-06-02T02:24:03.000Z
2021-11-15T17:51:49.000Z
h2o-core/src/main/java/water/util/JSONUtils.java
jbentleyEG/h2o-3
93f1084b5e244beca517b0a1fc8b0c02061d597f
[ "Apache-2.0" ]
1
2021-05-23T07:41:39.000Z
2021-05-23T07:41:39.000Z
23.941176
71
0.761671
5,094
package water.util; import com.google.gson.Gson; import water.nbhm.NonBlockingHashMap; import java.util.Properties; public class JSONUtils { public static NonBlockingHashMap<String, Object> parse(String json) { return new Gson().fromJson(json, NonBlockingHashMap.class); } public static Properties parseToProperties(String json) { return new Gson().fromJson(json, Properties.class); } }
3e0c04c424ed834ccfd4ef35d9f9753e6d96570c
1,061
java
Java
core/spi/src/main/java/org/jboss/arquillian/core/spi/EventContext.java
arjantijms/arquillian-core
2933b98422589abe802f9d31ac21e57032898679
[ "Apache-2.0" ]
223
2015-02-09T11:41:23.000Z
2022-03-21T14:13:36.000Z
core/spi/src/main/java/org/jboss/arquillian/core/spi/EventContext.java
arjantijms/arquillian-core
2933b98422589abe802f9d31ac21e57032898679
[ "Apache-2.0" ]
225
2015-01-05T15:58:18.000Z
2022-03-16T08:51:16.000Z
core/spi/src/main/java/org/jboss/arquillian/core/spi/EventContext.java
arjantijms/arquillian-core
2933b98422589abe802f9d31ac21e57032898679
[ "Apache-2.0" ]
124
2015-01-18T15:13:55.000Z
2022-03-02T06:25:23.000Z
34.193548
75
0.733019
5,095
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.core.spi; /** * EventContext * * @author <a href="mailto:efpyi@example.com">Aslak Knutsen</a> * @version $Revision: $ */ public interface EventContext<T> { T getEvent(); void proceed(); }
3e0c054714942348c4bd9ec48bb02cc92024682d
898
java
Java
src/dkeep/ui/gui/ImageRenderer.java
Rockdell/LPOO1718_T3G11
4834bb22a939341de13c545044760a4537113352
[ "MIT" ]
null
null
null
src/dkeep/ui/gui/ImageRenderer.java
Rockdell/LPOO1718_T3G11
4834bb22a939341de13c545044760a4537113352
[ "MIT" ]
null
null
null
src/dkeep/ui/gui/ImageRenderer.java
Rockdell/LPOO1718_T3G11
4834bb22a939341de13c545044760a4537113352
[ "MIT" ]
null
null
null
25.657143
136
0.747216
5,096
package dkeep.ui.gui; import java.awt.Component; import java.awt.Image; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; public class ImageRenderer extends DefaultTableCellRenderer { /** Create the panel. */ public ImageRenderer() {} public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel lbl = ((JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column)); Image im = null; try { im = (ImageIO.read(new File((String) value))).getScaledInstance(30, 30, Image.SCALE_FAST); } catch (IOException e) { e.printStackTrace(); } lbl = new JLabel(new ImageIcon(im)); return lbl; } }
3e0c065a2a0ec76eb79ea87e207e79e4829e2cef
866
java
Java
src/main/java/top/hellholestudios/xgn/jmj/scoring/classic/Sanankou.java
XiaoGeNintendo/JMahjong
1c5df1b0cbf3d4b360e502bc7b63611ee358ea4c
[ "MIT" ]
null
null
null
src/main/java/top/hellholestudios/xgn/jmj/scoring/classic/Sanankou.java
XiaoGeNintendo/JMahjong
1c5df1b0cbf3d4b360e502bc7b63611ee358ea4c
[ "MIT" ]
null
null
null
src/main/java/top/hellholestudios/xgn/jmj/scoring/classic/Sanankou.java
XiaoGeNintendo/JMahjong
1c5df1b0cbf3d4b360e502bc7b63611ee358ea4c
[ "MIT" ]
null
null
null
25.470588
118
0.556582
5,097
package top.hellholestudios.xgn.jmj.scoring.classic; import top.hellholestudios.xgn.jmj.Mentsu; import top.hellholestudios.xgn.jmj.RonWrapper; import top.hellholestudios.xgn.jmj.scoring.AgariInfo; import top.hellholestudios.xgn.jmj.scoring.Yaku; public class Sanankou extends Yaku { public Sanankou() { super("3ak", "三暗刻"); } @Override public int check(RonWrapper ron) { int c = 0; for (int i = 0; i < 4; i++) { if (ron.sorted.mentsus[i]!=null && ron.sorted.mentsus[i].type == Mentsu.Kotsu && (ron.agariInfo.getAgariType()== AgariInfo.AgariType.Tsumo || i != ron.sorted.lastTileIndicator)) { c++; } } c+=ron.ankans.length; if (c == 3) { return 2; } else { return 0; } } }
3e0c06d7b1f4d5e7005e7513a334a65b856d4e49
518
java
Java
test/com/bjc/protoss/dp/harry/TemplateTest.java
rainyheart/bjc-protoss-design_patten-demo
3c99851cae65f457a6f0f4ca9d2c56b6756167e9
[ "Apache-2.0" ]
4
2016-11-22T02:49:29.000Z
2019-04-02T02:30:08.000Z
test/com/bjc/protoss/dp/harry/TemplateTest.java
rainyheart/bjc-protoss-design_patten-demo
3c99851cae65f457a6f0f4ca9d2c56b6756167e9
[ "Apache-2.0" ]
null
null
null
test/com/bjc/protoss/dp/harry/TemplateTest.java
rainyheart/bjc-protoss-design_patten-demo
3c99851cae65f457a6f0f4ca9d2c56b6756167e9
[ "Apache-2.0" ]
null
null
null
28.777778
65
0.735521
5,098
package com.bjc.protoss.dp.harry; import com.bjc.protoss.dp.module.template.harry.Template; import com.bjc.protoss.dp.module.template.harry.TemplateConcrete; /** * Created by zhexzhi on 12/14/2016. * 所谓模板板式,就是在父类中定义算法的主要流程,而把一些个性化的步骤延迟到子类中去实现 * example: spring JdbcTemplate ...简化了很多样板式代码处理,使程序员只需关注业务 * http://blog.csdn.net/dyllove98/article/details/7772463 */ public class TemplateTest { public static void main(String[] args) { Template temp = new TemplateConcrete(); temp.work(); } }
3e0c072c9364acee56ad0aeb0c96fa6bb19f7f05
345
java
Java
intern/chapter_003_collections_light/src/main/java/ru/job4j/list2list/ConvertList2List.java
ilya-moskovtsev/imoskovtsev
4069d9217628875187a906235719daed7b0f1f70
[ "Apache-2.0" ]
1
2017-05-22T21:02:51.000Z
2017-05-22T21:02:51.000Z
intern/chapter_003_collections_light/src/main/java/ru/job4j/list2list/ConvertList2List.java
ilya-moskovtsev/imoskovtsev
4069d9217628875187a906235719daed7b0f1f70
[ "Apache-2.0" ]
64
2019-04-04T12:18:56.000Z
2022-03-31T20:16:38.000Z
intern/chapter_003_collections_light/src/main/java/ru/job4j/list2list/ConvertList2List.java
ilya-moskovtsev/imoskovtsev
4069d9217628875187a906235719daed7b0f1f70
[ "Apache-2.0" ]
null
null
null
23
71
0.678261
5,099
package ru.job4j.list2list; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ConvertList2List { public List<Integer> convert(List<int[]> list) { List<Integer> result = new ArrayList<>(); list.forEach(ints -> Arrays.stream(ints).forEach(result::add)); return result; } }
3e0c08080be0ad32d1c8262fd81666cb0dfed846
5,190
java
Java
app/src/main/java/com/engeniouspark/android/roro/firebasechat/ui/fragments/LoginFragment.java
roshanrote/firebase-chat-master
d28dffcc23e8001509209391504806ff5816a1b7
[ "MIT" ]
null
null
null
app/src/main/java/com/engeniouspark/android/roro/firebasechat/ui/fragments/LoginFragment.java
roshanrote/firebase-chat-master
d28dffcc23e8001509209391504806ff5816a1b7
[ "MIT" ]
null
null
null
app/src/main/java/com/engeniouspark/android/roro/firebasechat/ui/fragments/LoginFragment.java
roshanrote/firebase-chat-master
d28dffcc23e8001509209391504806ff5816a1b7
[ "MIT" ]
null
null
null
33.843137
214
0.704326
5,101
package com.engeniouspark.android.roro.firebasechat.ui.fragments; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.engeniouspark.android.roro.firebasechat.R; import com.engeniouspark.android.roro.firebasechat.core.login.LoginContract; import com.engeniouspark.android.roro.firebasechat.core.login.LoginPresenter; import com.engeniouspark.android.roro.firebasechat.ui.activities.ChatActivity; import com.engeniouspark.android.roro.firebasechat.ui.activities.RegisterActivity; import com.engeniouspark.android.roro.firebasechat.ui.activities.UserListingActivity; import com.engeniouspark.android.roro.firebasechat.utils.Constants; import com.engeniouspark.android.roro.firebasechat.utils.SessionData; public class LoginFragment extends Fragment implements View.OnClickListener, LoginContract.View { private LoginPresenter mLoginPresenter; private EditText mETxtEmail, mETxtPassword; private Button mBtnLogin, mBtnRegister; String emailId; SessionData sessionData; Context context; private ProgressDialog mProgressDialog; public static LoginFragment newInstance() { Bundle args = new Bundle(); LoginFragment fragment = new LoginFragment(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View fragmentView = inflater.inflate(R.layout.fragment_login, container, false); bindViews(fragmentView); return fragmentView; } private void bindViews(View view) { mETxtEmail = (EditText) view.findViewById(R.id.edit_text_email_id); mETxtPassword = (EditText) view.findViewById(R.id.edit_text_password); mBtnLogin = (Button) view.findViewById(R.id.button_login); mBtnRegister = (Button) view.findViewById(R.id.button_register); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); init(); context = getActivity(); sessionData = new SessionData(context); } private void init() { mLoginPresenter = new LoginPresenter(this); mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setTitle(getString(R.string.loading)); mProgressDialog.setMessage(getString(R.string.please_wait)); mProgressDialog.setIndeterminate(true); mBtnLogin.setOnClickListener(this); mBtnRegister.setOnClickListener(this); setDummyCredentials(); } private void setDummyCredentials() { mETxtEmail.setText("kenaa@example.com"); mETxtPassword.setText("123456"); } @Override public void onClick(View view) { int viewId = view.getId(); switch (viewId) { case R.id.button_login: onLogin(view); break; case R.id.button_register: onRegister(view); break; } } private void onLogin(View view) { emailId = mETxtEmail.getText().toString(); String password = mETxtPassword.getText().toString(); mLoginPresenter.login(getActivity(), emailId, password); mProgressDialog.show(); } private void onRegister(View view) { RegisterActivity.startActivity(getActivity()); } @Override public void onLoginSuccess(String message) { mProgressDialog.dismiss(); Toast.makeText(getActivity(), "Logged in successfully", Toast.LENGTH_SHORT).show(); // UserListingActivity.startActivity(getActivity(), // Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); if (emailId.equals("envkt@example.com")) { sessionData.setObjectAsString("user","admin"); UserListingActivity.startActivity(getActivity(), Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); } else { sessionData.setObjectAsString("user","user"); Intent intent = new Intent(getActivity(), ChatActivity.class); intent.putExtra(Constants.ARG_RECEIVER, "efpyi@example.com"); intent.putExtra(Constants.ARG_RECEIVER_UID, "iFnvdIOGd3a5QIVPsGioztAdRzU2"); intent.putExtra(Constants.ARG_FIREBASE_TOKEN, "cLecWqQYKy0:APA91bFeh0AajKudiip509BFAAJniR4j3BT7LAIR_xxvcEwtFcBJur8Mm1v5p5ZGrkuuZn_khQAFOU_8VvbgbjpuedoqVFl-Y3FczqzB-7TdXGQNiOywEGCuYafeGHco9mujpmVf5ugP"); getActivity().startActivity(intent); } } @Override public void onLoginFailure(String message) { mProgressDialog.dismiss(); Toast.makeText(getActivity(), "Error: " + message, Toast.LENGTH_SHORT).show(); } }
3e0c09c37a1be03c0e45102840a435f130d2566a
2,256
java
Java
src/main/java/org/docksidestage/dbflute/cbean/nss/MemberWithdrawalNss.java
shin-kinoshita/dbflute-example-on-springboot
6b6355111fda1a6f4eb75d67968aef2b54da8dc1
[ "Apache-2.0" ]
13
2015-03-11T00:37:03.000Z
2022-01-31T01:28:22.000Z
src/main/java/org/docksidestage/dbflute/cbean/nss/MemberWithdrawalNss.java
shin-kinoshita/dbflute-example-on-springboot
6b6355111fda1a6f4eb75d67968aef2b54da8dc1
[ "Apache-2.0" ]
25
2017-07-16T10:54:15.000Z
2022-03-07T11:47:28.000Z
src/main/java/org/docksidestage/dbflute/cbean/nss/MemberWithdrawalNss.java
zoosm3/dbflute-example-on-springboot
c6bef11666d84bfbfed7a42edf2654d0fb70fa90
[ "Apache-2.0" ]
15
2015-02-10T07:33:34.000Z
2021-08-19T12:16:00.000Z
42.566038
117
0.548316
5,102
/* * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.docksidestage.dbflute.cbean.nss; import org.docksidestage.dbflute.cbean.cq.MemberWithdrawalCQ; /** * The nest select set-upper of member_withdrawal. * @author DBFlute(AutoGenerator) */ public class MemberWithdrawalNss { // =================================================================================== // Attribute // ========= protected final MemberWithdrawalCQ _query; public MemberWithdrawalNss(MemberWithdrawalCQ query) { _query = query; } public boolean hasConditionQuery() { return _query != null; } // =================================================================================== // Nested Relation // =============== /** * With nested relation columns to select clause. <br> * (会員)MEMBER by my MEMBER_ID, named 'member'. * @return The set-upper of more nested relation. {...with[nested-relation].with[more-nested-relation]} (NotNull) */ public MemberNss withMember() { _query.xdoNss(() -> _query.queryMember()); return new MemberNss(_query.queryMember()); } /** * With nested relation columns to select clause. <br> * (退会理由)WITHDRAWAL_REASON by my WITHDRAWAL_REASON_CODE, named 'withdrawalReason'. */ public void withWithdrawalReason() { _query.xdoNss(() -> _query.queryWithdrawalReason()); } }
3e0c09fae48de14f1b2bc1b61918960d41838aa1
2,511
java
Java
xs2a-server-api/src/main/java/de/adorsys/psd2/model/LinksTransactionDetails.java
golden-dimension/xs2a
88c46847ee5869bf609445a22d37bd14d75d1252
[ "Apache-2.0" ]
null
null
null
xs2a-server-api/src/main/java/de/adorsys/psd2/model/LinksTransactionDetails.java
golden-dimension/xs2a
88c46847ee5869bf609445a22d37bd14d75d1252
[ "Apache-2.0" ]
null
null
null
xs2a-server-api/src/main/java/de/adorsys/psd2/model/LinksTransactionDetails.java
golden-dimension/xs2a
88c46847ee5869bf609445a22d37bd14d75d1252
[ "Apache-2.0" ]
null
null
null
27.293478
146
0.718041
5,103
package de.adorsys.psd2.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import de.adorsys.psd2.model.HrefType; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.Map; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * LinksTransactionDetails */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-11-12T17:35:11.808068+02:00[Europe/Kiev]") public class LinksTransactionDetails extends HashMap<String, HrefType> { @JsonProperty("transactionDetails") private HrefType transactionDetails = null; public LinksTransactionDetails transactionDetails(HrefType transactionDetails) { this.transactionDetails = transactionDetails; return this; } /** * Get transactionDetails * @return transactionDetails **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid @JsonProperty("transactionDetails") public HrefType getTransactionDetails() { return transactionDetails; } public void setTransactionDetails(HrefType transactionDetails) { this.transactionDetails = transactionDetails; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } LinksTransactionDetails _linksTransactionDetails = (LinksTransactionDetails) o; return Objects.equals(this.transactionDetails, _linksTransactionDetails.transactionDetails); } @Override public int hashCode() { return Objects.hash(transactionDetails, super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LinksTransactionDetails {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" transactionDetails: ").append(toIndentedString(transactionDetails)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e0c0b058599bcd99b8dfb0b5eb8cd9de91d4d12
1,649
java
Java
src/main/java/best/boba/bobawhitelist/Config.java
bobacraft/bobawhitelist
ad135924dac1a63fbcb7c56125349cd6355af1d3
[ "MIT" ]
null
null
null
src/main/java/best/boba/bobawhitelist/Config.java
bobacraft/bobawhitelist
ad135924dac1a63fbcb7c56125349cd6355af1d3
[ "MIT" ]
7
2022-01-17T11:30:38.000Z
2022-01-18T02:45:27.000Z
src/main/java/best/boba/bobawhitelist/Config.java
bobacraft/bobawhitelist
ad135924dac1a63fbcb7c56125349cd6355af1d3
[ "MIT" ]
null
null
null
27.949153
97
0.699212
5,104
package best.boba.bobawhitelist; import com.velocitypowered.api.proxy.ProxyServer; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.logging.Logger; public class Config { private final ProxyServer server; private final Logger logger; private final Path dataDirectory; private final Path whitelistFile; private final Path usernameCacheFile; private Whitelist whitelist; private UsernameCache usernameCache; public Config(ProxyServer server, Logger logger, Path dataDirectory) throws IOException { this.server = server; this.logger = logger; this.dataDirectory = dataDirectory; this.whitelistFile = Paths.get(this.dataDirectory.toString(), "whitelist.json"); this.usernameCacheFile = Paths.get(this.dataDirectory.toString(), "username-cache.json"); this.whitelist = new Whitelist(this.whitelistFile); this.usernameCache = new UsernameCache(this.usernameCacheFile); } public ProxyServer getServer() { return server; } public Logger getLogger() { return logger; } public Path getDataDirectory() { return dataDirectory; } public Path getWhitelistFile() { return whitelistFile; } public Whitelist getWhitelist() { return this.whitelist; } public UsernameCache getUsernameCache() { return this.usernameCache; } public void reloadWhitelist() throws IOException { this.whitelist = new Whitelist(this.whitelistFile); this.usernameCache = new UsernameCache(this.usernameCacheFile); } }
3e0c0b1b1591439b2f149cbe843921916b6ea5d4
557
java
Java
backups/Kotlin-backup/anagram/src/test/java/de/zalando/workshop/TextAnagramTest.java
roskenet/Playground
3cce70eeb38646b0f2ffbd071c3aaec7b8f5b9cb
[ "MIT" ]
null
null
null
backups/Kotlin-backup/anagram/src/test/java/de/zalando/workshop/TextAnagramTest.java
roskenet/Playground
3cce70eeb38646b0f2ffbd071c3aaec7b8f5b9cb
[ "MIT" ]
null
null
null
backups/Kotlin-backup/anagram/src/test/java/de/zalando/workshop/TextAnagramTest.java
roskenet/Playground
3cce70eeb38646b0f2ffbd071c3aaec7b8f5b9cb
[ "MIT" ]
1
2020-10-02T04:57:25.000Z
2020-10-02T04:57:25.000Z
21.423077
58
0.666068
5,105
package de.zalando.workshop; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class TextAnagramTest { @Test void testIsAnagram_true() { Text text = new Text("Suppenwürfel"); boolean result = text.isAnagramTo("Würfelsuppen"); assertThat(result).isEqualTo(true); } @Test void testIsAnagram_false() { Text text = new Text("Bilderrahmen"); boolean result = text.isAnagramTo("Fototapete"); assertThat(result).isEqualTo(false); } }
3e0c0b51b5e532d0697d0c8c790fa34676423bb5
4,928
java
Java
src/main/java/net/stormdev/mario/shop/IconMenu.java
BGHDDevelopment/mariokart-source
91d497f43a55189228b0a09415e34ceef4a56a1e
[ "MIT" ]
null
null
null
src/main/java/net/stormdev/mario/shop/IconMenu.java
BGHDDevelopment/mariokart-source
91d497f43a55189228b0a09415e34ceef4a56a1e
[ "MIT" ]
null
null
null
src/main/java/net/stormdev/mario/shop/IconMenu.java
BGHDDevelopment/mariokart-source
91d497f43a55189228b0a09415e34ceef4a56a1e
[ "MIT" ]
null
null
null
25.271795
72
0.715097
5,106
package net.stormdev.mario.shop; import java.util.Arrays; import java.util.List; import java.util.UUID; import net.stormdev.mario.mariokart.MarioKart; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import com.useful.ucarsCommon.StatValue; public class IconMenu implements Listener { private String name; private int size; private OptionClickEventHandler handler; private Plugin plugin; private String[] optionNames; private ItemStack[] optionIcons; private Boolean enabled = true; private String metaData; private boolean destroyOnExit = false; public IconMenu(String name, int size, OptionClickEventHandler handler, Plugin plugin) { this.name = name; this.size = size; this.handler = handler; this.plugin = plugin; this.optionNames = new String[size]; this.optionIcons = new ItemStack[size]; this.metaData = "menu." + UUID.randomUUID().toString(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } public IconMenu(String name, int size, OptionClickEventHandler handler, Plugin plugin, boolean destroyOnExit) { this(name, size, handler, plugin); this.destroyOnExit = destroyOnExit; } public IconMenu setOption(int position, ItemStack icon, String name, String... info) { optionNames[position] = name; optionIcons[position] = setItemNameAndLore(icon, name, info); return this; } public IconMenu setOption(int position, ItemStack icon, String name, List<String> info) { optionNames[position] = name; optionIcons[position] = setItemNameAndLore(icon, name, info); return this; } public void open(Player player) { Inventory inventory = Bukkit.createInventory(player, size, name); for (int i = 0; i < optionIcons.length; i++) { if (optionIcons[i] != null) { inventory.setItem(i, optionIcons[i]); } } player.openInventory(inventory); player.setMetadata(metaData, new StatValue(null, MarioKart.plugin)); } public void destroy() { HandlerList.unregisterAll(this); handler = null; plugin = null; optionNames = null; optionIcons = null; enabled = false; metaData = null; } @EventHandler void onClose(InventoryCloseEvent event){ if(event.getPlayer().hasMetadata("metaData")){ event.getPlayer().removeMetadata(metaData, plugin); if(destroyOnExit){ destroy(); } } } @EventHandler(priority = EventPriority.MONITOR) void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().getTitle().equals(name) && enabled && event.getWhoClicked().hasMetadata(metaData)) { event.setCancelled(true); int slot = event.getRawSlot(); if (slot >= 0 && slot < size && optionNames[slot] != null) { Plugin plugin = this.plugin; OptionClickEvent e = new OptionClickEvent( (Player) event.getWhoClicked(), slot, optionNames[slot]); handler.onOptionClick(e); if (e.willClose()) { final Player p = (Player) event.getWhoClicked(); Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { @Override public void run() { p.closeInventory(); p.removeMetadata(metaData, MarioKart.plugin); } }, 1); } if (e.willDestroy()) { destroy(); } } } } public interface OptionClickEventHandler { public void onOptionClick(OptionClickEvent event); } public class OptionClickEvent { private Player player; private int position; private String name; private boolean close; private boolean destroy; public OptionClickEvent(Player player, int position, String name) { this.player = player; this.position = position; this.name = name; this.close = true; this.destroy = false; } public Player getPlayer() { return player; } public int getPosition() { return position; } public String getName() { return name; } public boolean willClose() { return close; } public boolean willDestroy() { return destroy; } public void setWillClose(boolean close) { this.close = close; } public void setWillDestroy(boolean destroy) { this.destroy = destroy; } } private ItemStack setItemNameAndLore(ItemStack item, String name, String[] lore) { ItemMeta im = item.getItemMeta(); im.setDisplayName(name); im.setLore(Arrays.asList(lore)); item.setItemMeta(im); return item; } private ItemStack setItemNameAndLore(ItemStack item, String name, List<String> lore) { ItemMeta im = item.getItemMeta(); im.setDisplayName(name); im.setLore(lore); item.setItemMeta(im); return item; } }
3e0c0d0fd4ea80a0cc0fa59353c29c9f72534724
1,856
java
Java
src/tableModel/PersonalCharacteristicsTableModel.java
AAGAraujo/dkds
211243a052e92ec7b74de9594a49841f739b0a3d
[ "MIT" ]
null
null
null
src/tableModel/PersonalCharacteristicsTableModel.java
AAGAraujo/dkds
211243a052e92ec7b74de9594a49841f739b0a3d
[ "MIT" ]
null
null
null
src/tableModel/PersonalCharacteristicsTableModel.java
AAGAraujo/dkds
211243a052e92ec7b74de9594a49841f739b0a3d
[ "MIT" ]
null
null
null
22.361446
85
0.75
5,107
package tableModel; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import model.CulturalPersonalCharacteristic; public class PersonalCharacteristicsTableModel extends AbstractTableModel{ private static final int COL_DESCRIPTION = 0; List<CulturalPersonalCharacteristic> line; private String[] column = new String[]{"Personal Characteristic"}; public PersonalCharacteristicsTableModel(List<CulturalPersonalCharacteristic> cpc) { this.line = new ArrayList<>(cpc); } @Override public int getColumnCount() { return column.length; } @Override public int getRowCount() { return line.size(); } @Override public String getColumnName(int columnIndex) { return column[columnIndex]; } public Class getColumnClass() { return String.class; } public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public Object getValueAt(int rowIndex, int columnIndex) { CulturalPersonalCharacteristic m = line.get(rowIndex); if (columnIndex == COL_DESCRIPTION) { return m.getDescription(); } return ""; } public void setValueAt(Object aValue, int row, int column) { CulturalPersonalCharacteristic u = line.get(row); if (column == COL_DESCRIPTION) { u.setDescription(aValue.toString()); } } public CulturalPersonalCharacteristic getCPC(int index){ return line.get(index); } public void addCPC(CulturalPersonalCharacteristic cpc) { line.add(cpc); int lastIndex = getRowCount() - 1; fireTableRowsInserted(lastIndex, lastIndex); } public void updateCPC(int lineIndex, CulturalPersonalCharacteristic cpc) { line.set(lineIndex, cpc); fireTableRowsUpdated(lineIndex, lineIndex); } public void removeCPC(int lineIndex) { line.remove(lineIndex); fireTableRowsDeleted(lineIndex, lineIndex); } }
3e0c0d149a588f652506ab3e3ae9da53674fc144
401
java
Java
src/activitystreamer/commands/authenticate/AuthenticateCommand.java
jayan2005/four_legs
5801b08bdbbfc1d1369c4db9a8216eaee3650e5b
[ "MIT" ]
null
null
null
src/activitystreamer/commands/authenticate/AuthenticateCommand.java
jayan2005/four_legs
5801b08bdbbfc1d1369c4db9a8216eaee3650e5b
[ "MIT" ]
2
2018-04-07T05:33:09.000Z
2018-04-22T03:36:58.000Z
src/activitystreamer/commands/authenticate/AuthenticateCommand.java
jayan2005/four_legs
5801b08bdbbfc1d1369c4db9a8216eaee3650e5b
[ "MIT" ]
3
2018-04-07T04:53:31.000Z
2018-04-11T03:08:46.000Z
20.05
58
0.793017
5,108
package activitystreamer.commands.authenticate; import activitystreamer.command.Command; import activitystreamer.commands.AbstractCommand; public class AuthenticateCommand extends AbstractCommand { private String secret; public AuthenticateCommand(String secret) { super(Command.Names.AUTHENTICATE.toString()); this.secret = secret; } public String getSecret() { return secret; } }
3e0c0d44b1f901a2e1400ede6e5f5cbcb270e644
1,016
java
Java
PracticalTest02Var05/src/ro/pub/cs/systems/pdsd/practicaltest02var05/PracticalTest02Var05MainActivity.java
FlorinaSpataru/PracticalTest02Var05
66c2e0a9b1e18d94df09dd4b1d810e88578eb66b
[ "Apache-2.0" ]
null
null
null
PracticalTest02Var05/src/ro/pub/cs/systems/pdsd/practicaltest02var05/PracticalTest02Var05MainActivity.java
FlorinaSpataru/PracticalTest02Var05
66c2e0a9b1e18d94df09dd4b1d810e88578eb66b
[ "Apache-2.0" ]
null
null
null
PracticalTest02Var05/src/ro/pub/cs/systems/pdsd/practicaltest02var05/PracticalTest02Var05MainActivity.java
FlorinaSpataru/PracticalTest02Var05
66c2e0a9b1e18d94df09dd4b1d810e88578eb66b
[ "Apache-2.0" ]
null
null
null
29.028571
74
0.772638
5,109
package ro.pub.cs.systems.pdsd.practicaltest02var05; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class PracticalTest02Var05MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_practical_test02_var05_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.practical_test02_var05_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
3e0c0d7292911781c3104b9abe0ba2e250853860
2,258
java
Java
arcusApp/app/src/main/java/arcus/app/subsystems/alarm/promonitoring/models/AlarmStatusModel.java
pupper68k/arcusandroid
50e0a6d71609bf404353da80d8e620584cc818d3
[ "Apache-2.0" ]
30
2019-03-01T01:25:19.000Z
2020-09-12T02:27:22.000Z
arcusApp/app/src/main/java/arcus/app/subsystems/alarm/promonitoring/models/AlarmStatusModel.java
pupper68k/arcusandroid
50e0a6d71609bf404353da80d8e620584cc818d3
[ "Apache-2.0" ]
21
2019-09-16T07:37:00.000Z
2020-04-30T05:00:06.000Z
arcusApp/app/src/main/java/arcus/app/subsystems/alarm/promonitoring/models/AlarmStatusModel.java
pupper68k/arcusandroid
50e0a6d71609bf404353da80d8e620584cc818d3
[ "Apache-2.0" ]
29
2019-03-09T00:24:20.000Z
2021-01-07T14:34:03.000Z
28.948718
76
0.659876
5,110
/* * Copyright 2019 Arcus Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package arcus.app.subsystems.alarm.promonitoring.models; public abstract class AlarmStatusModel { private final int iconResourceId; private final String alarmTypeString; private boolean isProMonitored; public AlarmStatusModel(int iconResourceId, String alarmTypeString) { this.iconResourceId = iconResourceId; this.alarmTypeString = alarmTypeString; } public int getIconResourceId() { return this.iconResourceId; } public String getAlarmTypeString() { return this.alarmTypeString; } public boolean isProMonitored() { return isProMonitored; } public void setProMonitored(boolean proMonitored) { isProMonitored = proMonitored; } @Override public String toString() { return "AlarmStatusModel{" + "iconResourceId=" + iconResourceId + ", alarmTypeString='" + alarmTypeString + '\'' + ", isProMonitored=" + isProMonitored + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AlarmStatusModel)) return false; AlarmStatusModel that = (AlarmStatusModel) o; if (iconResourceId != that.iconResourceId) return false; if (isProMonitored != that.isProMonitored) return false; return alarmTypeString.equals(that.alarmTypeString); } @Override public int hashCode() { int result = iconResourceId; result = 31 * result + alarmTypeString.hashCode(); result = 31 * result + (isProMonitored ? 1 : 0); return result; } }
3e0c0da230e03631fc64fa290fc4c3502fad1d36
11,661
java
Java
src/org/primaresearch/clc/phd/repository/search/LabellableObjectFilter.java
PRImA-Research-Lab/semantic-labelling
5bbe439e1c25231758b6d28138fe6294fbd2823e
[ "Apache-2.0" ]
11
2018-03-02T07:34:50.000Z
2021-09-17T16:49:31.000Z
src/org/primaresearch/clc/phd/repository/search/LabellableObjectFilter.java
PRImA-Research-Lab/semantic-labelling
5bbe439e1c25231758b6d28138fe6294fbd2823e
[ "Apache-2.0" ]
1
2018-10-18T12:28:07.000Z
2018-10-18T12:28:07.000Z
src/org/primaresearch/clc/phd/repository/search/LabellableObjectFilter.java
PRImA-Research-Lab/semantic-labelling
5bbe439e1c25231758b6d28138fe6294fbd2823e
[ "Apache-2.0" ]
5
2018-04-04T13:27:27.000Z
2021-09-17T16:50:59.000Z
33.702312
173
0.709973
5,111
package org.primaresearch.clc.phd.repository.search; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.primaresearch.clc.phd.ontology.label.HasLabels; import org.primaresearch.clc.phd.ontology.label.Label; import org.primaresearch.clc.phd.ontology.label.LabelGroup; import org.primaresearch.clc.phd.ontology.label.LabelType; /** * Filter for objects that have labels. * * @author clc * */ public class LabellableObjectFilter implements Filter { private Collection<LabelGroup> rootLabels; /** Map [Label type ID, filter element] */ private Map<String, LabelFilterElement> labelFilterElements = new HashMap<String, LabelFilterElement>(); private Collection<FilterChangeListener> listeners = new LinkedList<FilterChangeListener>(); /** * Constructor * @param rootLabels Root label types to be used for this filter (other types will be ignored) */ public LabellableObjectFilter(Collection<LabelGroup> rootLabels) { this.rootLabels = rootLabels; for (Iterator<LabelGroup> it = rootLabels.iterator(); it.hasNext(); ) initLabelFilterElements(it.next().getType(), null); } public void addListener(FilterChangeListener listener) { listeners.add(listener); } public void removeListener(FilterChangeListener listener) { listeners.remove(listener); } private void notifyListeners() { for (Iterator<FilterChangeListener> it = listeners.iterator(); it.hasNext(); ) it.next().filterChanged(this); } /** * Returns a list of all objects from the input list that apply to this label filter. * Also refreshes the counts of the internal filter elements (number of objects per label). * @param toBeFiltered Input objects * @return A new list */ public List<HasLabels> filterObjects(Collection<HasLabels> toBeFiltered) { return filterAndCountObjects(toBeFiltered, true); } /** * Refreshes the counts of the internal filter elements (number of objects per label). * @param objectsWithLabels Input objects */ public void countObjects(Collection<HasLabels> objectsWithLabels) { filterAndCountObjects(objectsWithLabels, false); } /** * Returns a list of all objects from the input list that apply to this label filter. * Also refreshes the counts of the internal filter elements (number of objects per label). * @param toBeFiltered Input objects * @param doFilter If set to false, the filter is not applied to the input list * @return A new list */ private List<HasLabels> filterAndCountObjects(Collection<HasLabels> toBeFiltered, boolean doFilter) { resetCounts(); List<HasLabels> filtered = new LinkedList<HasLabels>(); for (Iterator<HasLabels> it = toBeFiltered.iterator(); it.hasNext(); ) { HasLabels obj = it.next(); Collection<LabelGroup> labelGroups = obj.getLabels(); if (labelGroups != null) { for (Iterator<LabelGroup> itLabelGroups = labelGroups.iterator(); itLabelGroups.hasNext(); ) { LabelGroup labelGroup = itLabelGroups.next(); if (labelGroup.getLabels() == null) continue; for (Iterator<Label> itLabels = labelGroup.getLabels().iterator(); itLabels.hasNext(); ) { Label label = itLabels.next(); LabelFilterElement LabelFilterElement = labelFilterElements.get(label.getType().getId()); if (LabelFilterElement == null || !LabelFilterElement.isEnabled()) { //If there's no filter element for this label or //the filter element is disabled then this filter //does not cover the labels' root type. In that case //we have to add the object to the result list. if (doFilter) filtered.add(obj); } else { //if (LabelFilterElement != null) //Count LabelFilterElement.setCount(LabelFilterElement.getCount()+1); //LabelFilterElement.addMatchingObject(obj); //Filter if (doFilter) { if (LabelFilterElement.isSelected()) filtered.add(obj); } } } } } } return filtered; } /** * Checks a group of objects if they go through or are filtered out all together. * @param objects Group of objects with labels * @return True if the group would go through and not be filtered out */ public boolean filterAsGroup(Collection<HasLabels> objects, Object groupParent) { if (objects == null) return true; boolean objectsGoThrough = true; if (objects.isEmpty()) { //Filter out objects with no labels as soon as one filter element is selected for (Iterator<String> it = labelFilterElements.keySet().iterator(); it.hasNext(); ) { String labelTypeId = it.next(); LabelFilterElement LabelFilterElement = labelFilterElements.get(labelTypeId); if (LabelFilterElement.isEnabled() && LabelFilterElement.isSelected()) { objectsGoThrough = false; break; } } } else { //Go through all filter elements for (Iterator<String> it = labelFilterElements.keySet().iterator(); it.hasNext(); ) { String labelTypeId = it.next(); LabelFilterElement LabelFilterElement = labelFilterElements.get(labelTypeId); if (!LabelFilterElement.isEnabled()) continue; //Now check all objects of the given group if (checkGroupForOneLabel(objects,labelTypeId)) { //LabelFilterElement.setCount(LabelFilterElement.getCount()+1); //LabelFilterElement.addMatchingObject(groupParent); } else { if (LabelFilterElement.isSelected()) objectsGoThrough = false; } } } return objectsGoThrough; } /** * Checks if at least one member of a group of objects has a specific label. * @param objects Group of objects with labels * @param labelTypeToUse Label type ID * @return <code>true</code> if at least one of the given objects has a label of the specified type */ private boolean checkGroupForOneLabel(Collection<HasLabels> objects, String labelTypeToUse) { for (Iterator<HasLabels> it = objects.iterator(); it.hasNext(); ) { HasLabels obj = it.next(); Collection<LabelGroup> labelGroups = obj.getLabels(); if (labelGroups != null) { for (Iterator<LabelGroup> itLabelGroups = labelGroups.iterator(); itLabelGroups.hasNext(); ) { LabelGroup labelGroup = itLabelGroups.next(); if (labelGroup.getLabels() == null) continue; for (Iterator<Label> itLabels = labelGroup.getLabels().iterator(); itLabels.hasNext(); ) { Label label = itLabels.next(); //if (label.getType().getId().equals(labelTypeToUse)) { if (label.getType().getId().startsWith(labelTypeToUse)) { //Type or one one of it's subtypes return true; } } } } } return false; } /** * Updates the counters for all label types * Should be used in conjunction with <code>resetCounts()</code> * @param objects Group of objects with labels */ public void countAsGroup(Collection<HasLabels> objects, Object groupParent) { if (objects == null || objects.isEmpty()) return; //Go through all filter elements for (Iterator<String> it = labelFilterElements.keySet().iterator(); it.hasNext(); ) { String labelTypeId = it.next(); LabelFilterElement LabelFilterElement = labelFilterElements.get(labelTypeId); if (!LabelFilterElement.isEnabled()) continue; //Now check all objects of the given group if (checkGroupForOneLabel(objects,labelTypeId)) { LabelFilterElement.setCount(LabelFilterElement.getCount()+1); } } } /** * Returns the selection state of this filter for the given label type. * @return <code>true</code> if this filter does let through objects with the given type; <code>false</code> if objects are filtered out. */ public boolean isLabelTypeSelected(LabelType labelType) { LabelFilterElement LabelFilterElement = labelFilterElements.get(labelType.getId()); if (LabelFilterElement == null) //Filter does not cover the type return true; return LabelFilterElement.isSelected(); } public void setLabelTypeSelected(LabelType labelType, boolean selected) { LabelFilterElement LabelFilterElement = labelFilterElements.get(labelType.getId()); if (LabelFilterElement == null) //Filter does not cover the type return; boolean changed = LabelFilterElement.isSelected() != selected; LabelFilterElement.setSelected(selected); if (changed) notifyListeners(); } /** * Returns the enabled state of this filter for the given label type. * @return <code>true</code> if enabled; <code>false</code> otherwise. */ public boolean isLabelTypeEnabled(LabelType labelType) { LabelFilterElement LabelFilterElement = labelFilterElements.get(labelType.getId()); if (LabelFilterElement == null) //Filter does not cover the type return false; return LabelFilterElement.isEnabled(); } /** * Returns the number of objects with the given this filter lets through. * @return Number of objects from last count (calls to <code>filterObjects</code> or <code>countObjects</code>). Returns -1 if the label type is not covered by this filter. */ public int getObjectCount(LabelType labelType) { LabelFilterElement LabelFilterElement = labelFilterElements.get(labelType.getId()); if (LabelFilterElement == null) //Filter does not cover the type return -1; return LabelFilterElement.getCount(); } /** * Sets the count of each filter element to zero. */ public void resetCounts() { for (Iterator<LabelFilterElement> it = labelFilterElements.values().iterator(); it.hasNext(); ) //it.next().resetMatchingObjects(); it.next().setCount(0); } /** * Recursively creates filter elements for the given label type and its children */ private void initLabelFilterElements(LabelType labelType, LabelFilterElement parent) { if (labelType == null) return; LabelFilterElement el = new LabelFilterElement(parent); labelFilterElements.put(labelType.getId(), el); //Children if (labelType.getChildren() != null) { for (Iterator<LabelType> it = labelType.getChildren().iterator(); it.hasNext(); ) { initLabelFilterElements(it.next(), el); } } } /** * Returns the root label types of this filter (other label types are ignored when applying the filter). */ public Collection<LabelGroup> getRootLabels() { return rootLabels; } /** * Initialises the filter (filtering should let through all objects) * @param allWorkflows Unfiltered list of objects */ public void init(Collection<HasLabels> allObjects) { //Collect all label types of the given objects Set<String> foundLabelTypes = new HashSet<String>(); //Set of type IDs for (Iterator<HasLabels> it = allObjects.iterator(); it.hasNext(); ) { HasLabels objectWithLabels = it.next(); if (objectWithLabels == null) continue; for (Iterator<LabelGroup> itLabelGroups = objectWithLabels.getLabels().iterator(); itLabelGroups.hasNext(); ) { LabelGroup grp = itLabelGroups.next(); if (grp == null) continue; for (Iterator<Label> itLabels = grp.getLabels().iterator(); itLabels.hasNext(); ) foundLabelTypes.add(itLabels.next().getType().getId()); } } //Enable all filter elements that correspond with the found label types // Go through all filter elements for (Iterator<String> it = labelFilterElements.keySet().iterator(); it.hasNext(); ) { String labelTypeId = it.next(); LabelFilterElement labelFilterElement = labelFilterElements.get(labelTypeId); if (foundLabelTypes.contains(labelTypeId)) labelFilterElement.setEnabled(true); } } }
3e0c0ed9e45596b83f68f8fb2d504093e44522bf
17,649
java
Java
app/src/main/java/i2p/bote/android/util/ViewAddressFragment.java
i2p/i2p.i2p-bote.android
69c8c017f1c74cc2e168a60a5689f08f742796d3
[ "Apache-2.0", "CC-BY-4.0" ]
17
2015-03-14T20:26:40.000Z
2022-03-25T22:57:19.000Z
app/src/main/java/i2p/bote/android/util/ViewAddressFragment.java
i2p/i2p.i2p-bote.android
69c8c017f1c74cc2e168a60a5689f08f742796d3
[ "Apache-2.0", "CC-BY-4.0" ]
4
2015-01-23T07:17:03.000Z
2017-04-21T23:21:05.000Z
app/src/main/java/i2p/bote/android/util/ViewAddressFragment.java
i2p/i2p.i2p-bote.android
69c8c017f1c74cc2e168a60a5689f08f742796d3
[ "Apache-2.0", "CC-BY-4.0" ]
6
2015-05-31T16:56:34.000Z
2020-12-06T15:56:24.000Z
42.021429
127
0.594595
5,112
package i2p.bote.android.util; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.Rect; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.DecelerateInterpolator; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.animation.AnimatorSet; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.view.ViewHelper; import i2p.bote.android.Constants; import i2p.bote.android.R; public abstract class ViewAddressFragment extends Fragment { public static final String ADDRESS = "address"; protected String mAddress; Toolbar mToolbar; protected ImageView mPicture; protected TextView mPublicName; protected TextView mDescription; protected TextView mCryptoImplName; TextView mAddressField; ImageView mAddressQrCode; TextView mFingerprint; ImageView mExpandedQrCode; // Hold a reference to the current animator, // so that it can be canceled mid-way. private Animator mQrCodeAnimator; // The system "short" animation time duration, in milliseconds. This // duration is ideal for subtle animations or animations that occur // very frequently. private int mShortAnimationDuration; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); mAddress = getArguments().getString(ADDRESS); // Retrieve and cache the system's default "short" animation time. mShortAnimationDuration = getResources().getInteger( android.R.integer.config_shortAnimTime); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_view_address, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mToolbar = (Toolbar) view.findViewById(R.id.main_toolbar); mPicture = (ImageView) view.findViewById(R.id.picture); mPublicName = (TextView) view.findViewById(R.id.public_name); mDescription = (TextView) view.findViewById(R.id.description); mFingerprint = (TextView) view.findViewById(R.id.fingerprint); mCryptoImplName = (TextView) view.findViewById(R.id.crypto_impl_name); mAddressField = (TextView) view.findViewById(R.id.email_dest); mAddressQrCode = (ImageView) view.findViewById(R.id.email_dest_qr_code); mExpandedQrCode = (ImageView) view.findViewById(R.id.expanded_qr_code); view.findViewById(R.id.copy_key).setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View view) { Object clipboardService = getActivity().getSystemService(Context.CLIPBOARD_SERVICE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) clipboardService; clipboard.setText(mAddress); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) clipboardService; android.content.ClipData clip = android.content.ClipData.newPlainText( getString(R.string.bote_dest_for, getPublicName()), mAddress); clipboard.setPrimaryClip(clip); } Toast.makeText(getActivity(), R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } }); if (mAddress != null) { loadAddress(); } else { // No address provided, finish // Should not happen getActivity().setResult(Activity.RESULT_CANCELED); getActivity().finish(); } } protected abstract void loadAddress(); protected abstract String getPublicName(); protected abstract int getDeleteAddressMessage(); protected abstract void onEditAddress(); protected abstract void onDeleteAddress(); @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); AppCompatActivity activity = ((AppCompatActivity) getActivity()); // Set the action bar activity.setSupportActionBar(mToolbar); // Enable ActionBar app icon to behave as action to go back activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void onResume() { super.onResume(); mAddressField.setText(mAddress); mAddressQrCode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { zoomQrCode(); } }); loadQrCode(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.view_address, menu); menu.findItem(R.id.action_edit_address).setIcon(BoteHelper.getMenuIcon(getActivity(), GoogleMaterial.Icon.gmd_create)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_edit_address: onEditAddress(); return true; case R.id.action_delete_address: DialogFragment df = new DialogFragment() { @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(getDeleteAddressMessage()) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); onDeleteAddress(); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); return builder.create(); } }; df.show(getActivity().getSupportFragmentManager(), "deleteaddress"); return true; default: return super.onOptionsItemSelected(item); } } public NdefMessage createNdefMessage() { return new NdefMessage(new NdefRecord[]{ createNameRecord(), createDestinationRecord() }); } private NdefRecord createNameRecord() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) return new NdefRecord( NdefRecord.TNF_EXTERNAL_TYPE, "i2p.bote:contact".getBytes(), new byte[0], getPublicName().getBytes() ); else return NdefRecord.createExternal( "i2p.bote", "contact", getPublicName().getBytes() ); } private NdefRecord createDestinationRecord() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) return new NdefRecord( NdefRecord.TNF_EXTERNAL_TYPE, "i2p.bote:contactDestination".getBytes(), new byte[0], mAddress.getBytes() ); else return NdefRecord.createExternal( "i2p.bote", "contactDestination", mAddress.getBytes() ); } /** * Load QR Code asynchronously and with a fade in animation */ private void loadQrCode() { AsyncTask<Void, Void, Bitmap[]> loadTask = new AsyncTask<Void, Void, Bitmap[]>() { protected Bitmap[] doInBackground(Void... unused) { String qrCodeContent = Constants.EMAILDEST_SCHEME + ":" + mAddress; // render with minimal size Bitmap qrCode = QrCodeUtils.getQRCodeBitmap(qrCodeContent, 0); Bitmap[] scaled = new Bitmap[2]; // scale the image up to our actual size. we do this in code rather // than let the ImageView do this because we don't require filtering. int size = getResources().getDimensionPixelSize(R.dimen.qr_code_size); scaled[0] = Bitmap.createScaledBitmap(qrCode, size, size, false); // scale for the expanded image DisplayMetrics dm = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); int smallestDimen = Math.min(dm.widthPixels, dm.heightPixels); scaled[1] = Bitmap.createScaledBitmap(qrCode, smallestDimen, smallestDimen, false); return scaled; } protected void onPostExecute(Bitmap[] scaled) { // only change view, if fragment is attached to activity if (ViewAddressFragment.this.isAdded()) { mAddressQrCode.setImageBitmap(scaled[0]); mExpandedQrCode.setImageBitmap(scaled[1]); // simple fade-in animation AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(200); mAddressQrCode.startAnimation(anim); } } }; loadTask.execute(); } private void zoomQrCode() { // If there's an animation in progress, cancel it // immediately and proceed with this one. if (mQrCodeAnimator != null) { mQrCodeAnimator.cancel(); } // Calculate the starting and ending bounds for the zoomed-in image. // This step involves lots of math. Yay, math. final Rect startBounds = new Rect(); final Rect finalBounds = new Rect(); final Point globalOffset = new Point(); // The start bounds are the global visible rectangle of the thumbnail, // and the final bounds are the global visible rectangle of the container // view. Also set the container view's offset as the origin for the // bounds, since that's the origin for the positioning animation // properties (X, Y). mAddressQrCode.getGlobalVisibleRect(startBounds); getActivity().findViewById(R.id.container) .getGlobalVisibleRect(finalBounds, globalOffset); startBounds.offset(-globalOffset.x, -globalOffset.y); finalBounds.offset(-globalOffset.x, -globalOffset.y); // Adjust the start bounds to be the same aspect ratio as the final // bounds using the "center crop" technique. This prevents undesirable // stretching during the animation. Also calculate the start scaling // factor (the end scaling factor is always 1.0). float startScale; if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds.width() / startBounds.height()) { // Extend start bounds horizontally startScale = (float) startBounds.height() / finalBounds.height(); float startWidth = startScale * finalBounds.width(); float deltaWidth = (startWidth - startBounds.width()) / 2; startBounds.left -= deltaWidth; startBounds.right += deltaWidth; } else { // Extend start bounds vertically startScale = (float) startBounds.width() / finalBounds.width(); float startHeight = startScale * finalBounds.height(); float deltaHeight = (startHeight - startBounds.height()) / 2; startBounds.top -= deltaHeight; startBounds.bottom += deltaHeight; } // Hide the thumbnail and show the zoomed-in view. When the animation // begins, it will position the zoomed-in view in the place of the // thumbnail. ViewHelper.setAlpha(mAddressQrCode, 0f); mExpandedQrCode.setVisibility(View.VISIBLE); // Set the pivot point for SCALE_X and SCALE_Y transformations // to the top-left corner of the zoomed-in view (the default // is the center of the view). ViewHelper.setPivotX(mExpandedQrCode, 0f); ViewHelper.setPivotY(mExpandedQrCode, 0f); // Construct and run the parallel animation of the four translation and // scale properties (X, Y, SCALE_X, and SCALE_Y). AnimatorSet set = new AnimatorSet(); set .play(ObjectAnimator.ofFloat(mExpandedQrCode, "x", startBounds.left, finalBounds.left)) .with(ObjectAnimator.ofFloat(mExpandedQrCode, "y", startBounds.top, finalBounds.top)) .with(ObjectAnimator.ofFloat(mExpandedQrCode, "scaleX", startScale, 1f)) .with(ObjectAnimator.ofFloat(mExpandedQrCode, "scaleY", startScale, 1f)); set.setDuration(mShortAnimationDuration); set.setInterpolator(new DecelerateInterpolator()); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mQrCodeAnimator = null; } @Override public void onAnimationCancel(Animator animation) { mQrCodeAnimator = null; } }); set.start(); mQrCodeAnimator = set; // Upon clicking the zoomed-in image, it should zoom back down // to the original bounds and show the thumbnail instead of // the expanded image. final float startScaleFinal = startScale; mExpandedQrCode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mQrCodeAnimator != null) { mQrCodeAnimator.cancel(); } // Animate the four positioning/sizing properties in parallel, // back to their original values. AnimatorSet set = new AnimatorSet(); set.play(ObjectAnimator .ofFloat(mExpandedQrCode, "x", startBounds.left)) .with(ObjectAnimator .ofFloat(mExpandedQrCode, "y", startBounds.top)) .with(ObjectAnimator .ofFloat(mExpandedQrCode, "scaleX", startScaleFinal)) .with(ObjectAnimator .ofFloat(mExpandedQrCode, "scaleY", startScaleFinal)); set.setDuration(mShortAnimationDuration); set.setInterpolator(new DecelerateInterpolator()); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ViewHelper.setAlpha(mAddressQrCode, 1f); mExpandedQrCode.setVisibility(View.GONE); mExpandedQrCode.setClickable(false); mQrCodeAnimator = null; } @Override public void onAnimationCancel(Animator animation) { ViewHelper.setAlpha(mAddressQrCode, 1f); mExpandedQrCode.setVisibility(View.GONE); mExpandedQrCode.setClickable(false); mQrCodeAnimator = null; } }); set.start(); mQrCodeAnimator = set; } }); } }
3e0c0f5adb84dd96a94ed28fbec221b241771ce5
24,216
java
Java
platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
null
null
null
platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
null
null
null
35.044863
153
0.702593
5,113
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileChooser.ex; import com.intellij.ide.IdeBundle; import com.intellij.ide.PasteProvider; import com.intellij.ide.SaveAndSyncHandler; import com.intellij.ide.dnd.FileCopyPasteUtil; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.treeView.NodeRenderer; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationActivationListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.fileChooser.*; import com.intellij.openapi.fileChooser.impl.FileChooserFactoryImpl; import com.intellij.openapi.fileChooser.impl.FileChooserUtil; import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.SideBorder; import com.intellij.ui.SimpleListCellRenderer; import com.intellij.ui.UIBundle; import com.intellij.ui.components.labels.LinkLabel; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.Consumer; import com.intellij.util.IconUtil; import com.intellij.util.io.URLUtil; import com.intellij.util.ui.EmptyIcon; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.UiNotifyConnector; import com.intellij.util.ui.update.Update; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.datatransfer.Transferable; import java.io.File; import java.nio.file.Paths; import java.util.List; import java.util.*; import java.util.function.Supplier; public class FileChooserDialogImpl extends DialogWrapper implements FileChooserDialog, PathChooserDialog, FileLookup { @NonNls public static final String FILE_CHOOSER_SHOW_PATH_PROPERTY = "FileChooser.ShowPath"; private static final String RECENT_FILES_KEY = "file.chooser.recent.files"; public static final @NotNull Supplier<@Nls String> DRAG_N_DROP_HINT = IdeBundle.messagePointer("tooltip.drag.drop.file"); private final FileChooserDescriptor myChooserDescriptor; protected FileSystemTreeImpl myFileSystemTree; private Project myProject; private VirtualFile[] myChosenFiles = VirtualFile.EMPTY_ARRAY; private JPanel myNorthPanel; private TextFieldAction myTextFieldAction; protected FileTextFieldImpl myPathTextField; private ComboBox<String> myPath; private MergingUpdateQueue myUiUpdater; private boolean myTreeIsUpdating; private static final DataKey<PathField> PATH_FIELD = DataKey.create("PathField"); public FileChooserDialogImpl(@NotNull final FileChooserDescriptor descriptor, @Nullable Project project) { super(project, true); myChooserDescriptor = descriptor; myProject = project; setTitle(getChooserTitle(descriptor)); } public FileChooserDialogImpl(@NotNull final FileChooserDescriptor descriptor, @NotNull Component parent) { this(descriptor, parent, null); } public FileChooserDialogImpl(@NotNull final FileChooserDescriptor descriptor, @NotNull Component parent, @Nullable Project project) { super(parent, true); myChooserDescriptor = descriptor; myProject = project; setTitle(getChooserTitle(descriptor)); } private static @NlsContexts.DialogTitle String getChooserTitle(final FileChooserDescriptor descriptor) { final String title = descriptor.getTitle(); return title != null ? title : UIBundle.message("file.chooser.default.title"); } @Override public VirtualFile @NotNull [] choose(@Nullable final Project project, final VirtualFile @NotNull ... toSelect) { init(); if (myProject == null && project != null) { myProject = project; } if (toSelect.length == 1) { restoreSelection(toSelect[0]); } else if (toSelect.length == 0) { restoreSelection(null); // select last opened file } else { selectInTree(toSelect, true, true); } show(); return myChosenFiles; } @Override public VirtualFile @NotNull [] choose(@Nullable final VirtualFile toSelect, @Nullable final Project project) { if (toSelect == null) { return choose(project); } return choose(project, toSelect); } @Override public void choose(@Nullable VirtualFile toSelect, @NotNull Consumer<? super List<VirtualFile>> callback) { init(); restoreSelection(toSelect); show(); if (myChosenFiles.length > 0) { callback.consume(Arrays.asList(myChosenFiles)); } else if (callback instanceof FileChooser.FileChooserConsumer) { ((FileChooser.FileChooserConsumer)callback).cancelled(); } } protected void restoreSelection(@Nullable VirtualFile toSelect) { final VirtualFile lastOpenedFile = FileChooserUtil.getLastOpenedFile(myProject); final VirtualFile file = FileChooserUtil.getFileToSelect(myChooserDescriptor, myProject, toSelect, lastOpenedFile); if (file != null && file.isValid()) { myPathTextField.setText(VfsUtil.getReadableUrl(file), true, () -> selectInTree(new VirtualFile[]{file}, false, false)); } } void storeSelection(@Nullable VirtualFile file) { if (file != null) { Pair<String, String> pair = file.getFileSystem().getProtocol() == StandardFileSystems.JAR_PROTOCOL ? URLUtil.splitJarUrl(file.getPath()) : null; FileChooserUtil.setLastOpenedFile(myProject, pair == null ? file.toNioPath() : Paths.get(pair.getFirst())); } if (file != null && file.getFileSystem() instanceof LocalFileSystem) { saveRecent(file.getPath()); } } private void saveRecent(String path) { List<String> files = new ArrayList<>(Arrays.asList(getRecentFiles())); files.remove(path); files.add(0, path); while (files.size() > 30) { files.remove(files.size() - 1); } PropertiesComponent.getInstance().setValues(RECENT_FILES_KEY, ArrayUtilRt.toStringArray(files)); } private String @NotNull [] getRecentFiles() { String[] array = PropertiesComponent.getInstance().getValues(RECENT_FILES_KEY); if (array == null) { return ArrayUtil.EMPTY_STRING_ARRAY; } if (array.length > 0 && myPathTextField != null && myPathTextField.getField().getText().replace('\\', '/').equals(array[0])) { return Arrays.copyOfRange(array, 1, array.length); } return array; } protected DefaultActionGroup createActionGroup() { registerTreeActionShortcut("FileChooser.Delete"); registerTreeActionShortcut("FileChooser.Refresh"); return (DefaultActionGroup)ActionManager.getInstance().getAction("FileChooserToolbar"); } private void registerTreeActionShortcut(@NonNls final String actionId) { final JTree tree = myFileSystemTree.getTree(); final AnAction action = ActionManager.getInstance().getAction(actionId); action.registerCustomShortcutSet(action.getShortcutSet(), tree, myDisposable); } @Override @Nullable protected final JComponent createTitlePane() { final String description = myChooserDescriptor.getDescription(); if (StringUtil.isEmptyOrSpaces(description)) return null; final JLabel label = new JLabel(description); label.setBorder(BorderFactory.createCompoundBorder( new SideBorder(UIUtil.getPanelBackground().darker(), SideBorder.BOTTOM), JBUI.Borders.empty(0, 5, 10, 5))); return label; } @Override protected JComponent createCenterPanel() { JPanel panel = new MyPanel(); myUiUpdater = new MergingUpdateQueue("FileChooserUpdater", 200, false, panel); Disposer.register(myDisposable, myUiUpdater); new UiNotifyConnector(panel, myUiUpdater); panel.setBorder(JBUI.Borders.empty()); createTree(); final DefaultActionGroup group = createActionGroup(); ActionToolbar toolBar = ActionManager.getInstance().createActionToolbar("FileChooserDialog", group, true); toolBar.setTargetComponent(panel); final JPanel toolbarPanel = new JPanel(new BorderLayout()); toolbarPanel.add(toolBar.getComponent(), BorderLayout.CENTER); myTextFieldAction = new TextFieldAction() { @Override public void linkSelected(final LinkLabel aSource, final Object aLinkData) { toggleShowTextField(); } }; toolbarPanel.add(myTextFieldAction, BorderLayout.EAST); JPanel extraToolbarPanel = createExtraToolbarPanel(); if(extraToolbarPanel != null){ toolbarPanel.add(extraToolbarPanel, BorderLayout.SOUTH); } myPath = new ComboBox<>(getRecentFiles()); myPath.setEditable(true); myPath.setRenderer(SimpleListCellRenderer.create((var label, @NlsContexts.Label var value, var index) -> { label.setText(value); VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(new File(value)); label.setIcon(file == null ? EmptyIcon.ICON_16 : IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, null)); })); myPathTextField = new FileTextFieldImpl.Vfs( (JTextField)myPath.getEditor().getEditorComponent(), FileChooserFactoryImpl.getMacroMap(), getDisposable(), new LocalFsFinder.FileChooserFilter(myChooserDescriptor, myFileSystemTree)) { @Override protected void onTextChanged(final String newValue) { myUiUpdater.cancelAllUpdates(); updateTreeFromPath(newValue); } }; Disposer.register(myDisposable, myPathTextField); myNorthPanel = new JPanel(new BorderLayout()); myNorthPanel.add(toolbarPanel, BorderLayout.NORTH); updateTextFieldShowing(); panel.add(myNorthPanel, BorderLayout.NORTH); registerMouseListener(group); JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myFileSystemTree.getTree()); panel.add(scrollPane, BorderLayout.CENTER); panel.setPreferredSize(JBUI.size(400)); JLabel dndLabel = new JLabel(DRAG_N_DROP_HINT.get(), SwingConstants.CENTER); dndLabel.setFont(JBUI.Fonts.miniFont()); dndLabel.setForeground(UIUtil.getLabelDisabledForeground()); panel.add(dndLabel, BorderLayout.SOUTH); ApplicationManager.getApplication().getMessageBus().connect(getDisposable()) .subscribe(ApplicationActivationListener.TOPIC, new ApplicationActivationListener() { @Override public void applicationActivated(@NotNull IdeFrame ideFrame) { SaveAndSyncHandler.getInstance().maybeRefresh(ModalityState.current()); } }); return panel; } @Nullable protected JPanel createExtraToolbarPanel() { return null; } @Override public JComponent getPreferredFocusedComponent() { if (isToShowTextField()) { return myPathTextField != null ? myPathTextField.getField() : null; } else { return myFileSystemTree != null ? myFileSystemTree.getTree() : null; } } @Override public final void dispose() { LocalFileSystem.getInstance().removeWatchedRoots(myRequests.values()); super.dispose(); } private boolean isTextFieldActive() { return myPathTextField.getField().getRootPane() != null; } @Override protected void doOKAction() { if (!isOKActionEnabled()) { return; } if (isTextFieldActive()) { final String text = myPathTextField.getTextFieldText(); final LookupFile file = myPathTextField.getFile(); if (text == null || file == null || !file.exists()) { setErrorText(IdeBundle.message("dialog.message.specified.path.cannot.be.found"), myPathTextField.getField()); return; } } final List<VirtualFile> selectedFiles = Arrays.asList(getSelectedFilesInt()); final VirtualFile[] files = VfsUtilCore.toVirtualFileArray(FileChooserUtil.getChosenFiles(myChooserDescriptor, selectedFiles)); if (files.length == 0) { myChosenFiles = VirtualFile.EMPTY_ARRAY; close(CANCEL_EXIT_CODE); return; } try { myChooserDescriptor.validateSelectedFiles(files); } catch (Exception e) { Messages.showErrorDialog(getContentPane(), e.getMessage(), getTitle()); return; } myChosenFiles = files; storeSelection(files[files.length - 1]); super.doOKAction(); } @Override public final void doCancelAction() { myChosenFiles = VirtualFile.EMPTY_ARRAY; super.doCancelAction(); } protected JTree createTree() { Tree internalTree = createInternalTree(); myFileSystemTree = new FileSystemTreeImpl(myProject, myChooserDescriptor, internalTree, null, null, null); internalTree.setRootVisible(myChooserDescriptor.isTreeRootVisible()); internalTree.setShowsRootHandles(true); Disposer.register(myDisposable, myFileSystemTree); myFileSystemTree.addOkAction(this::doOKAction); JTree tree = myFileSystemTree.getTree(); if (!Registry.is("file.chooser.async.tree.model")) tree.setCellRenderer(new NodeRenderer()); tree.getSelectionModel().addTreeSelectionListener(new FileTreeSelectionListener()); tree.addTreeExpansionListener(new FileTreeExpansionListener()); setOKActionEnabled(false); myFileSystemTree.addListener(selection -> { // myTreeIsUpdating makes no sense for AsyncTreeModel if (myTreeIsUpdating && myFileSystemTree.getTreeBuilder() == null) myTreeIsUpdating = false; updatePathFromTree(selection, false); }, myDisposable); new FileDrop(tree, new FileDrop.Target() { @Override public FileChooserDescriptor getDescriptor() { return myChooserDescriptor; } @Override public boolean isHiddenShown() { return myFileSystemTree.areHiddensShown(); } @Override public void dropFiles(final List<VirtualFile> files) { if (!myChooserDescriptor.isChooseMultiple() && !files.isEmpty()) { selectInTree(new VirtualFile[]{files.get(0)}, true, true); } else { selectInTree(VfsUtilCore.toVirtualFileArray(files), true, true); } } }); return tree; } @NotNull protected Tree createInternalTree() { return new Tree(); } private void registerMouseListener(final ActionGroup group) { myFileSystemTree.registerMouseListener(group); } private VirtualFile[] getSelectedFilesInt() { if (myTreeIsUpdating || !myUiUpdater.isEmpty()) { if (isTextFieldActive() && !StringUtil.isEmpty(myPathTextField.getTextFieldText())) { LookupFile toFind = myPathTextField.getFile(); if (toFind instanceof LocalFsFinder.VfsFile && toFind.exists()) { VirtualFile file = ((LocalFsFinder.VfsFile)toFind).getFile(); if (file != null) { return new VirtualFile[]{file}; } } } return VirtualFile.EMPTY_ARRAY; } return myFileSystemTree.getSelectedFiles(); } private final Map<String, LocalFileSystem.WatchRequest> myRequests = new HashMap<>(); private static boolean isToShowTextField() { return PropertiesComponent.getInstance().getBoolean(FILE_CHOOSER_SHOW_PATH_PROPERTY, true); } private static void setToShowTextField(boolean toShowTextField) { PropertiesComponent.getInstance().setValue(FILE_CHOOSER_SHOW_PATH_PROPERTY, Boolean.toString(toShowTextField)); } private final class FileTreeExpansionListener implements TreeExpansionListener { @Override public void treeExpanded(TreeExpansionEvent event) { final Object[] path = event.getPath().getPath(); if (path.length == 2 && path[1] instanceof DefaultMutableTreeNode) { // top node has been expanded => watch disk recursively final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path[1]; Object userObject = node.getUserObject(); if (userObject instanceof FileNodeDescriptor) { final VirtualFile file = ((FileNodeDescriptor)userObject).getElement().getFile(); if (file != null && file.isDirectory()) { final String rootPath = file.getPath(); if (myRequests.get(rootPath) == null) { final LocalFileSystem.WatchRequest watchRequest = LocalFileSystem.getInstance().addRootToWatch(rootPath, true); if (watchRequest != null) { myRequests.put(rootPath, watchRequest); } } } } } } @Override public void treeCollapsed(TreeExpansionEvent event) { } } private final class FileTreeSelectionListener implements TreeSelectionListener { @Override public void valueChanged(TreeSelectionEvent e) { TreePath[] paths = e.getPaths(); boolean enabled = true; for (TreePath treePath : paths) { if (e.isAddedPath(treePath)) { VirtualFile file = FileSystemTreeImpl.getVirtualFile(treePath); if (file == null || !myChooserDescriptor.isFileSelectable(file)) enabled = false; } } setOKActionEnabled(enabled); } } protected final class MyPanel extends JPanel implements DataProvider { final PasteProvider myPasteProvider = new PasteProvider() { @Override public void performPaste(@NotNull DataContext dataContext) { if (myPathTextField != null) { String path = calculatePath(); myPathTextField.setText(path, true, null); updateTreeFromPath(path); } } @Nullable private String calculatePath() { final Transferable contents = CopyPasteManager.getInstance().getContents(); if (contents != null) { final List<File> fileList = FileCopyPasteUtil.getFileList(contents); if (fileList != null) { if (!fileList.isEmpty()) { return fileList.get(0).getAbsolutePath(); } } } return null; } @Override public boolean isPastePossible(@NotNull DataContext dataContext) { return isPasteEnabled(dataContext); } @Override public boolean isPasteEnabled(@NotNull DataContext dataContext) { return FileCopyPasteUtil.isFileListFlavorAvailable() && calculatePath() != null; } }; public MyPanel() { super(new BorderLayout(0, 0)); } @Override public Object getData(@NotNull String dataId) { if (PATH_FIELD.is(dataId)) { return (PathField)FileChooserDialogImpl.this::toggleShowTextField; } if (FileSystemTree.DATA_KEY.is(dataId)) { return myFileSystemTree; } if (PlatformDataKeys.PASTE_PROVIDER.is(dataId)) { return myPasteProvider; } return myChooserDescriptor.getUserData(dataId); } } public void toggleShowTextField() { setToShowTextField(!isToShowTextField()); updateTextFieldShowing(); } private void updateTextFieldShowing() { myTextFieldAction.update(); myNorthPanel.remove(myPath); if (isToShowTextField()) { List<VirtualFile> selection = new ArrayList<>(); if (myFileSystemTree.getSelectedFile() != null) { selection.add(myFileSystemTree.getSelectedFile()); } updatePathFromTree(selection, true); myNorthPanel.add(myPath, BorderLayout.CENTER); } else { setErrorText(null); } IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(myPathTextField.getField(), true)); myNorthPanel.revalidate(); myNorthPanel.repaint(); } private void updatePathFromTree(final List<? extends VirtualFile> selection, boolean now) { if (!isToShowTextField() || myTreeIsUpdating) return; String text = ""; if (!selection.isEmpty()) { text = VfsUtil.getReadableUrl(selection.get(0)); } else { final List<VirtualFile> roots = myChooserDescriptor.getRoots(); if (!myFileSystemTree.getTree().isRootVisible() && roots.size() == 1) { text = VfsUtil.getReadableUrl(roots.get(0)); } } if (myFileSystemTree.getTreeBuilder() == null) { if (text.isEmpty()) return; String old = myPathTextField.getTextFieldText(); if (old == null || old.equals(text)) return; int index = old.length() - 1; if (index == text.length() && File.separatorChar == old.charAt(index) && old.startsWith(text)) return; } myPathTextField.setText(text, now, () -> { myPathTextField.getField().selectAll(); setErrorText(null); }); } private void updateTreeFromPath(final String text) { if (!isToShowTextField()) return; if (myPathTextField.isPathUpdating()) return; if (text == null) return; myUiUpdater.queue(new Update("treeFromPath.1") { @Override public void run() { ApplicationManager.getApplication().executeOnPooledThread(() -> { final LocalFsFinder.VfsFile toFind = (LocalFsFinder.VfsFile)myPathTextField.getFile(); if (toFind == null || !toFind.exists()) return; myUiUpdater.queue(new Update("treeFromPath.2") { @Override public void run() { selectInTree(toFind.getFile(), text); } }); }); } }); } private void selectInTree(final VirtualFile vFile, String fromText) { if (vFile != null && vFile.isValid()) { if (fromText == null || fromText.equalsIgnoreCase(myPathTextField.getTextFieldText())) { selectInTree(new VirtualFile[]{vFile}, false, fromText == null); } } else { reportFileNotFound(); } } private void selectInTree(VirtualFile[] array, boolean requestFocus, boolean updatePathNeeded) { myTreeIsUpdating = true; final List<VirtualFile> fileList = Arrays.asList(array); if (!Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) { myFileSystemTree.select(array, () -> { if (!myFileSystemTree.areHiddensShown() && !Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) { // try to select files in hidden folders myFileSystemTree.showHiddens(true); selectInTree(array, requestFocus, updatePathNeeded); return; } if (array.length == 1 && !Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) { // try to select a parent of a missed file VirtualFile parent = array[0].getParent(); if (parent != null && parent.isValid()) { selectInTree(new VirtualFile[]{parent}, requestFocus, updatePathNeeded); return; } } reportFileNotFound(); if (updatePathNeeded) { updatePathFromTree(fileList, true); } if (requestFocus) { SwingUtilities.invokeLater(() -> myFileSystemTree.getTree().requestFocus()); } }); } else { reportFileNotFound(); if (updatePathNeeded) { updatePathFromTree(fileList, true); } } } private void reportFileNotFound() { myTreeIsUpdating = false; setErrorText(null); } @Override protected String getDimensionServiceKey() { return "FileChooserDialogImpl"; } @Override protected String getHelpId() { return "select.path.dialog"; } }
3e0c0f73a04e654f8d7a474d4afeb21fb42e91b9
3,367
java
Java
src/me/drton/flightplot/AddProcessorDialog.java
tiny-plane/FlightPlot_MeiYing
c16bff75edd21b72968779bf031fbd09b4fedd65
[ "Unlicense" ]
null
null
null
src/me/drton/flightplot/AddProcessorDialog.java
tiny-plane/FlightPlot_MeiYing
c16bff75edd21b72968779bf031fbd09b4fedd65
[ "Unlicense" ]
null
null
null
src/me/drton/flightplot/AddProcessorDialog.java
tiny-plane/FlightPlot_MeiYing
c16bff75edd21b72968779bf031fbd09b4fedd65
[ "Unlicense" ]
null
null
null
34.010101
124
0.628453
5,114
package me.drton.flightplot; import me.drton.flightplot.processors.PlotProcessor; import javax.swing.*; import java.awt.event.*; public class AddProcessorDialog extends JDialog { private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JTextField titleField; private JList processorTypesList; private DefaultListModel processorTypesListModel; private String[] processorTypes; private ProcessorPreset origProcessorPreset = null; private Runnable callback; public AddProcessorDialog(String[] processorTypes) { this.processorTypes = processorTypes; //this.processorTypes = processorTypes; setContentPane(contentPane); setModal(true); setTitle("添加待处理数据"); getRootPane().setDefaultButton(buttonOK); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } public String getProcessorTitle() { return titleField.getText(); } public ProcessorPreset getOrigProcessorPreset() { return origProcessorPreset; } public String getProcessorType() { return (String) processorTypesList.getSelectedValue(); } public void display(Runnable callback, ProcessorPreset processorPreset) {//从fieldlist里面弄没用,那个地方只能传递出选择的field的名字,这里才开始处理 // runnable是用于生成新的线程的接口类,里面只有一种方法,就是运行,run,调用这个方法就可以生成一个新的线程。 if (processorTypesListModel.size() == 0) { for (String processorType : processorTypes) { processorTypesListModel.addElement(processorType); } processorTypesList.setSelectedValue("Simple", true);//默认是选择simple的 } this.callback = callback; if (processorPreset != null) { origProcessorPreset = processorPreset; titleField.setText(processorPreset.getTitle()); processorTypesList.setSelectedValue(processorPreset.getProcessorType(), true); } else { origProcessorPreset = null; titleField.setText(""); } titleField.requestFocus(); this.setVisible(true); } private void onOK() { setVisible(false); callback.run(); } private void onCancel() { setVisible(false); } private void createUIComponents() { processorTypesListModel = new DefaultListModel(); processorTypesList = new JList(processorTypesListModel); } }
3e0c10b81294ed2cb6d126a5f5f1ba9e69ce2bfb
214
java
Java
backend/src/test/java/backend/flashcards/FlashcardsApplicationTests.java
TonyMorse92/FlashCards
0906c55133606003471812fca14d7736127d3548
[ "MIT" ]
null
null
null
backend/src/test/java/backend/flashcards/FlashcardsApplicationTests.java
TonyMorse92/FlashCards
0906c55133606003471812fca14d7736127d3548
[ "MIT" ]
null
null
null
backend/src/test/java/backend/flashcards/FlashcardsApplicationTests.java
TonyMorse92/FlashCards
0906c55133606003471812fca14d7736127d3548
[ "MIT" ]
null
null
null
15.285714
60
0.794393
5,115
package backend.flashcards; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class FlashcardsApplicationTests { @Test void contextLoads() { } }
3e0c116dd8ac4b795cbdbdfa011f884d6691f9cc
281
java
Java
src/com/aaron/chainofresponsibility/AbstractHandler.java
cdcdec/DesignPatterns
b2a0dfd98f256db13654de30556a47858568e81b
[ "Apache-2.0" ]
null
null
null
src/com/aaron/chainofresponsibility/AbstractHandler.java
cdcdec/DesignPatterns
b2a0dfd98f256db13654de30556a47858568e81b
[ "Apache-2.0" ]
null
null
null
src/com/aaron/chainofresponsibility/AbstractHandler.java
cdcdec/DesignPatterns
b2a0dfd98f256db13654de30556a47858568e81b
[ "Apache-2.0" ]
null
null
null
18.733333
47
0.637011
5,116
package com.aaron.chainofresponsibility; public abstract class AbstractHandler { private Handler handler; public Handler getHandler() { return handler; } public void setHandler(Handler handler) { this.handler = handler; } }
3e0c12aaebe2a2e800bdf197c529c376c9a14cb2
6,156
java
Java
AL-Game/data/scripts/system/handlers/quest/theobomos/_3074DangerousProbability.java
karllgiovany/Aion-Lightning-4.9-SRC
05beede3382ec7dbdabb2eb9f76e4e42d046ff59
[ "FTL" ]
1
2019-09-24T23:26:34.000Z
2019-09-24T23:26:34.000Z
AL-Game/data/scripts/system/handlers/quest/theobomos/_3074DangerousProbability.java
korssar2008/Aion-Lightning-4.9
05beede3382ec7dbdabb2eb9f76e4e42d046ff59
[ "FTL" ]
null
null
null
AL-Game/data/scripts/system/handlers/quest/theobomos/_3074DangerousProbability.java
korssar2008/Aion-Lightning-4.9
05beede3382ec7dbdabb2eb9f76e4e42d046ff59
[ "FTL" ]
1
2017-12-28T16:59:47.000Z
2017-12-28T16:59:47.000Z
41.594595
87
0.485543
5,117
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package quest.theobomos; import com.aionemu.commons.utils.Rnd; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.QuestService; import com.aionemu.gameserver.services.item.ItemService; /** * @author Wakizashi * @modified vlog */ public class _3074DangerousProbability extends QuestHandler { private final static int questId = 3074; private int reward = -1; public _3074DangerousProbability() { super(questId); } @Override public void register() { qe.registerQuestNpc(798193).addOnQuestStart(questId); qe.registerQuestNpc(798193).addOnTalkEvent(questId); } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); int targetId = env.getTargetId(); QuestState qs = player.getQuestStateList().getQuestState(questId); DialogAction dialog = env.getDialog(); if (qs == null || qs.getStatus() == QuestStatus.NONE || qs.canRepeat()) { if (targetId == 798193) { // Nagrunerk if (dialog == DialogAction.EXCHANGE_COIN) { if (QuestService.startQuest(env)) { return sendQuestDialog(env, 1011); } else { return sendQuestSelectionDialog(env); } } } } else if (qs.getStatus() == QuestStatus.START) { if (targetId == 798193) { // Nagrunerk long kinahAmount = player.getInventory().getKinah(); long angelsEye = player.getInventory().getItemCountByItemId(186000037); switch (dialog) { case EXCHANGE_COIN: { return sendQuestDialog(env, 1011); } case SELECT_ACTION_1011: { if (kinahAmount >= 1000 && angelsEye >= 1) { changeQuestStep(env, 0, 0, true); reward = 0; return sendQuestDialog(env, 5); } else { return sendQuestDialog(env, 1009); } } case SELECT_ACTION_1352: { if (kinahAmount >= 5000 && angelsEye >= 1) { changeQuestStep(env, 0, 0, true); reward = 1; return sendQuestDialog(env, 6); } else { return sendQuestDialog(env, 1009); } } case SELECT_ACTION_1693: { if (kinahAmount >= 25000 && angelsEye >= 1) { changeQuestStep(env, 0, 0, true); reward = 2; return sendQuestDialog(env, 7); } else { return sendQuestDialog(env, 1009); } } case FINISH_DIALOG: { return sendQuestSelectionDialog(env); } default: break; } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 798193) { // Nagrunerk if (dialog == DialogAction.SELECTED_QUEST_NOREWARD) { switch (reward) { case 0: { if (QuestService.finishQuest(env, 0)) { player.getInventory().decreaseKinah(1000); removeQuestItem(env, 186000037, 1); ItemService.addItem(player, 186000005, 1); reward = -1; break; } } case 1: { if (QuestService.finishQuest(env, 1)) { player.getInventory().decreaseKinah(5000); removeQuestItem(env, 186000037, 1); ItemService.addItem(player, 186000005, Rnd.get(1, 3)); reward = -1; break; } } case 2: { if (QuestService.finishQuest(env, 2)) { ItemService.addItem(player, 186000005, Rnd.get(1, 6)); player.getInventory().decreaseKinah(25000); removeQuestItem(env, 186000037, 1); reward = -1; break; } } } return closeDialogWindow(env); } else { QuestService.abandonQuest(player, questId); } } } return false; } }
3e0c134cd80312269cbb04a82a00ccbe364eb9b9
1,749
java
Java
src/main/java/com/phoenix/blockchain/core/model/BlockHeader.java
viphoenix/bitcoin-springboot
a03a53e4e55c49d79f44d8d9d7e5ea9860068c35
[ "MIT" ]
4
2018-07-15T08:46:51.000Z
2018-09-13T03:14:07.000Z
src/main/java/com/phoenix/blockchain/core/model/BlockHeader.java
viphoenix/bitcoin-springboot
a03a53e4e55c49d79f44d8d9d7e5ea9860068c35
[ "MIT" ]
null
null
null
src/main/java/com/phoenix/blockchain/core/model/BlockHeader.java
viphoenix/bitcoin-springboot
a03a53e4e55c49d79f44d8d9d7e5ea9860068c35
[ "MIT" ]
null
null
null
16.980583
70
0.590623
5,118
package com.phoenix.blockchain.core.model; import com.phoenix.blockchain.common.constants.BitCoinConstants; /** * Created by chengfeng on 2018/7/8. * * 区块头 */ public class BlockHeader extends BaseDomain { private static final long serialVersionUID = 7702113613467813322L; private String version = BitCoinConstants.SYS_VERSION; /** * 上一区块Header hash */ private String preHash; /** * 当前区块Header Hash, 比特币系统未使用 */ private String curHash; /** * 随机值 */ private Long nonce; /** * 当前区块高度 */ private Long height; /** * 挖矿难度 */ private long difficulty; /** * 区块生成时间 */ private Long timestamp; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getPreHash() { return preHash; } public void setPreHash(String preHash) { this.preHash = preHash; } public String getCurHash() { return curHash; } public void setCurHash(String curHash) { this.curHash = curHash; } public Long getNonce() { return nonce; } public void setNonce(Long nonce) { this.nonce = nonce; } public Long getHeight() { return height; } public void setHeight(Long height) { this.height = height; } public long getDifficulty() { return difficulty; } public void setDifficulty(long difficulty) { this.difficulty = difficulty; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } }
3e0c139b2efb4599db9a778756e620f925102544
809
java
Java
ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java
5herhom/Linkis
e9b2919528f5d30cb71fcf49bf37b8d684806ed2
[ "Apache-2.0" ]
5
2019-12-02T01:36:46.000Z
2020-05-13T08:47:45.000Z
ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java
5herhom/Linkis
e9b2919528f5d30cb71fcf49bf37b8d684806ed2
[ "Apache-2.0" ]
2
2020-06-02T03:04:26.000Z
2020-08-06T09:07:42.000Z
ujes/entrance/src/main/java/com/webank/wedatasphere/linkis/entrance/persistence/AbstractPersistenceEngine.java
5herhom/Linkis
e9b2919528f5d30cb71fcf49bf37b8d684806ed2
[ "Apache-2.0" ]
2
2020-05-13T12:40:20.000Z
2020-06-02T02:44:51.000Z
28.892857
77
0.745365
5,119
/* * Copyright 2019 WeBank * * 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. */ /** * author: enjoyyin * date: 2018/9/27 * time: 10:10 * Description: */ package com.webank.wedatasphere.linkis.entrance.persistence; public abstract class AbstractPersistenceEngine implements PersistenceEngine{ }
3e0c13de47ab17098c4977f8f240517df110ae1c
234
java
Java
cornerstone/src/main/java/com/ctrip/framework/cs/enterprise/AuthenticationFailedException.java
birdie7761/vi
39e870cd8b18d07d15a58f2bab12b68a0e5e7b39
[ "Apache-2.0" ]
240
2018-05-18T09:17:59.000Z
2022-01-12T10:38:06.000Z
cornerstone/src/main/java/com/ctrip/framework/cs/enterprise/AuthenticationFailedException.java
birdie7761/vi
39e870cd8b18d07d15a58f2bab12b68a0e5e7b39
[ "Apache-2.0" ]
12
2018-05-20T12:17:53.000Z
2020-09-28T18:00:07.000Z
cornerstone/src/main/java/com/ctrip/framework/cs/enterprise/AuthenticationFailedException.java
birdie7761/vi
39e870cd8b18d07d15a58f2bab12b68a0e5e7b39
[ "Apache-2.0" ]
99
2018-05-30T12:48:28.000Z
2022-02-28T15:03:20.000Z
19.5
62
0.717949
5,120
package com.ctrip.framework.cs.enterprise; /** * Created by jiang.j on 2016/10/20. */ public class AuthenticationFailedException extends Exception { public AuthenticationFailedException(Throwable e){ super(e); } }
3e0c150236e6f4d04fb872bcdb711e35b7a38670
1,860
java
Java
adapters-1.6/src/test/java/com/flipkart/fdp/ml/adapter/LogisticRegressionBridgeTest.java
flipkart-incubator/spark-transformers
66cbc60aaedbe0d2b73eb35808335272f17cc89b
[ "Apache-2.0" ]
43
2016-04-20T17:00:04.000Z
2022-01-06T15:23:46.000Z
adapters-1.6/src/test/java/com/flipkart/fdp/ml/adapter/LogisticRegressionBridgeTest.java
nareshsankapelly/spark-transformers
66cbc60aaedbe0d2b73eb35808335272f17cc89b
[ "Apache-2.0" ]
13
2016-03-29T06:24:59.000Z
2017-12-14T11:14:37.000Z
adapters-1.6/src/test/java/com/flipkart/fdp/ml/adapter/LogisticRegressionBridgeTest.java
nareshsankapelly/spark-transformers
66cbc60aaedbe0d2b73eb35808335272f17cc89b
[ "Apache-2.0" ]
27
2016-03-28T16:29:23.000Z
2019-11-17T08:17:02.000Z
35.769231
99
0.716667
5,121
package com.flipkart.fdp.ml.adapter; import com.flipkart.fdp.ml.export.ModelExporter; import com.flipkart.fdp.ml.importer.ModelImporter; import com.flipkart.fdp.ml.transformer.Transformer; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.mllib.classification.LogisticRegressionModel; import org.apache.spark.mllib.classification.LogisticRegressionWithSGD; import org.apache.spark.mllib.linalg.Vector; import org.apache.spark.mllib.regression.LabeledPoint; import org.apache.spark.mllib.util.MLUtils; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; public class LogisticRegressionBridgeTest extends SparkTestBase { @Test public void testLogisticRegression() { //prepare data String datapath = "src/test/resources/binary_classification_test.libsvm"; JavaRDD<LabeledPoint> trainingData = MLUtils.loadLibSVMFile(sc.sc(), datapath).toJavaRDD(); //Train model in spark LogisticRegressionModel lrmodel = new LogisticRegressionWithSGD().run(trainingData.rdd()); //Export this model byte[] exportedModel = ModelExporter.export(lrmodel, null); //Import and get Transformer Transformer transformer = ModelImporter.importAndGetTransformer(exportedModel); //validate predictions List<LabeledPoint> testPoints = trainingData.collect(); for (LabeledPoint i : testPoints) { Vector v = i.features(); double actual = lrmodel.predict(v); Map<String, Object> data = new HashMap<String, Object>(); data.put("features", v.toArray()); transformer.transform(data); double predicted = (double) data.get("prediction"); assertEquals(actual, predicted, EPSILON); } } }
3e0c150cf42037302abfbbd3aa3061326d8356df
6,376
java
Java
src/main/java/org/smof/collection/AbstractQuery.java
JPDSousa/mongo-obj-framework
35e690660d3eb9089748e04aaee0618edb6f1d43
[ "MIT" ]
10
2017-05-12T11:02:27.000Z
2018-02-12T12:21:06.000Z
src/main/java/org/smof/collection/AbstractQuery.java
JPDSousa/mongo-obj-framework
35e690660d3eb9089748e04aaee0618edb6f1d43
[ "MIT" ]
88
2017-03-26T16:00:48.000Z
2019-06-24T02:30:58.000Z
src/main/java/org/smof/collection/AbstractQuery.java
JPDSousa/mongo-obj-framework
35e690660d3eb9089748e04aaee0618edb6f1d43
[ "MIT" ]
24
2017-09-28T13:13:39.000Z
2019-10-05T06:03:54.000Z
33.036269
111
0.740433
5,122
/******************************************************************************* * Copyright (C) 2017 Joao Sousa * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package org.smof.collection; import java.util.Map; import java.util.regex.Pattern; import org.bson.BsonArray; import org.bson.BsonValue; import org.smof.element.Element; import org.smof.field.PrimaryField; import org.smof.parsers.SmofParser; import org.smof.parsers.SmofType; import static org.smof.collection.QueryOperators.*; abstract class AbstractQuery<T extends Element, Query extends SmofQuery<T, ?>> implements SmofQuery<T, Query> { private final SmofParser parser; private final Class<T> elementClass; protected AbstractQuery(SmofParser parser, Class<T> elementClass) { this.elementClass = elementClass; this.parser = parser; } @Override public Class<T> getElementClass() { return elementClass; } protected abstract void append(String name, BsonValue value); protected abstract BsonValue getFilter(); protected SmofParser getParser() { return parser; } private Query applyQuery(String fieldName, Object value, QueryOperators op) { final BsonValue bsonValue = toBsonQueryValue(fieldName, value); return applyBsonQuery(fieldName, bsonValue, op); } @SuppressWarnings("unchecked") private Query applyBsonQuery(String fieldName, BsonValue value, QueryOperators op) { append(fieldName, op.query(value)); return (Query) this; } private BsonValue toBsonQueryValue(String fieldName, Object value) { return toBsonQueryValue(parser.getField(elementClass, fieldName), value); } private BsonValue toBsonQueryValue(PrimaryField field, Object value) { if((field.getType() == SmofType.OBJECT && value instanceof Map) || field.getType() == SmofType.ARRAY) { return parser.toBson(value, field.getSecondaryField()); } return parser.toBson(value, field); } private BsonValue toBsonQueryValues(PrimaryField field, Object[] values) { final BsonArray bsonValue = new BsonArray(); for (Object value : values) { bsonValue.add(toBsonQueryValue(field, value)); } return bsonValue; } @Override public Query withFieldEquals(String fieldName, Object value) { return applyQuery(fieldName, value, EQUALS); } @Override public Query withFieldNotEquals(String fieldName, Object value) { return applyQuery(fieldName, value, NOT_EQUALS); } @Override public Query withFieldIn(String fieldName, Object[] values) { final PrimaryField field = parser.getField(elementClass, fieldName); final BsonValue bsonValue = toBsonQueryValues(field, values); return applyBsonQuery(fieldName, bsonValue, IN); } @Override public Query withFieldNotIn(String fieldName, Object[] values) { final PrimaryField field = parser.getField(elementClass, fieldName); final BsonValue bsonValue = toBsonQueryValues(field, values); return applyBsonQuery(fieldName, bsonValue, NOT_IN); } @SuppressWarnings("unchecked") @Override public Query withFieldRegex(String fieldName, Pattern value) { final BsonValue bsonValue = parser.toBson(value, Pattern.class); append(fieldName, bsonValue); return (Query) this; } @Override public Query withFieldGreater(String fieldName, Object value) { return withFieldGreater(fieldName, value, false); } @Override public Query withFieldGreater(String fieldName, Object value, boolean greaterOrEqual) { return applyQuery(fieldName, value, greaterOrEqual ? GREATER_OR_EQUAL : GREATER); } @Override public Query withFieldGreaterOrEqual(String fieldName, Object value) { return withFieldGreater(fieldName, value, true); } @Override public Query withFieldSmaller(String fieldName, Object value) { return withFieldSmaller(fieldName, value, false); } @Override public Query withFieldSmaller(String fieldName, Object value, boolean smallerOrEqual) { return applyQuery(fieldName, value, smallerOrEqual ? SMALLER_OR_EQUAL : SMALLER); } @Override public Query withFieldSmallerOrEqual(String fieldName, Object value) { return withFieldSmaller(fieldName, value, true); } @SuppressWarnings("unchecked") @Override public ArrayQuery<T> beginAnd() { return new ArrayQuery<>((AbstractQuery<T, SmofQuery<T, ?>>) this, AND); } @SuppressWarnings("unchecked") @Override public ArrayQuery<T> beginOr() { return new ArrayQuery<>((AbstractQuery<T, SmofQuery<T, ?>>) this, OR); } @SuppressWarnings("unchecked") @Override public ArrayQuery<T> beginNor() { return new ArrayQuery<>((AbstractQuery<T, SmofQuery<T, ?>>) this, NOR); } @SuppressWarnings("unchecked") @Override public DocumentQuery<T> beginNot() { return new DocumentQuery<>((AbstractQuery<T, SmofQuery<T, ?>>) this, NOT); } @Override public Query withFieldMod(String fieldName, int divisor, int remainder) { final PrimaryField field = parser.getField(elementClass, fieldName); final BsonValue bsonValue = toBsonQueryValues(field, new Object[]{divisor, remainder}); return applyBsonQuery(fieldName, bsonValue, MOD); } @Override public Query withFieldAll(String fieldName, Object[] values) { final PrimaryField field = parser.getField(elementClass, fieldName); final BsonValue bsonValue = toBsonQueryValues(field, values); return applyBsonQuery(fieldName, bsonValue, ALL); } }
3e0c151f4bf346a479f5e49b5c54d0de10df276c
11,371
java
Java
src/android/BaiduLocation.java
pengpengmz/com.qdc.plugins.baidu.location
4b8f246398bfbce948b93166af330fafae7f8151
[ "MIT" ]
null
null
null
src/android/BaiduLocation.java
pengpengmz/com.qdc.plugins.baidu.location
4b8f246398bfbce948b93166af330fafae7f8151
[ "MIT" ]
null
null
null
src/android/BaiduLocation.java
pengpengmz/com.qdc.plugins.baidu.location
4b8f246398bfbce948b93166af330fafae7f8151
[ "MIT" ]
1
2021-12-30T07:43:34.000Z
2021-12-30T07:43:34.000Z
42.429104
124
0.549116
5,123
package com.qdc.plugins.baidu; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; //import org.apache.cordova.LOG; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.location.LocationClientOption.LocationMode; /** * 百度云推送插件 * * @author mrwutong * 2016-06-07 peng 修改,支持 Android定位SDKv6.2.3 */ public class BaiduLocation extends CordovaPlugin { /** LOG TAG */ private static final String LOG_TAG = "BaiduLocation";//BaiduLocation.class.getSimpleName(); /** JS回调接口对象 */ public static CallbackContext cbCtx = null; /** 百度定位客户端 */ public LocationClient mLocationClient = null; //private Object objLock = new Object(); /** 百度定位监听 */ public BDLocationListener myListener = new BDLocationListener() { @Override public void onReceiveLocation(BDLocation location) { try { /* * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来,每次回调的时间; * location.getTime() 是指服务端出本次结果的时间,如果位置不发生变化,则时间不变 */ StringBuilder sb = new StringBuilder(256); sb.append("time : "); sb.append(location.getTime()); sb.append("\nerror code : "); sb.append(location.getLocType()); sb.append("\nlatitude : "); sb.append(location.getLatitude()); sb.append("\nlontitude : "); sb.append(location.getLongitude()); sb.append("\nradius : "); sb.append(location.getRadius()); sb.append("\nCountryCode : "); sb.append(location.getCountryCode()); sb.append("\nCountry : "); sb.append(location.getCountry()); sb.append("\ncitycode : "); sb.append(location.getCityCode()); sb.append("\ncity : "); sb.append(location.getCity()); sb.append("\nDistrict : "); sb.append(location.getDistrict()); sb.append("\nStreet : "); sb.append(location.getStreet()); /* sb.append("\naddr : "); sb.append(location.getAddrStr()); sb.append("\nDescribe: "); sb.append(location.getLocationDescribe()); sb.append("\nDirection(not all devices have value): "); sb.append(location.getDirection()); sb.append("\nPoi: "); if (location.getPoiList() != null && !location.getPoiList().isEmpty()) { for (int i = 0; i < location.getPoiList().size(); i++) { Poi poi = (Poi) location.getPoiList().get(i); sb.append(poi.getName() + ";"); } } */ JSONObject json = new JSONObject(); json.put("time", location.getTime()); json.put("locType", location.getLocType()); json.put("latitude", location.getLatitude()); json.put("lontitude", location.getLongitude()); json.put("radius", location.getRadius()); if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果 sb.append("\nspeed : "); sb.append(location.getSpeed());// 单位:公里每小时 sb.append("\nsatellite : "); sb.append(location.getSatelliteNumber()); sb.append("\nheight : "); sb.append(location.getAltitude());// 单位:米 sb.append("\ndirection : "); sb.append(location.getDirection());// 单位度 sb.append("\naddr : "); sb.append(location.getAddrStr()); sb.append("\ndescribe : "); sb.append("gps定位成功"); json.put("speed", location.getSpeed()); json.put("satellite", location.getSatelliteNumber()); json.put("height", location.getAltitude()); json.put("direction", location.getDirection()); json.put("addr", location.getAddrStr()); json.put("describe", "gps定位成功"); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果 sb.append("\naddr : "); sb.append(location.getAddrStr()); //运营商信息 sb.append("\noperationers : "); sb.append(location.getOperators()); sb.append("\ndescribe : "); sb.append("网络定位成功"); json.put("addr", location.getAddrStr()); json.put("operationers", location.getOperators()); json.put("describe", "网络定位成功"); } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果 sb.append("\ndescribe : "); sb.append("离线定位成功,离线定位结果也是有效的"); json.put("describe", "离线定位成功,离线定位结果也是有效的"); } else if (location.getLocType() == BDLocation.TypeServerError) { sb.append("\ndescribe : "); sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因"); json.put("describe", "服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因"); } else if (location.getLocType() == BDLocation.TypeNetWorkException) { sb.append("\ndescribe : "); sb.append("网络不同导致定位失败,请检查网络是否通畅"); json.put("describe", "网络不同导致定位失败,请检查网络是否通畅"); } else if (location.getLocType() == BDLocation.TypeCriteriaException) { sb.append("\ndescribe : "); sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机"); json.put("describe", "无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机"); } // sb.append("\nlocationdescribe : "); // sb.append(location.getLocationDescribe());// 位置语义化信息 // List<Poi> list = location.getPoiList();// POI数据 // if (list != null) { // sb.append("\npoilist size = : "); // sb.append(list.size()); // for (Poi p : list) { // sb.append("\npoi= : "); // sb.append(p.getId() + " " + p.getName() + " " + p.getRank()); // } // } Log.i(LOG_TAG, sb.toString()); //PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, sb.toString()); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, json); pluginResult.setKeepCallback(true); cbCtx.sendPluginResult(pluginResult); } catch (JSONException e) { String errMsg = e.getMessage(); Log.e(LOG_TAG, errMsg, e); PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, errMsg); pluginResult.setKeepCallback(true); cbCtx.sendPluginResult(pluginResult); } finally { mLocationClient.stop(); } } }; /** * 插件主入口 */ @Override public boolean execute(String action, final JSONArray args, CallbackContext callbackContext) throws JSONException { //Log.i(LOG_TAG, "BaiduPush#execute"); boolean ret = false; //if ("getCurrentPosition".equalsIgnoreCase(action)) { if (action.equalsIgnoreCase("getCurrentPosition")) { cbCtx = callbackContext; //PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); //pluginResult.setKeepCallback(true); //cbCtx.sendPluginResult(pluginResult); if (mLocationClient == null) { mLocationClient = new LocationClient(this.webView.getContext()); mLocationClient.registerLocationListener(myListener); //if(mLocationClient.isStarted()) mLocationClient.stop(); // 配置定位SDK参数 initLocation(); } //mLocationClient.start(); //mLocationClient.requestLocation(); //实际上在start之后会默认发起一次定位请求,开发者无须检查这个函数,只要等着定位回调就可以了 if (mLocationClient.isStarted() == false) { mLocationClient.start(); Log.i(LOG_TAG, "LocationClient start done"); } /* if (mLocationClient != null && mLocationClient.isStarted()) { mLocationClient.requestLocation(); } else { String errMsg = ""; if (mLocationClient == null) errMsg = "LocationClient is null,"; if (mLocationClient.isStarted() == false) errMsg = "LocationClient is not started"; Log.e(LOG_TAG, errMsg); //Thread.sleep(100); //mLocationClient.requestLocation(); Timer timer = new Timer();// 实例化Timer类 timer.schedule(new TimerTask() { public void run() { //mLocationClient.requestLocation(); if (mLocationClient != null && mLocationClient.isStarted()) { mLocationClient.requestLocation(); } else { Log.e(LOG_TAG, "LocationClient is not started after delay"); } this.cancel(); } }, 500);// 这里百毫秒 } */ ret = true; } return ret; } /** * 配置定位SDK参数 */ private void initLocation() { LocationClientOption option = new LocationClientOption(); option.setOpenGps(true); option.setLocationMode(LocationMode.Hight_Accuracy); //option.setLocationMode(LocationMode.Battery_Saving);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll; //option.setScanSpan(3000);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要 option.setIsNeedLocationDescribe(true);//可选,设置是否需要地址描述 option.setNeedDeviceDirect(false);//可选,设置是否需要设备方向结果 option.setLocationNotify(false);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 option.setIgnoreKillProcess(true);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集 option.setProdName("UltraCRM-BaiduLocation"); option.disableCache(true);// 禁止启用缓存定位 mLocationClient.setLocOption(option); } }