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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9243374b34c6be32b93bcdd329f26cf68d7a114c
| 5,790 |
java
|
Java
|
components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXRemoteTest.java
|
dmgerman/camel
|
cab53c57b3e58871df1f96d54b2a2ad5a73ce220
|
[
"Apache-2.0"
] | null | null | null |
components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXRemoteTest.java
|
dmgerman/camel
|
cab53c57b3e58871df1f96d54b2a2ad5a73ce220
|
[
"Apache-2.0"
] | 23 |
2021-03-23T00:01:38.000Z
|
2022-01-04T16:47:34.000Z
|
components/camel-jmx/src/test/java/org/apache/camel/component/jmx/JMXRemoteTest.java
|
dmgerman/camel
|
cab53c57b3e58871df1f96d54b2a2ad5a73ce220
|
[
"Apache-2.0"
] | null | null | null | 16.685879 | 810 | 0.800518 | 1,002,579 |
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
DECL|package|org.apache.camel.component.jmx
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|jmx
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|File
import|;
end_import
begin_import
import|import
name|java
operator|.
name|rmi
operator|.
name|registry
operator|.
name|LocateRegistry
import|;
end_import
begin_import
import|import
name|java
operator|.
name|rmi
operator|.
name|registry
operator|.
name|Registry
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collections
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|management
operator|.
name|MBeanServerFactory
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|management
operator|.
name|remote
operator|.
name|JMXConnectorServer
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|management
operator|.
name|remote
operator|.
name|JMXConnectorServerFactory
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|management
operator|.
name|remote
operator|.
name|JMXServiceURL
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|test
operator|.
name|AvailablePortFinder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|jupiter
operator|.
name|api
operator|.
name|AfterEach
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|jupiter
operator|.
name|api
operator|.
name|Test
import|;
end_import
begin_comment
comment|/** * Tests against a "remote" JMX server. Creates an RMI Registry on or near port 39000 * and registers the simple mbean *<p/> * Only test here is the notification test since everything should work the * same as the platform server. May want to refactor the existing tests to * run the full suite on the local platform and this "remote" setup. */
end_comment
begin_class
DECL|class|JMXRemoteTest
specifier|public
class|class
name|JMXRemoteTest
extends|extends
name|SimpleBeanFixture
block|{
DECL|field|url
name|JMXServiceURL
name|url
decl_stmt|;
DECL|field|connector
name|JMXConnectorServer
name|connector
decl_stmt|;
DECL|field|registry
name|Registry
name|registry
decl_stmt|;
annotation|@
name|Override
annotation|@
name|AfterEach
DECL|method|tearDown ()
specifier|public
name|void
name|tearDown
parameter_list|()
throws|throws
name|Exception
block|{
name|super
operator|.
name|tearDown
argument_list|()
expr_stmt|;
name|connector
operator|.
name|stop
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|initServer ()
specifier|protected
name|void
name|initServer
parameter_list|()
throws|throws
name|Exception
block|{
name|int
name|port
init|=
name|AvailablePortFinder
operator|.
name|getNextAvailable
argument_list|()
decl_stmt|;
name|registry
operator|=
name|LocateRegistry
operator|.
name|createRegistry
argument_list|(
name|port
argument_list|)
expr_stmt|;
name|url
operator|=
operator|new
name|JMXServiceURL
argument_list|(
literal|"service:jmx:rmi:///jndi/rmi://localhost:"
operator|+
name|port
operator|+
literal|"/"
operator|+
name|DOMAIN
argument_list|)
expr_stmt|;
comment|// create MBean server
name|server
operator|=
name|MBeanServerFactory
operator|.
name|createMBeanServer
argument_list|(
name|DOMAIN
argument_list|)
expr_stmt|;
comment|// create JMXConnectorServer MBean
name|connector
operator|=
name|JMXConnectorServerFactory
operator|.
name|newJMXConnectorServer
argument_list|(
name|url
argument_list|,
name|Collections
operator|.
expr|<
name|String
argument_list|,
name|Object
operator|>
name|emptyMap
argument_list|()
argument_list|,
name|server
argument_list|)
expr_stmt|;
name|connector
operator|.
name|start
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|buildFromURI ()
specifier|protected
name|JMXUriBuilder
name|buildFromURI
parameter_list|()
block|{
name|String
name|uri
init|=
name|url
operator|.
name|toString
argument_list|()
decl_stmt|;
return|return
name|super
operator|.
name|buildFromURI
argument_list|()
operator|.
name|withServerName
argument_list|(
name|uri
argument_list|)
return|;
block|}
annotation|@
name|Test
DECL|method|notification ()
specifier|public
name|void
name|notification
parameter_list|()
throws|throws
name|Exception
block|{
name|getSimpleMXBean
argument_list|()
operator|.
name|touch
argument_list|()
expr_stmt|;
name|getMockFixture
argument_list|()
operator|.
name|waitForMessages
argument_list|()
expr_stmt|;
name|getMockFixture
argument_list|()
operator|.
name|assertMessageReceived
argument_list|(
operator|new
name|File
argument_list|(
literal|"src/test/resources/consumer-test/touched.xml"
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
|
924337e7f2ab9390d6748ee8d77d8266cc7708b0
| 9,676 |
java
|
Java
|
app/src/main/java/com/tdkankan/Presente/DialogCreater.java
|
yanfeng9611/TDKanKan
|
1677aee791a661d2117de04e1b7cea957f80044a
|
[
"MIT"
] | 2 |
2021-06-06T10:36:58.000Z
|
2021-09-05T14:47:56.000Z
|
app/src/main/java/com/tdkankan/Presente/DialogCreater.java
|
yanfeng9611/TDKanKan
|
1677aee791a661d2117de04e1b7cea957f80044a
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/tdkankan/Presente/DialogCreater.java
|
yanfeng9611/TDKanKan
|
1677aee791a661d2117de04e1b7cea957f80044a
|
[
"MIT"
] | 3 |
2021-06-27T08:52:48.000Z
|
2022-01-02T04:08:32.000Z
| 40.655462 | 121 | 0.603452 | 1,002,580 |
package com.tdkankan.Presente;
import android.app.Dialog;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import com.tdkankan.Data.GlobalConfig;
import com.tdkankan.Data.ReadConfig;
import com.tdkankan.R;
import com.tdkankan.UI.ReadingActivity;
/**
* @author ZQZESS
* @date 1/6/2021.
* @file DialogCreater
* GitHub:https://github.com/zqzess
* 不会停止运行的app不是好app w(゚Д゚)w
*/
public class DialogCreater {
public static Dialog createReadSetting(final ReadingActivity readingActivity,
final ReadPresenter readPresenter,
View.OnClickListener settingListener,
View.OnClickListener chapterListListener,
View.OnClickListener lastChapterListener,
View.OnClickListener nextChapterListener,
SeekBar.OnSeekBarChangeListener onSeekBarChangeListener) {
final Dialog dialog = new Dialog(readingActivity, R.style.jmui_default_dialog_style);
final View view = LayoutInflater.from(readingActivity).inflate(R.layout.dialog_read_setting, null);
dialog.setContentView(view);
//更多设置
LinearLayout MoreSetting = (LinearLayout) view.findViewById(R.id.layout_more_setting);
MoreSetting.setOnClickListener(settingListener);
/*
点击屏幕消失
*/
view.findViewById(R.id.rl_title_view).setOnClickListener(null);
view.findViewById(R.id.layout_bottom_view).setOnClickListener(null);
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
dialog.dismiss();
return false;
}
});
//夜间模式
LinearLayout NightAndDayChange=(LinearLayout)view.findViewById(R.id.layout_night_and_day);
final TextView tv_isDrak=(TextView)view.findViewById(R.id.tv_night_and_day);
final ImageView iv_isDrak=(ImageView)view.findViewById(R.id.iv_night_and_day);
if(ReadConfig.isDark)
{//isDrak默认false
iv_isDrak.setImageResource(R.mipmap.daylight);
tv_isDrak.setText("白天");
}
NightAndDayChange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tv_isDrak.getText().toString().equals("白天"))
{
ReadConfig.isDark=false;
iv_isDrak.setImageResource(R.mipmap.darkmoon);
tv_isDrak.setText("夜间");
readPresenter.DayAndNightChange(0);
ReadConfig.SaveSetting(readingActivity);//保存设置
}else
{
ReadConfig.isDark=true;
iv_isDrak.setImageResource(R.mipmap.daylight);
tv_isDrak.setText("白天");
readPresenter.DayAndNightChange(1);
ReadConfig.SaveSetting(readingActivity);//保存设置
}
}
});
/*
*目录
*/
LinearLayout layoutChapterList = (LinearLayout) view.findViewById(R.id.layout_chapter_list);
layoutChapterList.setOnClickListener(chapterListListener);
//上一章
TextView lastChapter=(TextView)view.findViewById(R.id.tv_last_chapter);
lastChapter.setOnClickListener(lastChapterListener);
//下一章
TextView nextChapter=(TextView)view.findViewById(R.id.tv_next_chapter);
nextChapter.setOnClickListener(nextChapterListener);
//章节跳转
SeekBar sbChapterProgress = (SeekBar) view.findViewById(R.id.sb_read_chapter_progress);
sbChapterProgress.setProgress(GlobalConfig.chapternow*100/(GlobalConfig.list.size()-1));
sbChapterProgress.setOnSeekBarChangeListener(onSeekBarChangeListener);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.show();
return dialog;
}
public static Dialog createReadDetailSetting(final ReadingActivity readingActivity,final ReadPresenter readPresenter)
{
/*
*详细设置
*/
final Dialog dialog = new Dialog(readingActivity, R.style.jmui_default_dialog_style);
final View view = LayoutInflater.from(readingActivity).inflate(R.layout.dialog_read_setting_detail, null);
dialog.setContentView(view);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
//触摸外部关闭
view.findViewById(R.id.layout_bottom_view).setOnClickListener(null);
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
dialog.dismiss();
return false;
}
});
//字体大小
TextView tvSizeReduce = (TextView) view.findViewById(R.id.tv_reduce_text_size);
TextView tvSizeIncrease = (TextView) view.findViewById(R.id.tv_increase_text_size);
final TextView tvSize = (TextView) view.findViewById(R.id.tv_text_size);
tvSize.setText(String.valueOf(setFontSizeView()));
tvSizeReduce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ReadConfig.FontSize>=53)
{//字体减小,单章页面变小
String tmp=tvSize.getText().toString();
int tmpcount= Integer.parseInt(tmp);
tvSize.setText(String.valueOf(tmpcount-1));
ReadConfig.FontSize-=3;
readPresenter.LoadChapterContent();
if(GlobalConfig.Page+1>=GlobalConfig.PageTotal)
{//如何字体变小前页码大于变小后总页码
GlobalConfig.Page=GlobalConfig.PageTotal-1;
}
readingActivity.tv_read.setImageBitmap(readPresenter.changePageContent(GlobalConfig.Page));
ReadConfig.SaveSetting(readingActivity);//保存设置
}
}
});
tvSizeIncrease.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ReadConfig.FontSize<=77)
{
//字体增大,单章页面变多
String tmp=tvSize.getText().toString();
int tmpcount= Integer.parseInt(tmp);
tvSize.setText(String.valueOf(tmpcount+1));
ReadConfig.FontSize+=3;
readPresenter.LoadChapterContent();
readingActivity.tv_read.setImageBitmap(readPresenter.changePageContent(GlobalConfig.Page));
ReadConfig.SaveSetting(readingActivity);//保存设置
}
}
});
//亮度调节
final SeekBar seekBar = (SeekBar) view.findViewById(R.id.sb_brightness_progress);
final TextView tvBrightFollowSystem = (TextView) view.findViewById(R.id.tv_system_brightness);
seekBar.setProgress(ReadConfig.appLight*100/255);
tvBrightFollowSystem.setSelected(ReadConfig.isSystemLight);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
GlobalConfig.setBrightness(readingActivity,progress*255/100);
ReadConfig.appLight=progress*255/100;
tvBrightFollowSystem.setSelected(false);
ReadConfig.SaveSetting(readingActivity);//保存设置
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
tvBrightFollowSystem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvBrightFollowSystem.setSelected(!tvBrightFollowSystem.isSelected());//设置未选择
if(tvBrightFollowSystem.isSelected())
{//跟随系统
WindowManager.LayoutParams lp = readingActivity.getWindow().getAttributes();
lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
readingActivity.getWindow().setAttributes(lp);
ReadConfig.isSystemLight=true;
ReadConfig.SaveSetting(readingActivity);//保存设置
}else
{//不跟随
// seekBar.setProgress(GlobalConfig.appLight*100/255);
GlobalConfig.setBrightness(readingActivity,ReadConfig.appLight);
ReadConfig.isSystemLight=false;
ReadConfig.SaveSetting(readingActivity);//保存设置
}
}
});
dialog.show();
return dialog;
}
public static int setFontSizeView()
{
int[] size={50,53,56,59,62,65,68,71,74,77,80};
int[] sizeview={20,21,22,23,24,25,26,27,28,29,30};
int result=20;
for(int i=0;i<size.length;i++)
{
if(ReadConfig.FontSize==size[i])
{
result=sizeview[i];
return result;
}
}
return result;
}
}
|
924338cb9a3a019a7ad5847450ef4b91fd64e0ec
| 1,892 |
java
|
Java
|
uyTube - Parte 3/uyTube - Servidor Web/src/logica/webservices/ListaHistorialDt.java
|
ElLucioVpe/uytube
|
848ddd9629a88aafdcb71484513b73220761da62
|
[
"MIT"
] | 1 |
2021-11-17T17:30:01.000Z
|
2021-11-17T17:30:01.000Z
|
uyTube - Parte 3/uyTube - Servidor Web/src/logica/webservices/ListaHistorialDt.java
|
ElLucioVpe/uytube
|
848ddd9629a88aafdcb71484513b73220761da62
|
[
"MIT"
] | null | null | null |
uyTube - Parte 3/uyTube - Servidor Web/src/logica/webservices/ListaHistorialDt.java
|
ElLucioVpe/uytube
|
848ddd9629a88aafdcb71484513b73220761da62
|
[
"MIT"
] | null | null | null | 26.277778 | 119 | 0.640592 | 1,002,581 |
package logica.webservices;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para listaHistorialDt complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType name="listaHistorialDt">
* <complexContent>
* <extension base="{http://webservices.logica/}listaDeReproduccionDt">
* <sequence>
* <element name="visitas" type="{http://webservices.logica/}visitaDt" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "listaHistorialDt", propOrder = {
"visitas"
})
public class ListaHistorialDt
extends ListaDeReproduccionDt
{
@XmlElement(nillable = true)
protected List<VisitaDt> visitas;
/**
* Gets the value of the visitas property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the visitas property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getVisitas().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link VisitaDt }
*
*
*/
public List<VisitaDt> getVisitas() {
if (visitas == null) {
visitas = new ArrayList<VisitaDt>();
}
return this.visitas;
}
}
|
9243394fc3bd220efb7c7fbf65c2a5dcfea80256
| 2,582 |
java
|
Java
|
src/main/java/org/gbif/ws/client/ClientRetryer.java
|
gbif/gbif-common-ws
|
beda3725621a9d77c9e88aa106f14e1886c5ffb2
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/gbif/ws/client/ClientRetryer.java
|
gbif/gbif-common-ws
|
beda3725621a9d77c9e88aa106f14e1886c5ffb2
|
[
"Apache-2.0"
] | 6 |
2017-06-14T04:20:49.000Z
|
2021-05-27T14:02:11.000Z
|
src/main/java/org/gbif/ws/client/ClientRetryer.java
|
gbif/gbif-common-ws
|
beda3725621a9d77c9e88aa106f14e1886c5ffb2
|
[
"Apache-2.0"
] | 2 |
2017-06-14T04:24:17.000Z
|
2020-02-17T03:03:03.000Z
| 27.763441 | 100 | 0.680093 | 1,002,582 |
/*
* 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.gbif.ws.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import feign.RetryableException;
import feign.Retryer;
@SuppressWarnings("unused")
public class ClientRetryer implements Retryer {
private static final Logger LOG = LoggerFactory.getLogger(ClientRetryer.class);
private final int maxAttempts;
private final long period;
private final double multiplier;
int attempt;
long sleptForMillis;
public ClientRetryer() {
this(1000, 3, 1.5);
}
public ClientRetryer(long period, int maxAttempts, double multiplier) {
this.period = period;
this.maxAttempts = maxAttempts;
this.multiplier = multiplier;
this.attempt = 1;
}
protected long currentTimeMillis() {
return System.currentTimeMillis();
}
@Override
public void continueOrPropagate(RetryableException e) {
if (attempt++ >= maxAttempts) {
LOG.error(
"All {} retry attempts failed. Giving up. Last execution was: '{}: {}'",
maxAttempts,
e.getClass().getSimpleName(),
e.getMessage());
throw e;
}
long interval;
if (e.retryAfter() != null) {
interval = e.retryAfter().getTime() - currentTimeMillis();
if (interval < 0) {
return;
}
} else {
interval = nextMaxInterval();
}
try {
Thread.sleep(interval);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
throw e;
}
sleptForMillis += interval;
}
/**
* Calculates the time interval to a retry attempt. <br>
* The interval increases exponentially with each attempt, at a rate of nextInterval *= multiplier
* (where multiplier is the backoff factor), to the maximum interval.
*
* @return time in nanoseconds from now until the next attempt.
*/
long nextMaxInterval() {
return (long) (period * Math.pow(multiplier, attempt - 1));
}
@Override
public Retryer clone() {
return new ClientRetryer(period, maxAttempts, multiplier);
}
}
|
92433a356e6a5c3413088ff085a261a058c3dba2
| 1,078 |
java
|
Java
|
mFinance/src/main/java/edu/psu/ist412/mFinance/models/ApplicationUserSecurityPrincipal.java
|
IST412-FA19/mFinanceMaven
|
05ef5a6b348a9a11fa5578cab4840bd92035ee02
|
[
"MIT"
] | 1 |
2019-11-07T20:18:39.000Z
|
2019-11-07T20:18:39.000Z
|
mFinance/src/main/java/edu/psu/ist412/mFinance/models/ApplicationUserSecurityPrincipal.java
|
IST412-FA19/mFinanceMaven
|
05ef5a6b348a9a11fa5578cab4840bd92035ee02
|
[
"MIT"
] | 3 |
2019-12-07T23:06:30.000Z
|
2019-12-09T03:56:33.000Z
|
mFinance/src/main/java/edu/psu/ist412/mFinance/models/ApplicationUserSecurityPrincipal.java
|
IST412-FA19/mFinanceGradle
|
05ef5a6b348a9a11fa5578cab4840bd92035ee02
|
[
"MIT"
] | null | null | null | 22.93617 | 79 | 0.707792 | 1,002,583 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.psu.ist412.mFinance.models;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author garre
*/
@Entity
public class ApplicationUserSecurityPrincipal implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
@Column(nullable = false, unique = true)
private String principalName;
public ApplicationUserSecurityPrincipal() {}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPrincipalName() {
return principalName;
}
public void setPrincipalName(String principalName) {
this.principalName = principalName;
}
}
|
92433b46df0c829dd2c29812a82bdfcb21373c38
| 23,077 |
java
|
Java
|
library/src/main/java/org/mustangproject/ZUGFeRD/OXExporterFromA3.java
|
invenius/mustangproject
|
f66780cabbfbd15107001d004d1cc1d792bceccd
|
[
"Apache-2.0"
] | null | null | null |
library/src/main/java/org/mustangproject/ZUGFeRD/OXExporterFromA3.java
|
invenius/mustangproject
|
f66780cabbfbd15107001d004d1cc1d792bceccd
|
[
"Apache-2.0"
] | null | null | null |
library/src/main/java/org/mustangproject/ZUGFeRD/OXExporterFromA3.java
|
invenius/mustangproject
|
f66780cabbfbd15107001d004d1cc1d792bceccd
|
[
"Apache-2.0"
] | null | null | null | 32.920114 | 158 | 0.728171 | 1,002,584 |
/**
* *********************************************************************
* <p>
* Copyright 2020 Jochen Staerk
* <p>
* Use is subject to license terms.
* <p>
* 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.
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* <p>
* See the License for the specific language governing permissions and
* limitations under the License.
* <p>
* **********************************************************************
*/
package org.mustangproject.ZUGFeRD;
import org.apache.pdfbox.cos.*;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDMarkInfo;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType2;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.color.PDOutputIntent;
import org.apache.pdfbox.preflight.utils.ByteArrayDataSource;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.PDFAIdentificationSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.type.ArrayProperty;
import org.apache.xmpbox.type.BadFieldValueException;
import org.apache.xmpbox.xml.DomXmpParser;
import org.apache.xmpbox.xml.XmpParsingException;
import org.apache.xmpbox.xml.XmpSerializer;
import org.mustangproject.EStandard;
import org.mustangproject.FileAttachment;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.xml.transform.TransformerException;
import java.io.*;
import java.util.*;
public class OXExporterFromA3 extends ZUGFeRDExporterFromA3 {
protected PDFAConformanceLevel conformanceLevel = PDFAConformanceLevel.UNICODE;
protected ArrayList<FileAttachment> fileAttachments = new ArrayList<FileAttachment>();
/**
* This flag controls whether or not the metadata is overwritten, or kind of merged.
* The merging probably needs to be overhauled, but for my purpose it was good enough.
*/
protected boolean overwrite = true;
private boolean disableAutoClose;
private boolean fileAttached = false;
private Profile profile = null;
private boolean documentPrepared = false;
/**
* Data (XML invoice) to be added to the ZUGFeRD PDF. It may be externally set,
* in which case passing a IZUGFeRDExportableTransaction is not necessary. By
* default it is null meaning the caller needs to pass a
* IZUGFeRDExportableTransaction for the XML to be populated.
*/
protected PDMetadata metadata = null;
/**
* Producer attribute for PDF
*/
protected String producer = "mustangproject";
/**
* Author/Creator attribute for PDF
*/
protected String creator = "mustangproject";
/**
* CreatorTool
*/
protected String creatorTool = "mustangproject";
/**
* @deprecated author is never set yet
*/
@Deprecated
protected String author;
/**
* @deprecated title is never set yet
*/
@Deprecated
protected String title;
/**
* @deprecated subject is never set yet
*/
@Deprecated
protected String subject;
/**
* OrderX document type. As of version 1.0 it may be
* ORDER, ORDER_RESPONSE, or ORDER_CHANGE
*/
protected String orderXDocumentType = "ORDER";
private HashMap<String, byte[]> additionalXMLs = new HashMap<String, byte[]>();
private boolean attachZUGFeRDHeaders = true;
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfFilename filename of an PDF/A1 compliant document
*/
public OXExporterFromA3 load(String pdfFilename) throws IOException {
ensurePDFIsValid(new FileDataSource(pdfFilename));
try (FileInputStream pdf = new FileInputStream(pdfFilename)) {
return load(readAllBytes(pdf));
}
}
public IXMLProvider getProvider() {
return xmlProvider;
}
public OXExporterFromA3 setProfile(Profile p) {
this.profile = p;
if (xmlProvider != null) {
xmlProvider.setProfile(p);
}
return this;
}
public OXExporterFromA3 setProfile(String profilename) {
this.profile = Profiles.getByName(profilename);
if (xmlProvider != null) {
xmlProvider.setProfile(this.profile);
}
return this;
}
public OXExporterFromA3 addAdditionalFile(String name, byte[] content) {
fileAttachments.add(new FileAttachment(name, "text/xml", "Supplement", content).setDescription("ZUGFeRD extension/additional data"));
return this;
}
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfBinary binary of a PDF/A1 compliant document
*/
public OXExporterFromA3 load(byte[] pdfBinary) throws IOException {
ensurePDFIsValid(new ByteArrayDataSource(new ByteArrayInputStream(pdfBinary)));
doc = PDDocument.load(pdfBinary);
return this;
}
public OXExporterFromA3() {
super();
}
public void attachFile(FileAttachment file) {
fileAttachments.add(file);
}
public void attachFile(String filename, byte[] data, String mimetype, String relation) {
FileAttachment fa = new FileAttachment(filename, mimetype, relation, data);
fileAttachments.add(fa);
}
/***
* Perform the final export to a now ZUGFeRD-enriched PDF file
* @param ZUGFeRDfilename the pdf file name
* @throws IOException if anything is wrong in the target location
*/
public void export(String ZUGFeRDfilename) throws IOException {
if (!documentPrepared) {
prepareDocument();
}
if ((!fileAttached) && (attachZUGFeRDHeaders)) {
throw new IOException(
"File must be attached (usually with setTransaction) before perfoming this operation");
}
doc.save(ZUGFeRDfilename);
if (!disableAutoClose) {
close();
}
}
@Override
public void close() throws IOException {
if (doc != null) {
doc.close();
}
}
/***
* Perform the final export to a now ZUGFeRD-enriched PDF file as OutputStream
* @param output the OutputStream
* @throws IOException if anything is wrong in the OutputStream
*/
public void export(OutputStream output) throws IOException {
if (!documentPrepared) {
prepareDocument();
}
if ((!fileAttached) && (attachZUGFeRDHeaders)) {
throw new IOException(
"File must be attached (usually with setTransaction) before perfoming this operation");
}
doc.save(output);
if (!disableAutoClose) {
close();
}
}
/**
* Embeds an external file (generic - any type allowed) in the PDF.
* The embedding is done in the default PDF document.
*
* @param filename name of the file that will become attachment name in the PDF
* @param relationship how the file relates to the content, e.g. "Alternative"
* @param description Human-readable description of the file content
* @param subType type of the data e.g. could be "text/xml" - mime like
* @param data the binary data of the file/attachment
* @throws java.io.IOException if anything is wrong with filename
*/
public void PDFAttachGenericFile(String filename, String relationship, String description,
String subType, byte[] data) throws IOException {
PDFAttachGenericFile(this.doc, filename, relationship, description, subType, data);
}
/**
* Embeds an external file (generic - any type allowed) in the PDF.
*
* @param doc PDDocument to attach the file to.
* @param filename name of the file that will become attachment name in the PDF
* @param relationship how the file relates to the content, e.g. "Alternative"
* @param description Human-readable description of the file content
* @param subType type of the data e.g. could be "text/xml" - mime like
* @param data the binary data of the file/attachment
* @throws IOException if anything is wrong with filename
*/
public void PDFAttachGenericFile(PDDocument doc, String filename, String relationship, String description,
String subType, byte[] data) throws IOException {
fileAttached = true;
PDComplexFileSpecification fs = new PDComplexFileSpecification();
fs.setFile(filename);
COSDictionary dict = fs.getCOSObject();
dict.setName("AFRelationship", relationship);
dict.setString("UF", filename);
dict.setString("Desc", description);
ByteArrayInputStream fakeFile = new ByteArrayInputStream(data);
PDEmbeddedFile ef = new PDEmbeddedFile(doc, fakeFile);
// ef.addCompression();
ef.setSubtype(subType);
ef.setSize(data.length);
ef.setCreationDate(new GregorianCalendar());
ef.setModDate(GregorianCalendar.getInstance());
fs.setEmbeddedFile(ef);
// In addition make sure the embedded file is set under /UF
dict = fs.getCOSObject();
COSDictionary efDict = (COSDictionary) dict.getDictionaryObject(COSName.EF);
COSBase lowerLevelFile = efDict.getItem(COSName.F);
efDict.setItem(COSName.UF, lowerLevelFile);
// now add the entry to the embedded file tree and set in the document.
PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
PDEmbeddedFilesNameTreeNode efTree = names.getEmbeddedFiles();
if (efTree == null) {
efTree = new PDEmbeddedFilesNameTreeNode();
}
Map<String, PDComplexFileSpecification> namesMap = new HashMap<>();
Map<String, PDComplexFileSpecification> oldNamesMap = efTree.getNames();
if (oldNamesMap != null) {
for (String key : oldNamesMap.keySet()) {
namesMap.put(key, oldNamesMap.get(key));
}
}
namesMap.put(filename, fs);
efTree.setNames(namesMap);
names.setEmbeddedFiles(efTree);
doc.getDocumentCatalog().setNames(names);
// AF entry (Array) in catalog with the FileSpec
COSBase AFEntry = (COSBase) doc.getDocumentCatalog().getCOSObject().getItem("AF");
if ((AFEntry == null)) {
COSArray cosArray = new COSArray();
cosArray.add(fs);
doc.getDocumentCatalog().getCOSObject().setItem("AF", cosArray);
} else if (AFEntry instanceof COSArray) {
COSArray cosArray = (COSArray) AFEntry;
cosArray.add(fs);
doc.getDocumentCatalog().getCOSObject().setItem("AF", cosArray);
} else if ((AFEntry instanceof COSObject) &&
((COSObject) AFEntry).getObject() instanceof COSArray) {
COSArray cosArray = (COSArray) ((COSObject) AFEntry).getObject();
cosArray.add(fs);
} else {
throw new IOException("Unexpected object type for PDFDocument/Catalog/COSDictionary/Item(AF)");
}
}
/**
* Sets the ZUGFeRD XML data to be attached as a single byte array. This is
* useful for use-cases where the XML has already been produced by some external
* API or component.
*
* @param zugferdData XML data to be set as a byte array (XML file in raw form).
* @throws IOException (should not happen)
*/
public OXExporterFromA3 setXML(byte[] zugferdData) throws IOException {
CustomXMLProvider cus = new CustomXMLProvider();
cus.setXML(zugferdData);
this.setXMLProvider(cus);
prepare();
return this;
}
/**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on the
* metadata level, this will not e.g. convert graphics to JPG-2000)
*
* @param pdfSource source to read a PDF/A1 compliant document from
*/
public OXExporterFromA3 load(InputStream pdfSource) throws IOException {
return load(readAllBytes(pdfSource));
}
public boolean ensurePDFIsValid(final DataSource dataSource) throws IOException {
return true;
}
private static byte[] readAllBytes(InputStream in) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
IOUtils.copy(in, buffer);
return buffer.toByteArray();
}
/**
* All files are PDF/A-3, setConformance refers to the level conformance.
* <p>
* PDF/A-3 has three coformance levels, called "A", "U" and "B".
* <p>
* PDF/A-3-B where B means only visually preservable, U -standard for Mustang-
* means visually and unicode preservable and A means full compliance, i.e.
* visually, unicode and structurally preservable and tagged PDF, i.e. useful
* metainformation for blind people.
* <p>
* Feel free to pass "A" as new level if you know what you are doing :-)
*/
public OXExporterFromA3 setConformanceLevel(PDFAConformanceLevel newLevel) {
conformanceLevel = newLevel;
return this;
}
public OXExporterFromA3 setCreator(String creator) {
this.creator = creator;
return this;
}
public OXExporterFromA3 setCreatorTool(String creatorTool) {
this.creatorTool = creatorTool;
return this;
}
public OXExporterFromA3 setProducer(String producer) {
this.producer = producer;
return this;
}
/**
* Sets the property orderXDocumentType.
*
* @param orderXDocumentType new value. Expected: ORDER, ORDER_RESPONSE, or ORDER_CHANGE
*
* @return this exporter
*/
public OXExporterFromA3 setOrderXDocumentType(String orderXDocumentType)
{
this.orderXDocumentType = orderXDocumentType;
return this;
}
protected OXExporterFromA3 setAttachZUGFeRDHeaders(boolean attachHeaders) {
this.attachZUGFeRDHeaders = attachHeaders;
return this;
}
/**
* This will add both the RDF-indication which embedded file is Zugferd and the
* neccessary PDF/A schema extension description to be able to add this
* information to RDF
*
* @param metadata the PDFbox XMPMetadata object
*/
protected void addXMP(XMPMetadata metadata) {
if (attachZUGFeRDHeaders) {
XMPSchemaZugferd zf = new XMPSchemaZugferd(metadata, 1, true, xmlProvider.getProfile(),
"urn:factur-x:pdfa:CrossIndustryDocument:1p0#", "fx",
"order-x.xml");
zf.setType(this.orderXDocumentType);
metadata.addSchema(zf);
// also add the schema extensions...
XMPSchemaPDFAExtensions pdfaex = new XMPSchemaPDFAExtensions(this, metadata, 1, attachZUGFeRDHeaders, EStandard.orderx);
pdfaex.setZUGFeRDVersion(1);
metadata.addSchema(pdfaex);
}
}
/**
* Embeds the Zugferd XML structure in a file named ZUGFeRD-invoice.xml.
*
* @param trans a IZUGFeRDExportableTransaction that provides the data-model to
* populate the XML. This parameter may be null, if so the XML data
* should hav ebeen set via
* <code>setZUGFeRDXMLData(byte[] zugferdData)</code>
* @throws IOException if anything is wrong with already loaded PDF
*/
public IExporter setTransaction(IExportableTransaction trans) throws IOException {
this.trans = trans;
return prepare();
}
public IExporter prepare() throws IOException {
prepareDocument();
xmlProvider.generateXML(trans);
String filename = "order-x.xml";
PDFAttachGenericFile(doc, filename, "Alternative",
"Order metadata conforming to the Order-X standard (https://www.ferd-net.de/standards/order-x/index.html)",
"text/xml", xmlProvider.getXML());
for (FileAttachment attachment : fileAttachments) {
PDFAttachGenericFile(doc, attachment.getFilename(), attachment.getRelation(), attachment.getDescription(), attachment.getMimetype(), attachment.getData());
}
return this;
}
/**
* Reads the XMPMetadata from the PDDocument, if it exists.
* Otherwise creates XMPMetadata.
*/
protected XMPMetadata getXmpMetadata() throws IOException {
PDMetadata meta = doc.getDocumentCatalog().getMetadata();
if ((meta != null) && (meta.getLength() > 0)) {
try {
DomXmpParser xmpParser = new DomXmpParser();
return xmpParser.parse(meta.toByteArray());
} catch (XmpParsingException | IOException e) {
throw new IOException(e);
}
}
return XMPMetadata.createXMPMetadata();
}
protected byte[] serializeXmpMetadata(XMPMetadata xmpMetadata) throws TransformerException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
new XmpSerializer().serialize(xmpMetadata, buffer, true); // see https://github.com/ZUGFeRD/mustangproject/issues/44
return buffer.toByteArray();
}
/**
* Sets the producer if the overwrite flag is set or the producer is not already set.
* Sets the PDFVersion to 1.4 if the field is empty.
*/
protected void writeAdobePDFSchema(XMPMetadata xmp) {
AdobePDFSchema pdf = getAdobePDFSchema(xmp);
if (overwrite || isEmpty(pdf.getProducer()))
pdf.setProducer(producer);
}
/**
* Returns the AdobePDFSchema from the XMPMetadata if it exists.
* If the overwrite flag is set or no AdobePDFSchema exists in the XMPMetadata, it is created, added and returned.
*/
protected AdobePDFSchema getAdobePDFSchema(XMPMetadata xmp) {
AdobePDFSchema pdf = xmp.getAdobePDFSchema();
if (pdf != null)
if (overwrite)
xmp.removeSchema(pdf);
else
return pdf;
return xmp.createAndAddAdobePDFSchema();
}
protected void writePDFAIdentificationSchema(XMPMetadata xmp) {
PDFAIdentificationSchema pdfaid = getPDFAIdentificationSchema(xmp);
if (overwrite || isEmpty(pdfaid.getConformance())) {
try {
pdfaid.setConformance(conformanceLevel.getLetter());
} catch (BadFieldValueException ex) {
// This should be impossible, because it would occur only if an illegal
// conformance level is supplied,
// however the enum enforces that the conformance level is valid.
throw new RuntimeException(ex);
}
}
pdfaid.setPart(3);
}
protected PDFAIdentificationSchema getPDFAIdentificationSchema(XMPMetadata xmp) {
PDFAIdentificationSchema pdfaid = xmp.getPDFIdentificationSchema();
if (pdfaid != null)
if (overwrite)
xmp.removeSchema(pdfaid);
else
return pdfaid;
return xmp.createAndAddPFAIdentificationSchema();
}
protected void writeDublinCoreSchema(XMPMetadata xmp) {
DublinCoreSchema dc = getDublinCoreSchema(xmp);
if (dc.getFormat() == null)
dc.setFormat("application/pdf");
if ((overwrite || dc.getCreators() == null || dc.getCreators().isEmpty()) && creator != null)
dc.addCreator(creator);
if ((overwrite || dc.getDates() == null || dc.getDates().isEmpty()) && creator != null)
dc.addDate(Calendar.getInstance());
ArrayProperty titleProperty = dc.getTitleProperty();
if (titleProperty != null) {
if (overwrite && !isEmpty(title)) {
dc.removeProperty(titleProperty);
dc.setTitle(title);
} else if (titleProperty.getElementsAsString().stream().anyMatch("Untitled"::equalsIgnoreCase)) {
// remove unfitting ghostscript default
dc.removeProperty(titleProperty);
}
} else if (!isEmpty(title)) {
dc.setTitle(title);
}
}
protected DublinCoreSchema getDublinCoreSchema(XMPMetadata xmp) {
DublinCoreSchema dc = xmp.getDublinCoreSchema();
if (dc != null)
if (overwrite)
xmp.removeSchema(dc);
else
return dc;
return xmp.createAndAddDublinCoreSchema();
}
protected void writeXMLBasicSchema(XMPMetadata xmp) {
XMPBasicSchema xsb = getXmpBasicSchema(xmp);
if (overwrite || isEmpty(xsb.getCreatorTool()) || "UnknownApplication".equals(xsb.getCreatorTool()))
xsb.setCreatorTool(creatorTool);
if (overwrite || xsb.getCreateDate() == null)
xsb.setCreateDate(GregorianCalendar.getInstance());
}
protected XMPBasicSchema getXmpBasicSchema(XMPMetadata xmp) {
XMPBasicSchema xsb = xmp.getXMPBasicSchema();
if (xsb != null)
if (overwrite)
xmp.removeSchema(xsb);
else
return xsb;
return xmp.createAndAddXMPBasicSchema();
}
protected void writeDocumentInformation() {
String fullProducer = producer + " (via mustangproject.org " + Version.VERSION + ")";
PDDocumentInformation info = doc.getDocumentInformation();
if (overwrite || info.getCreationDate() == null)
info.setCreationDate(Calendar.getInstance());
if (overwrite || info.getModificationDate() == null)
info.setModificationDate(Calendar.getInstance());
if (overwrite || (isEmpty(info.getAuthor()) && !isEmpty(author)))
info.setAuthor(author);
if (overwrite || (isEmpty(info.getProducer()) && !isEmpty(fullProducer)))
info.setProducer(fullProducer);
if (overwrite || (isEmpty(info.getCreator()) && !isEmpty(creator)))
info.setCreator(creator);
if (overwrite || (isEmpty(info.getTitle()) && !isEmpty(title)))
info.setTitle(title);
if (overwrite || (isEmpty(info.getSubject()) && !isEmpty(subject)))
info.setSubject(subject);
}
/**
* Adds an OutputIntent and the sRGB color profile if no OutputIntent exist
*/
protected void addSRGBOutputIntend() throws IOException {
if (!doc.getDocumentCatalog().getOutputIntents().isEmpty()) {
return;
}
try {
InputStream colorProfile = Thread.currentThread().getContextClassLoader().getResourceAsStream("sRGB.icc");
if (colorProfile != null) {
PDOutputIntent intent = new PDOutputIntent(doc, colorProfile);
intent.setInfo("sRGB IEC61966-2.1");
intent.setOutputCondition("sRGB IEC61966-2.1");
intent.setOutputConditionIdentifier("sRGB IEC61966-2.1");
intent.setRegistryName("http://www.color.org");
doc.getDocumentCatalog().addOutputIntent(intent);
}
} catch (IOException e) {
throw e;
}
}
/**
* Adds a MarkInfo element to the PDF if it doesn't already exist and sets it as marked.
*/
protected void setMarked() {
PDDocumentCatalog catalog = doc.getDocumentCatalog();
if (catalog.getMarkInfo() == null) {
catalog.setMarkInfo(new PDMarkInfo(doc.getPages().getCOSObject()));
}
catalog.getMarkInfo().setMarked(true);
}
/**
* Adds a StructureTreeRoot element to the PDF if it doesn't already exist.
*/
protected void addStructureTreeRoot() {
if (doc.getDocumentCatalog().getStructureTreeRoot() == null) {
doc.getDocumentCatalog().setStructureTreeRoot(new PDStructureTreeRoot());
}
}
/**
* @return if pdf file will be automatically closed after adding ZF
*/
public boolean isAutoCloseDisabled() {
return disableAutoClose;
}
/**
* @param disableAutoClose prevent PDF file from being closed after adding ZF
*/
public OXExporterFromA3 disableAutoClose(boolean disableAutoClose) {
this.disableAutoClose = disableAutoClose;
return this;
}
protected void setXMLProvider(IXMLProvider p) {
this.xmlProvider = p;
if (profile != null) {
xmlProvider.setProfile(profile);
}
}
@Override
public OXExporterFromA3 setZUGFeRDVersion(int version) {
OXPullProvider z2p = new OXPullProvider();
setXMLProvider(z2p);
return this;
}
/**
* Utility method inspired by apache commons-lang3 StringUtils.
*
* @param string the string to test
* @return true if the string is null or empty
*/
private boolean isEmpty(String string) {
return string == null || string.isEmpty();
}
}
|
92433bfc83a69625b49af5f853a5e0e2b23c7410
| 467 |
java
|
Java
|
src/main/java/contour/draw/spatial/BorderLine.java
|
Arctic-0/jcontour
|
13ba43c7eff258505508b505f0d967090dcb8668
|
[
"MIT"
] | 1 |
2022-02-23T01:41:05.000Z
|
2022-02-23T01:41:05.000Z
|
src/main/java/contour/draw/spatial/BorderLine.java
|
Arctic-0/jcontour
|
13ba43c7eff258505508b505f0d967090dcb8668
|
[
"MIT"
] | null | null | null |
src/main/java/contour/draw/spatial/BorderLine.java
|
Arctic-0/jcontour
|
13ba43c7eff258505508b505f0d967090dcb8668
|
[
"MIT"
] | null | null | null | 19.666667 | 57 | 0.694915 | 1,002,585 |
/*
* Copyright 2012 Yaqiang Wang,
* [email protected]
*/
package contour.draw.spatial;
import java.util.ArrayList;
import java.util.List;
/**
* BorderLine class
*
* @author Yaqiang Wang
*/
public class BorderLine {
public double area;
public Extent extent = new Extent();
public boolean isOutLine;
public boolean isClockwise;
public List<PointD> pointList = new ArrayList<>();
public List<IJPoint> ijPointList = new ArrayList<>();
}
|
92433d7fee5afed6a799638265d55debdcacf4f7
| 7,436 |
java
|
Java
|
gemfire-junit/src/main/java/com/gemstone/gemfire/cache/hdfs/internal/hoplog/mapreduce/GFRecordReaderJUnitTest.java
|
xyxiaoyou/snappy-store
|
013ff282f888878cc99600e260ec1cde60112304
|
[
"Apache-2.0"
] | 38 |
2016-01-04T01:31:40.000Z
|
2020-04-07T06:35:36.000Z
|
gemfire-junit/src/main/java/com/gemstone/gemfire/cache/hdfs/internal/hoplog/mapreduce/GFRecordReaderJUnitTest.java
|
xyxiaoyou/snappy-store
|
013ff282f888878cc99600e260ec1cde60112304
|
[
"Apache-2.0"
] | 261 |
2016-01-07T09:14:26.000Z
|
2019-12-05T10:15:56.000Z
|
gemfire-junit/src/main/java/com/gemstone/gemfire/cache/hdfs/internal/hoplog/mapreduce/GFRecordReaderJUnitTest.java
|
xyxiaoyou/snappy-store
|
013ff282f888878cc99600e260ec1cde60112304
|
[
"Apache-2.0"
] | 22 |
2016-03-09T05:47:09.000Z
|
2020-04-02T17:55:30.000Z
| 36.995025 | 99 | 0.683029 | 1,002,586 |
/*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.cache.hdfs.internal.hoplog.mapreduce;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import io.snappydata.test.dunit.AvailablePortHelper;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit;
import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl;
import com.gemstone.gemfire.cache.hdfs.internal.PersistedEventImpl;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.BaseHoplogTestCase;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.HFileSortedOplog;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.HdfsSortedOplogOrganizer;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.HoplogConfig;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.HoplogSetReader.HoplogIterator;
import com.gemstone.gemfire.internal.util.BlobHelper;
public class GFRecordReaderJUnitTest extends BaseHoplogTestCase {
MiniDFSCluster cluster;
private int CLUSTER_PORT = AvailablePortHelper.getRandomAvailableTCPPort();
private File configFile;
Path regionPath = null;
/*
* Test splits cover all the data in the hoplog
*/
public void testGFRecordReader1HopNBlocks() throws Exception {
cluster = super.initMiniCluster(CLUSTER_PORT, 1);
int count = 200;
HdfsSortedOplogOrganizer bucket1 = new HdfsSortedOplogOrganizer(
regionManager, 1);
ArrayList<TestEvent> items = new ArrayList<TestEvent>();
for (int i = 0; i < count; i++) {
items.add(new TestEvent(("key-" + i), ("value-" + System.nanoTime())));
}
bucket1.flush(items.iterator(), count);
HFileSortedOplog hoplog = (HFileSortedOplog) bucket1.getSortedOplogs().iterator().next().get();
int blockCount = (int) (hoplog.getSize() / 4096) + 1;
assertTrue(1 < blockCount);
Configuration conf = hdfsStore.getFileSystem().getConf();
GFInputFormat gfInputFormat = new GFInputFormat();
Job job = Job.getInstance(conf, "test");
conf = job.getConfiguration();
conf.set(GFInputFormat.INPUT_REGION, getName());
conf.set(GFInputFormat.HOME_DIR, testDataDir.getName());
conf.setBoolean(GFInputFormat.CHECKPOINT, false);
List<InputSplit> splits = gfInputFormat.getSplits(job);
assertEquals(blockCount, splits.size());
CombineFileSplit split = (CombineFileSplit) splits.get(1);
HoplogIterator<byte[], byte[]> directIter = hoplog.getReader().scan(
split.getOffset(0), split.getLength(0));
TaskAttemptContext context = new TaskAttemptContextImpl(conf,
new TaskAttemptID());
RecordReader<GFKey, PersistedEventImpl> reader = gfInputFormat
.createRecordReader(splits.get(1), context);
reader.initialize(splits.get(1), context);
for (; directIter.hasNext();) {
assertTrue(reader.nextKeyValue());
directIter.next();
assertEquals(BlobHelper.deserializeBlob(directIter.getKey()),
reader.getCurrentKey().getKey());
}
assertFalse(reader.nextKeyValue());
hoplog.close();
}
public void testGFRecordReaderNHop1Split() throws Exception {
cluster = super.initMiniCluster(CLUSTER_PORT, 1);
int entryCount = 2;
int bucketCount = 3;
HashSet<String> keySet = new HashSet<String>();
for (int j = 0; j < bucketCount; j++) {
HdfsSortedOplogOrganizer bucket = new HdfsSortedOplogOrganizer(
regionManager, j);
ArrayList<TestEvent> items = new ArrayList<TestEvent>();
for (int i = 0; i < entryCount; i++) {
String key = "key - " + j + " : " + i;
items.add(new TestEvent(key, ("value-" + System.nanoTime())));
keySet.add(key);
}
bucket.flush(items.iterator(), entryCount);
}
assertEquals(entryCount * bucketCount, keySet.size());
Configuration conf = hdfsStore.getFileSystem().getConf();
GFInputFormat gfInputFormat = new GFInputFormat();
Job job = Job.getInstance(conf, "test");
conf = job.getConfiguration();
conf.set(GFInputFormat.INPUT_REGION, getName());
conf.set(GFInputFormat.HOME_DIR, testDataDir.getName());
conf.setBoolean(GFInputFormat.CHECKPOINT, false);
List<InputSplit> splits = gfInputFormat.getSplits(job);
assertEquals(1, splits.size());
CombineFileSplit split = (CombineFileSplit) splits.get(0);
assertEquals(bucketCount, split.getNumPaths());
TaskAttemptContext context = new TaskAttemptContextImpl(conf,
new TaskAttemptID());
RecordReader<GFKey, PersistedEventImpl> reader = gfInputFormat
.createRecordReader(split, context);
reader.initialize(split, context);
while (reader.nextKeyValue()) {
keySet.remove(reader.getCurrentKey().getKey());
}
assertEquals(0, keySet.size());
reader.close();
}
@Override
protected void configureHdfsStoreFactory() throws Exception {
super.configureHdfsStoreFactory();
System.setProperty(HoplogConfig.HFILE_BLOCK_SIZE_CONF,
String.valueOf(1 << 8));
configFile = new File("testGFInputFormat-config");
String hadoopClientConf = "<configuration>\n "
+ " <property>\n "
+ " <name>dfs.block.size</name>\n "
+ " <value>4096</value>\n "
+ " </property>\n "
+ " <property>\n "
+ " <name>fs.default.name</name>\n "
+ " <value>hdfs://127.0.0.1:" + CLUSTER_PORT + "</value>\n"
+ " </property>\n "
+ "</configuration>";
BufferedWriter bw = new BufferedWriter(new FileWriter(configFile));
bw.write(hadoopClientConf);
bw.close();
hsf.setHDFSClientConfigFile(configFile.getName());
}
@Override
protected void setUp() throws Exception {
CLUSTER_PORT = AvailablePortHelper.getRandomAvailableTCPPort();
super.setUp();
regionPath = new Path(testDataDir, getName());
}
@Override
protected void tearDown() throws Exception {
if (configFile != null) {
configFile.delete();
}
super.tearDown();
if (cluster != null) {
cluster.shutdown();
FileUtils.deleteDirectory(new File("hdfs-test-cluster"));
}
}
}
|
92433d8bb3a20e810c3684976c7bf7bc6ff1d0dc
| 25,236 |
java
|
Java
|
projects/starling-client/src/test/java/com/mcleodmoores/starling/client/fpml5_8/ExchangeRateTest.java
|
McLeodMoores/starling
|
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
|
[
"Apache-2.0"
] | 3 |
2017-12-18T09:32:40.000Z
|
2021-03-08T20:05:54.000Z
|
projects/starling-client/src/test/java/com/mcleodmoores/starling/client/fpml5_8/ExchangeRateTest.java
|
McLeodMoores/starling
|
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
|
[
"Apache-2.0"
] | 10 |
2017-01-19T13:32:36.000Z
|
2021-09-20T20:41:48.000Z
|
projects/starling-client/src/test/java/com/mcleodmoores/starling/client/fpml5_8/ExchangeRateTest.java
|
McLeodMoores/starling
|
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
|
[
"Apache-2.0"
] | 3 |
2017-12-14T12:46:18.000Z
|
2020-12-11T19:52:37.000Z
| 41.235294 | 110 | 0.720201 | 1,002,587 |
/**
* Copyright (C) 2016 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.mcleodmoores.starling.client.fpml5_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import java.math.BigDecimal;
import org.testng.annotations.Test;
import com.mcleodmoores.starling.client.portfolio.fpml5_8.CrossRate;
import com.mcleodmoores.starling.client.portfolio.fpml5_8.ExchangeRate;
import com.mcleodmoores.starling.client.portfolio.fpml5_8.QuoteBasis;
import com.mcleodmoores.starling.client.portfolio.fpml5_8.QuotedCurrencyPair;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.TestGroup;
/**
* Unit tests for {@link ExchangeRate}.
*/
@Test(groups = TestGroup.UNIT)
public class ExchangeRateTest {
/** GBP/USD rate */
private static final BigDecimal GBPUSD = BigDecimal.valueOf(1.25);
/** USD/JPY rate */
private static final BigDecimal USDJPY = BigDecimal.valueOf(100.);
/** JPY/USD rate */
private static final BigDecimal JPYUSD = BigDecimal.valueOf(0.01);
/** GBP/JPY rate */
private static final BigDecimal GBPJPY = BigDecimal.valueOf(125.);
/** JPY/GBP rate */
private static final BigDecimal JPYGBP = BigDecimal.valueOf(0.008);
/** USD/JPY cross rate */
private static final CrossRate USDJPY_CROSS = CrossRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.rate(USDJPY)
.build();
/** GBP/USD cross rate */
private static final CrossRate GBPUSD_CROSS = CrossRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.USD)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.rate(GBPUSD)
.build();
/**
* Tests that the rate can either be constructed from spot + forward or cross rates, not both.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfSpotAndFirstCrossRateSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.spotRate(USDJPY)
.forwardPoints(BigDecimal.ZERO)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.crossRate1(USDJPY_CROSS) // this should not be set
.build();
}
/**
* Tests that the rate can either be constructed from spot + forward or cross rates, not both.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfSpotAndSecondCrossRateSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.spotRate(USDJPY)
.forwardPoints(BigDecimal.ZERO)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.crossRate2(USDJPY_CROSS) // this should not be set
.build();
}
/**
* Tests that the forward and forward quote basis must be set if the spot is.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfForwardPointsAndQuoteBasisNotSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.spotRate(USDJPY)
.build();
}
/**
* Tests that the forward quote basis must be set if the spot and forward points are.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfFxForwardQuoteBasisNotSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.spotRate(USDJPY)
.forwardPoints(BigDecimal.ZERO)
.build();
}
/**
* Tests that the forward points must be set if the spot and forward quote basis are.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfFxForwardNotSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.spotRate(USDJPY)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build();
}
/**
* Tests that the spot must be set if the forward points and quote basis are.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfSpotNotSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.forwardPoints(BigDecimal.ZERO)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build();
}
/**
* Tests that both cross rates must be set.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfSecondCrossNotSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(USDJPY_CROSS)
.build();
}
/**
* Tests that the spot cannot be set if the cross rates are.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfCrossAndSpotSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(USDJPY_CROSS)
.crossRate2(GBPUSD_CROSS)
.spotRate(GBPJPY) // this should not be set
.build();
}
/**
* Tests that the forward points cannot be set if the cross rates are.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfCrossAndForwardSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(USDJPY_CROSS)
.crossRate2(GBPUSD_CROSS)
.forwardPoints(BigDecimal.ZERO) // this should not be set
.build();
}
/**
* Tests that the forward quote basis cannot be set if the cross rates are.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfCrossAndForwardQuoteBasisSet() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(USDJPY_CROSS)
.crossRate2(GBPUSD_CROSS)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2) // this should not be set
.build();
}
/**
* Tests that the currency pair must match those in the cross rates.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testErrorIfCrossRateCurrenciesDontMatch() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.EUR)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(USDJPY_CROSS)
.crossRate2(GBPUSD_CROSS)
.build();
}
/**
* Tests the exchange rate object that is constructed from a rate and quoted currency pair.
*/
@Test
public void testBuildDirect() {
final ExchangeRate exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.rate(USDJPY)
.build();
// all the fields that should not be set
assertNull(exchangeRate.getCrossRate1());
assertNull(exchangeRate.getCrossRate2());
assertNull(exchangeRate.getForwardPoints());
assertNull(exchangeRate.getFxForwardQuoteBasis());
assertNull(exchangeRate.getSpotRate());
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.USD);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY1_PER_CURRENCY2);
assertEquals(exchangeRate.getRate(), USDJPY);
}
/**
* Tests the exchange rate object that is constructed from cross rates, including the case where
* the order of the currencies in the quoted currency pair is the reverse of that in calculated
* from the cross rates.
*/
@Test
public void testBuildFromCrossRatesNoRateSet() {
// currency1 and currency2 are in the same order as the exchange rate calculated from the cross rates
ExchangeRate exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.build();
assertNull(exchangeRate.getForwardPoints());
assertNull(exchangeRate.getFxForwardQuoteBasis());
assertNull(exchangeRate.getSpotRate());
assertEquals(exchangeRate.getCrossRate1(), GBPUSD_CROSS);
assertEquals(exchangeRate.getCrossRate2(), USDJPY_CROSS);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.GBP);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY2_PER_CURRENCY1);
assertEquals(exchangeRate.getRate(), GBPJPY);
// currency1 and currency2 are in inverse order as the exchange rate calculated from the cross rates
exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.JPY)
.currency2(Currency.GBP)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.build();
assertNull(exchangeRate.getForwardPoints());
assertNull(exchangeRate.getFxForwardQuoteBasis());
assertNull(exchangeRate.getSpotRate());
assertEquals(exchangeRate.getCrossRate1(), GBPUSD_CROSS);
assertEquals(exchangeRate.getCrossRate2(), USDJPY_CROSS);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.GBP);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY2_PER_CURRENCY1);
assertEquals(exchangeRate.getRate().doubleValue(), 1 / GBPJPY.doubleValue());
}
/**
* Tests the exchange rate object that is constructed from cross rates, including the case where
* the order of the currencies in the quoted currency pair is the reverse of that in calculated
* from the cross rates. In this case, the rate is also set, so the calculated rate is compared to
* this value.
*/
@Test
public void testBuildFromCrossRatesRateAndQuoteBasisSet() {
// currency1 and currency2 are in the same order as the exchange rate calculated from the cross rates
ExchangeRate exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.rate(GBPJPY)
.build();
assertNull(exchangeRate.getForwardPoints());
assertNull(exchangeRate.getFxForwardQuoteBasis());
assertNull(exchangeRate.getSpotRate());
assertEquals(exchangeRate.getCrossRate1(), GBPUSD_CROSS);
assertEquals(exchangeRate.getCrossRate2(), USDJPY_CROSS);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.GBP);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY2_PER_CURRENCY1);
assertEquals(exchangeRate.getRate(), GBPJPY);
// currency1 and currency2 are in the same order as the exchange rate calculated from the cross rates
// but the quote basis is different
exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.rate(JPYGBP)
.build();
assertNull(exchangeRate.getForwardPoints());
assertNull(exchangeRate.getFxForwardQuoteBasis());
assertNull(exchangeRate.getSpotRate());
assertEquals(exchangeRate.getCrossRate1(), GBPUSD_CROSS);
assertEquals(exchangeRate.getCrossRate2(), USDJPY_CROSS);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.GBP);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY1_PER_CURRENCY2);
assertEquals(exchangeRate.getRate(), JPYGBP);
// currency1 and currency2 are in inverse order as the exchange rate calculated from the cross rates
exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.JPY)
.currency2(Currency.GBP)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.rate(GBPJPY)
.build();
assertNull(exchangeRate.getForwardPoints());
assertNull(exchangeRate.getFxForwardQuoteBasis());
assertNull(exchangeRate.getSpotRate());
assertEquals(exchangeRate.getCrossRate1(), GBPUSD_CROSS);
assertEquals(exchangeRate.getCrossRate2(), USDJPY_CROSS);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.GBP);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY1_PER_CURRENCY2);
assertEquals(exchangeRate.getRate(), GBPJPY);
// currency1 and currency2 are in inverse order as the exchange rate calculated from the cross rates
// but the quote basis is different
exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.JPY)
.currency2(Currency.GBP)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.rate(JPYGBP)
.build();
assertNull(exchangeRate.getForwardPoints());
assertNull(exchangeRate.getFxForwardQuoteBasis());
assertNull(exchangeRate.getSpotRate());
assertEquals(exchangeRate.getCrossRate1(), GBPUSD_CROSS);
assertEquals(exchangeRate.getCrossRate2(), USDJPY_CROSS);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.GBP);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY2_PER_CURRENCY1);
assertEquals(exchangeRate.getRate(), JPYGBP);
}
/**
* Tests that the rate and the calculated rate must match.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testBuildFromCrossRatesRateMismatch1() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.rate(GBPJPY.add(BigDecimal.ONE))
.build();
}
/**
* Tests that the rate and the calculated rate must match.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testBuildFromCrossRatesRateMismatch2() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.GBP)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.rate(JPYGBP.add(BigDecimal.ONE))
.build();
}
/**
* Tests that the rate and the calculated rate must match.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testBuildFromCrossRatesRateMismatch3() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.JPY)
.currency2(Currency.GBP)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.rate(JPYGBP.add(BigDecimal.ONE))
.build();
}
/**
* Tests that the rate and the calculated rate must match.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testBuildFromCrossRatesRateMismatch4() {
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.JPY)
.currency2(Currency.GBP)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.crossRate1(GBPUSD_CROSS)
.crossRate2(USDJPY_CROSS)
.rate(GBPJPY.add(BigDecimal.ONE))
.build();
}
/**
* Tests the exchange rate object that is constructed from spot and forward points, including the case where
* the order of the currencies in the quoted currency pair is the reverse of that the forward quote basis.
*/
@Test
public void testBuildFromSpotAndForwardNoRateSet() {
final BigDecimal forwardPoints = BigDecimal.valueOf(10);
final BigDecimal spot = USDJPY.subtract(forwardPoints);
// forward quote basis is the same as the rate quote basis
ExchangeRate exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.spotRate(spot)
.forwardPoints(forwardPoints)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build();
assertNull(exchangeRate.getCrossRate1());
assertNull(exchangeRate.getCrossRate2());
assertEquals(exchangeRate.getSpotRate(), spot);
assertEquals(exchangeRate.getForwardPoints(), forwardPoints);
assertEquals(exchangeRate.getFxForwardQuoteBasis(), QuoteBasis.CURRENCY1_PER_CURRENCY2);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.USD);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY1_PER_CURRENCY2);
assertEquals(exchangeRate.getRate(), USDJPY);
// forward quote basis is the inverse of the rate quote basis
exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.spotRate(spot)
.forwardPoints(forwardPoints)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build();
assertNull(exchangeRate.getCrossRate1());
assertNull(exchangeRate.getCrossRate2());
assertEquals(exchangeRate.getSpotRate(), spot);
assertEquals(exchangeRate.getForwardPoints(), forwardPoints);
assertEquals(exchangeRate.getFxForwardQuoteBasis(), QuoteBasis.CURRENCY1_PER_CURRENCY2);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.USD);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY2_PER_CURRENCY1);
assertEquals(exchangeRate.getRate().doubleValue(), 1 / USDJPY.doubleValue());
}
/**
* Tests the exchange rate object that is constructed from spot and forward points, including the case where
* the order of the currencies in the quoted currency pair is the reverse of that the forward quote basis.
* In this case, the rate is also set, so the calculated rate is compared to this value.
*/
@Test
public void testBuildFromSpotAndForwardRateAndQuoteBasisSet() {
final BigDecimal forwardPoints = BigDecimal.valueOf(10);
final BigDecimal spot = USDJPY.subtract(forwardPoints);
// forward quote basis is the same as the rate quote basis
ExchangeRate exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.rate(USDJPY)
.spotRate(spot)
.forwardPoints(forwardPoints)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build();
assertNull(exchangeRate.getCrossRate1());
assertNull(exchangeRate.getCrossRate2());
assertEquals(exchangeRate.getSpotRate(), spot);
assertEquals(exchangeRate.getForwardPoints(), forwardPoints);
assertEquals(exchangeRate.getFxForwardQuoteBasis(), QuoteBasis.CURRENCY1_PER_CURRENCY2);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.USD);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY1_PER_CURRENCY2);
assertEquals(exchangeRate.getRate(), USDJPY);
// forward quote basis is the inverse of the rate quote basis
exchangeRate = ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.rate(JPYUSD)
.spotRate(spot)
.forwardPoints(forwardPoints)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build();
assertNull(exchangeRate.getCrossRate1());
assertNull(exchangeRate.getCrossRate2());
assertEquals(exchangeRate.getSpotRate(), spot);
assertEquals(exchangeRate.getForwardPoints(), forwardPoints);
assertEquals(exchangeRate.getFxForwardQuoteBasis(), QuoteBasis.CURRENCY1_PER_CURRENCY2);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency1(), Currency.USD);
assertEquals(exchangeRate.getQuotedCurrencyPair().getCurrency2(), Currency.JPY);
assertEquals(exchangeRate.getQuotedCurrencyPair().getQuoteBasis(), QuoteBasis.CURRENCY2_PER_CURRENCY1);
assertEquals(exchangeRate.getRate().doubleValue(), 1 / USDJPY.doubleValue());
}
/**
* Tests that the rate and calculated rate must match.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testBuildFromSpotAndForwardRateMismatch1() {
final BigDecimal forwardPoints = BigDecimal.valueOf(10);
final BigDecimal spot = USDJPY.subtract(forwardPoints).add(BigDecimal.ONE);
// forward quote basis is the same as the rate quote basis
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build())
.rate(USDJPY)
.spotRate(spot)
.forwardPoints(forwardPoints)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build();
}
/**
* Tests that the rate and calculated rate must match.
*/
@Test(expectedExceptions = IllegalStateException.class)
public void testBuildFromSpotAndForwardRateMismatch2() {
final BigDecimal forwardPoints = BigDecimal.valueOf(10);
final BigDecimal spot = USDJPY.subtract(forwardPoints).add(BigDecimal.ONE);
// forward quote basis is the inverse of the rate quote basis
ExchangeRate.builder()
.quotedCurrencyPair(QuotedCurrencyPair.builder()
.currency1(Currency.USD)
.currency2(Currency.JPY)
.quoteBasis(QuoteBasis.CURRENCY2_PER_CURRENCY1)
.build())
.rate(JPYUSD)
.spotRate(spot)
.forwardPoints(forwardPoints)
.fxForwardQuoteBasis(QuoteBasis.CURRENCY1_PER_CURRENCY2)
.build();
}
}
|
92433dc300a521b998f319b4fc627e571ca908aa
| 2,324 |
java
|
Java
|
java/leetcode/IntegerToRoman.java
|
danyfang/SourceCode
|
8168f6058648f2a330a7354daf3a73a4d8a4e730
|
[
"MIT"
] | null | null | null |
java/leetcode/IntegerToRoman.java
|
danyfang/SourceCode
|
8168f6058648f2a330a7354daf3a73a4d8a4e730
|
[
"MIT"
] | null | null | null |
java/leetcode/IntegerToRoman.java
|
danyfang/SourceCode
|
8168f6058648f2a330a7354daf3a73a4d8a4e730
|
[
"MIT"
] | null | null | null | 24.463158 | 67 | 0.314114 | 1,002,588 |
//Leetcode problem 12 Integer To Roman
//Solution written by Xuqiang Fang on 11 April, 2018
/*
Input guranteed to be 1 ~ 3999
*/
/*
Symbol I V X L C D M
Value 1 5 10 50 100 500 1,000
*/
class Solution{
public String intToRoman(int num){
String s = "";
int thousand = num / 1000;
int hundred = (num - 1000 * thousand) / 100;
int ten = (num - 1000 * thousand - 100 * hundred) / 10;
int digit = num % 10;
boolean flag = true;
for(int i = thousand; i > 0; --i){
s += "M";
}
for(int i = hundred; i > 0; --i){
if(hundred == 9){
s += "CM";
break;
}
else if(hundred == 4){
s += "CD";
break;
}
else if(hundred >= 5){
if(flag){
s += "D";
flag = false;
i = i - 5;
if(i == 0)
break;
}
}
s += "C";
}
flag = true;
for(int i = ten; i > 0; --i){
if(ten == 9){
s += "XC";
break;
}
else if(ten == 4){
s += "XL";
break;
}
else if(ten >= 5){
if(flag){
s += "L";
flag = false;
i = i - 5;
if(i == 0)
break;
}
}
s += "X";
}
flag = true;
for(int i = digit; i > 0; --i){
if(digit == 9){
s += "IX";
break;
}
else if(digit == 4){
s += "IV";
break;
}
else if(digit >= 5){
if(flag){
s += "V";
flag = false;
i = i - 5;
if(i == 0)
break;
}
}
s += "I";
}
return s;
}
}
public class IntegerToRoman{
public static void main(String[] args){
Solution s = new Solution();
System.out.println(s.intToRoman(Integer.valueOf(args[0])));
}
}
|
92433e048a3680999bc5079c7362b1dd5c08a34f
| 897 |
java
|
Java
|
src/main/java/de/fload/Main.java
|
Fload2000/DiscordBot
|
7860142f6e31a0d454db4b11ad9fb34b6850326e
|
[
"MIT"
] | 1 |
2020-08-25T19:09:08.000Z
|
2020-08-25T19:09:08.000Z
|
src/main/java/de/fload/Main.java
|
Fload2000/DiscordBot
|
7860142f6e31a0d454db4b11ad9fb34b6850326e
|
[
"MIT"
] | null | null | null |
src/main/java/de/fload/Main.java
|
Fload2000/DiscordBot
|
7860142f6e31a0d454db4b11ad9fb34b6850326e
|
[
"MIT"
] | null | null | null | 24.243243 | 77 | 0.64437 | 1,002,589 |
package de.fload;
import de.fload.core.DiscordBot;
import de.fload.core.Settings;
import de.fload.database.DatabaseCreator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main class
*/
public class Main {
private final static Logger logger = LoggerFactory.getLogger(Main.class);
/**
* Main method.
*
* @param args execution flags
*/
public static void main(String[] args) {
// load settings from config file.
logger.info("Load settings.");
Settings.getInstance().load();
logger.info("Settings successfully loaded.");
// initialize the database
logger.info("Init database.");
DatabaseCreator.initDatabase();
logger.info("Database successfully initialized.");
// init and start the Discord-Bot
logger.info("Init Discord-Bot.");
DiscordBot.init();
}
}
|
92433f5500d361489ffc9934b17290ed2df612b6
| 4,904 |
java
|
Java
|
src/test/java/com/webank/webase/front/keystore/KeyStoreFileTest.java
|
hailong99/WeBASE-Front
|
56f7d1ac80e3d57b3ae8504964b7eeaa283eb444
|
[
"Apache-2.0"
] | 1 |
2020-09-25T08:33:14.000Z
|
2020-09-25T08:33:14.000Z
|
src/test/java/com/webank/webase/front/keystore/KeyStoreFileTest.java
|
hailong99/WeBASE-Front
|
56f7d1ac80e3d57b3ae8504964b7eeaa283eb444
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/webank/webase/front/keystore/KeyStoreFileTest.java
|
hailong99/WeBASE-Front
|
56f7d1ac80e3d57b3ae8504964b7eeaa283eb444
|
[
"Apache-2.0"
] | null | null | null | 46.754717 | 194 | 0.75222 | 1,002,590 |
/**
* Copyright 2014-2020 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.webank.webase.front.keystore;
import com.webank.webase.front.util.CommonUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.spec.InvalidKeySpecException;
import org.fisco.bcos.channel.client.P12Manager;
import org.fisco.bcos.channel.client.PEMManager;
import org.fisco.bcos.web3j.crypto.Credentials;
import org.fisco.bcos.web3j.crypto.gm.GenCredential;
import org.fisco.bcos.web3j.utils.Numeric;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
public class KeyStoreFileTest {
private static final String pemContent = "-----BEGIN PRIVATE KEY-----\n" +
"MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgC8TbvFSMA9y3CghFt51/" +
"caf86f4uutaoxfysmf7anj01xl6sv3ps" +
"ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7" +
"\n-----END PRIVATE KEY-----\n";
@Test
public void testLoadPem() throws CertificateException, InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException, UnrecoverableKeyException {
System.out.println(Numeric.toHexString(pemContent.getBytes()));
PEMManager pemManager0 = new PEMManager();
pemManager0.load(new ByteArrayInputStream(pemContent.getBytes()));
System.out.println(Numeric.toHexStringNoPrefix(pemManager0.getECKeyPair().getPrivateKey()));
// System.out.println(Numeric.toHexStringNoPrefix(pemManager0.getPrivateKey().getEncoded()));
}
@Test
public void testLoadPemFile() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, CertificateException, KeyStoreException {
PEMManager pemManager = new PEMManager();
// need pem
InputStream nodeCrtInput = new ClassPathResource("test.pem").getInputStream();
pemManager.load(nodeCrtInput);
System.out.println(pemManager.getPrivateKey());
System.out.println(Numeric.toHexString(pemManager.getPrivateKey().getEncoded()));
}
@Test
public void loadPrivateKeyTest() throws Exception {
String privateKey = "71f1479d9051e8d6b141a3b3ef9c01a7756da823a0af280c6bf62d18ee0cc978";
Credentials credentials = GenCredential.create(privateKey);
// private key 实例
BigInteger privateKeyInstance = credentials.getEcKeyPair().getPrivateKey();
System.out.println(Numeric.toHexStringNoPrefix(privateKeyInstance));
// public key 实例
BigInteger publicKeyInstance = credentials.getEcKeyPair().getPublicKey();
System.out.println(Numeric.toHexString(publicKeyInstance.toByteArray()));
String address = credentials.getAddress();
System.out.println(address);
}
@Test
public void testNotContainsChinese() {
String notContains = "test";
String contain = "test中文";
boolean flagTrue = CommonUtils.notContainsChinese(notContains);
boolean flagFalse = CommonUtils.notContainsChinese(contain);
Assert.assertTrue("contains chinese error", !flagFalse);
Assert.assertTrue("not contains normal", flagTrue);
}
@Test
public void testLoadP12() throws UnrecoverableKeyException, InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, CertificateException, IOException {
P12Manager p12Manager = new P12Manager();
p12Manager.setP12File("0x6399bda67f0ae8d1fdd997a885b8aee32a0c9696.p12");
p12Manager.setPassword("123");
p12Manager.load();
// c5658bbb9b905345e7c057690ec6f50c06dada711d1086820980496b4954fbc7
String privateKey = Numeric.toHexStringNoPrefix(p12Manager.getECKeyPair().getPrivateKey());
System.out.println("load private key: " + privateKey);
String address = GenCredential.create(privateKey).getAddress();
System.out.println("address: " + address);
Assert.assertTrue("pri error", address.equals("0x6399bda67f0ae8d1fdd997a885b8aee32a0c9696"));
}
}
|
92433f63f6f5b548f305da3b8c34d174cac70759
| 2,986 |
java
|
Java
|
src/main/java/dev/vality/scheduledpayoutworker/service/impl/PayoutManagerServiceImpl.java
|
valitydev/scheduled-payout-worker
|
bf7f8304b91ee38f343e4bc7b87e4c96e8f98042
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/dev/vality/scheduledpayoutworker/service/impl/PayoutManagerServiceImpl.java
|
valitydev/scheduled-payout-worker
|
bf7f8304b91ee38f343e4bc7b87e4c96e8f98042
|
[
"Apache-2.0"
] | 8 |
2022-02-09T15:20:30.000Z
|
2022-03-30T01:52:51.000Z
|
src/main/java/dev/vality/scheduledpayoutworker/service/impl/PayoutManagerServiceImpl.java
|
valitydev/scheduled-payout-worker
|
bf7f8304b91ee38f343e4bc7b87e4c96e8f98042
|
[
"Apache-2.0"
] | null | null | null | 39.813333 | 116 | 0.746484 | 1,002,591 |
package dev.vality.scheduledpayoutworker.service.impl;
import dev.vality.damsel.domain.Cash;
import dev.vality.damsel.domain.CurrencyRef;
import dev.vality.damsel.domain.Shop;
import dev.vality.geck.common.util.TypeUtil;
import dev.vality.payout.manager.PayoutManagementSrv;
import dev.vality.payout.manager.PayoutParams;
import dev.vality.payout.manager.ShopParams;
import dev.vality.scheduledpayoutworker.dao.*;
import dev.vality.scheduledpayoutworker.exception.InvalidStateException;
import dev.vality.scheduledpayoutworker.exception.NotFoundException;
import dev.vality.scheduledpayoutworker.service.PartyManagementService;
import dev.vality.scheduledpayoutworker.service.PayoutManagerService;
import dev.vality.scheduledpayoutworker.service.ShumwayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
@Service
@RequiredArgsConstructor
@Slf4j
public class PayoutManagerServiceImpl implements PayoutManagerService {
private final PayoutManagementSrv.Iface payoutManagerClient;
private final PartyManagementService partyManagementService;
private final ShumwayService shumwayService;
private final ShopMetaDao shopMetaDao;
/**
* Create payout by partyId, shopId and toTime. fromTime = toTime - MAX_DAYS
*
* @return payoutId if payout successfully created, null if payout amount = 0
*/
@Override
@Transactional
public String createPayoutByRange(String partyId, String shopId, LocalDateTime toTime)
throws NotFoundException, TException {
Shop shop = partyManagementService.getShop(partyId, shopId);
if (shop.getBlocking().isSetBlocked()) {
throw new InvalidStateException(
String.format("Party or shop blocked for payouts, partyId='%s', shopId='%s'", partyId, shopId));
}
var fromTime = shopMetaDao.get(partyId, shopId).getLastPayoutCreatedAt();
long amount;
if (fromTime == null) {
amount = shumwayService.getAccountBalance(Long.parseLong(shopId), toTime);
} else {
amount = shumwayService.getAccountBalanceDiff(Long.parseLong(shopId), fromTime, toTime);
}
if (amount == 0) {
return null;
}
String symbolicCode = shop.getAccount().getCurrency().getSymbolicCode();
CurrencyRef currency = new CurrencyRef().setSymbolicCode(symbolicCode);
Cash cash = new Cash().setAmount(amount).setCurrency(currency);
ShopParams shopParams = new ShopParams().setPartyId(partyId).setShopId(shopId);
PayoutParams payoutParams = new PayoutParams(shopParams, cash);
var payout = payoutManagerClient.createPayout(payoutParams);
shopMetaDao.update(partyId, shopId, toTime);
return payout.getPayoutId();
}
}
|
924341848a2b0288c9ebc4d8d6a0b908c44ed3db
| 1,262 |
java
|
Java
|
src/main/java/com/github/damianwajser/model/PathVariable.java
|
damianwajser/spring-rest-commons-options
|
524c5c74799b0b3e42eda3455b4db5ba28748f10
|
[
"Apache-2.0"
] | 4 |
2017-11-17T02:03:39.000Z
|
2018-06-12T18:59:12.000Z
|
src/main/java/com/github/damianwajser/model/PathVariable.java
|
damianwajser/spring-rest-commons-options
|
524c5c74799b0b3e42eda3455b4db5ba28748f10
|
[
"Apache-2.0"
] | 6 |
2017-11-16T17:30:15.000Z
|
2018-01-16T14:39:13.000Z
|
src/main/java/com/github/damianwajser/model/PathVariable.java
|
damianwajser/spring-rest-commons-options
|
524c5c74799b0b3e42eda3455b4db5ba28748f10
|
[
"Apache-2.0"
] | null | null | null | 26.851064 | 82 | 0.709192 | 1,002,592 |
package com.github.damianwajser.model;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.damianwajser.utils.ReflectionUtils;
public class PathVariable {
private static final Logger LOGGER = LoggerFactory.getLogger(PathVariable.class);
private List<Parameters> params = new ArrayList<>();
private static Pattern pattern = Pattern.compile("\\{[a-zA-Z0-9]*\\}");
public PathVariable() {
}
public PathVariable(Method m, String relativePath) {
params = ReflectionUtils.getPathVariable(m);
if (!params.isEmpty()) {
Matcher matcher = pattern.matcher(relativePath);
LOGGER.info("fix path variable: {}", relativePath);
for (int i = 0; i < params.size(); i++) {
if (matcher.find()) {
String param = matcher.group(0);
LOGGER.info("param: {}", param);
params.get(i).setName(param.replaceAll("\\{", "").replaceAll("\\}", ""));
}
}
}
}
public List<Parameters> getParams() {
return params;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
924341df44cf731e691c1f81c0440bf2f95f2e93
| 5,274 |
java
|
Java
|
src/rapaio/data/filter/VToInt.java
|
rapaio/rapaio
|
9d226ad07eb50f0d77409ba6d1d5e971134ae215
|
[
"Apache-2.0"
] | 82 |
2015-01-07T15:01:27.000Z
|
2022-03-22T16:40:22.000Z
|
src/rapaio/data/filter/VToInt.java
|
subashncrypt/rapaio
|
db7fb31bdb38e0ef9d738ea061de7eef5ecae91f
|
[
"Apache-2.0"
] | 198 |
2015-02-13T08:05:55.000Z
|
2022-03-24T04:57:19.000Z
|
src/rapaio/data/filter/VToInt.java
|
subashncrypt/rapaio
|
db7fb31bdb38e0ef9d738ea061de7eef5ecae91f
|
[
"Apache-2.0"
] | 26 |
2015-01-20T14:31:01.000Z
|
2022-03-21T23:40:32.000Z
| 30.668605 | 124 | 0.600569 | 1,002,593 |
/*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* Copyright 2013 - 2021 Aurelian Tutuianu
*
* 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 rapaio.data.filter;
import java.io.Serial;
import java.util.function.Function;
import rapaio.data.Var;
import rapaio.data.VarInt;
import rapaio.data.stream.VSpot;
import rapaio.printer.Printer;
import rapaio.printer.opt.POption;
import rapaio.util.function.Double2IntFunction;
import rapaio.util.function.Int2IntFunction;
/**
* Created by <a href="mailto:[email protected]">Aurelian Tutuianu</a> at 12/4/14.
*/
public class VToInt implements VFilter {
public static VToInt byDefault() {
return new VToInt(new DefaultByType());
}
public static VToInt bySpot(Function<VSpot, Integer> fun) {
return new VToInt(new TransformSpot(fun));
}
public static VToInt fromDouble(Double2IntFunction fun) {
return new VToInt(new TransformDouble(fun));
}
public static VToInt fromInt(Int2IntFunction fun) {
return new VToInt(new TransformInt(fun));
}
public static VToInt byLabel(Function<String, Integer> fun) {
return new VToInt(new TransformLabel(fun));
}
@Serial
private static final long serialVersionUID = -699221182441440988L;
private final Function<Var, Var> fun;
private VToInt(Function<Var, Var> fun) {
this.fun = fun;
}
@Override
public Var apply(Var var) {
return fun.apply(var);
}
/* Implements default transformations */
static class DefaultByType implements Function<Var, Var> {
@Override
public Var apply(Var var) {
return switch (var.type()) {
case DOUBLE -> new TransformDouble(x -> (int) Math.rint(x)).apply(var);
case INT, BINARY -> new TransformInt(x -> x).apply(var);
case NOMINAL, STRING -> new TransformLabel(x -> {
try {
return Integer.parseInt(x);
} catch (NumberFormatException ex) {
return VarInt.MISSING_VALUE;
}
}).apply(var);
default -> throw new IllegalArgumentException("Variable type: " + var.type().code() + " is not supported.");
};
}
}
static class TransformSpot implements Function<Var, Var> {
private final Function<VSpot, Integer> function;
TransformSpot(Function<VSpot, Integer> function) {
this.function = function;
}
@Override
public Var apply(Var var) {
int[] value = new int[var.size()];
for (int i = 0; i < var.size(); i++) {
value[i] = var.isMissing(i) ? VarInt.MISSING_VALUE : function.apply(new VSpot(i, var));
}
return VarInt.wrap(value).name(var.name());
}
}
static class TransformDouble implements Function<Var, Var> {
private final Double2IntFunction function;
TransformDouble(Double2IntFunction function) {
this.function = function;
}
@Override
public Var apply(Var var) {
int[] value = new int[var.size()];
for (int i = 0; i < var.size(); i++) {
value[i] = var.isMissing(i) ? VarInt.MISSING_VALUE : function.applyAsInt(var.getDouble(i));
}
return VarInt.wrap(value).name(var.name());
}
}
static class TransformInt implements Function<Var, Var> {
private final Int2IntFunction function;
TransformInt(Int2IntFunction function) {
this.function = function;
}
@Override
public Var apply(Var var) {
int[] value = new int[var.size()];
for (int i = 0; i < var.size(); i++) {
value[i] = var.isMissing(i) ? VarInt.MISSING_VALUE : function.applyAsInt(var.getInt(i));
}
return VarInt.wrap(value).name(var.name());
}
}
static class TransformLabel implements Function<Var, Var> {
private final Function<String, Integer> function;
TransformLabel(Function<String, Integer> function) {
this.function = function;
}
@Override
public Var apply(Var var) {
int[] values = new int[var.size()];
for (int i = 0; i < var.size(); i++) {
values[i] = function.apply(var.getLabel(i));
}
return VarInt.wrap(values).name(var.name());
}
}
@Override
public String toContent(Printer printer, POption<?>... options) {
return "VToInt";
}
@Override
public String toString() {
return "VToInt";
}
}
|
924342224df369bac4373ce320ffff8e5f0cca28
| 3,055 |
java
|
Java
|
src/main/java/com/lordjoe/ui/general/OKCancelDialog.java
|
lordjoe/VoterGuide
|
7a142649f69cb0ed82660cd2e88beebbbeb70a01
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/lordjoe/ui/general/OKCancelDialog.java
|
lordjoe/VoterGuide
|
7a142649f69cb0ed82660cd2e88beebbbeb70a01
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/lordjoe/ui/general/OKCancelDialog.java
|
lordjoe/VoterGuide
|
7a142649f69cb0ed82660cd2e88beebbbeb70a01
|
[
"Apache-2.0"
] | null | null | null | 25.040984 | 125 | 0.621604 | 1,002,594 |
package com.lordjoe.ui.general;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
/**
* com.lordjoe.ui.general.OKCancelDialog
*
* @author Steve Lewis
* @date Sep 2, 2005
*/
public abstract class OKCancelDialog extends JDialog
{
// My guess for room to allow for a title bar
public static final int WINDOW_TITLE_SIZE = 32;
public static final int WINDOW_BORDER_SIZE = 16;
// PRIVATE //
private final WrappedAction m_OKAction;
private final JPanel m_Commands;
private JComponent m_Component;
private JButton m_OKButton;
public OKCancelDialog(String aTitle, JFrame aParent)
{
super(aParent, aTitle);
setLayout(new BorderLayout());
m_Commands = new JPanel();
m_OKAction = new OKAction();
m_OKButton = new JButton(m_OKAction);
m_Commands.add(m_OKButton);
m_Commands.add(new JButton(new CancelAction()));
add(m_Commands, BorderLayout.SOUTH);
}
public void setComponent(JComponent added)
{
m_Component = added;
add(added, BorderLayout.CENTER);
}
protected JPanel getCommands()
{
return m_Commands;
}
protected JComponent getComponent()
{
return m_Component;
}
protected JButton getOKButton()
{
return m_OKButton;
}
public void normalizesSize()
{
Dimension mySize = buildMySize();
setSize(mySize);
}
protected Dimension buildMySize()
{
Insets ins = this.getInsets();
JPanel commands = getCommands();
Point loc = commands.getLocation();
Dimension commandSize = commands.getPreferredSize();
JComponent component = getComponent();
Dimension componentSize = component.getPreferredSize();
JButton okButton = getOKButton();
Dimension buttonSize = okButton.getPreferredSize();
int cmdHeight = Math.max(commandSize.height,buttonSize.height + 10);
Dimension mySize = new Dimension(
WINDOW_BORDER_SIZE + (int)loc.getX() + ins.left + ins.right + Math.max(commandSize.width, componentSize.width),
WINDOW_TITLE_SIZE + (int)loc.getY() + ins.top + ins.bottom + cmdHeight + componentSize.height);
return mySize;
}
public void setRealAction(AbstractAction realAction)
{
getOKAction().setRealAction(realAction);
}
public WrappedAction getOKAction()
{
return m_OKAction;
}
private class OKAction extends WrappedAction
{
public OKAction()
{
putValue(Action.NAME, "OK");
}
public void actionPerformed(ActionEvent e)
{
setVisible(false);
super.actionPerformed(e);
}
}
private class CancelAction extends AbstractAction
{
public CancelAction()
{
putValue(Action.NAME, "Cancel");
}
public void actionPerformed(ActionEvent e)
{
setVisible(false);
dispose();
}
}
}
|
92434232b17da7d1f16ceb7b1be368033ff9d057
| 1,975 |
java
|
Java
|
app/src/main/java/com/veerasystem/crust/main/Presenter.java
|
VeeraSystem/android-crust
|
ab3872c51297919082f3d30a05c9d42d80ac8449
|
[
"Apache-2.0"
] | 3 |
2017-07-11T13:23:24.000Z
|
2018-01-06T13:19:24.000Z
|
app/src/main/java/com/veerasystem/crust/main/Presenter.java
|
VeeraSystem/android-crust
|
ab3872c51297919082f3d30a05c9d42d80ac8449
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/veerasystem/crust/main/Presenter.java
|
VeeraSystem/android-crust
|
ab3872c51297919082f3d30a05c9d42d80ac8449
|
[
"Apache-2.0"
] | null | null | null | 28.214286 | 81 | 0.627848 | 1,002,595 |
/*
* Copyright (c) 2017 VEERA SYSTEM
*
* 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.veerasystem.crust.main;
import com.veerasystem.crust.data.source.remote.Remote;
import javax.inject.Inject;
import okhttp3.ResponseBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class Presenter implements CrustContractor.Presenter {
private Remote remote;
private CrustContractor.View view;
@Inject
Presenter(Remote remote, CrustContractor.View view) {
this.remote = remote;
this.view = view;
view.setPresenter(this);
}
@Override
public void start() {
}
@Override
public void signOut() {
Observable<ResponseBody> logoutResponce = remote.logout(view.getToken());
logoutResponce.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(ResponseBody responseBody) {
view.showLoginPage();
}
});
}
}
|
924344bc7a78f3b94e7c0247655b315b3061dcfa
| 750 |
java
|
Java
|
src/main/java/pl/dpawlak/flocoge/log/ErrorLogger.java
|
domel8dp/flocoge
|
6be37ad788431817c9591ef622f4bd46d4088689
|
[
"MIT"
] | 1 |
2019-08-27T09:31:51.000Z
|
2019-08-27T09:31:51.000Z
|
src/main/java/pl/dpawlak/flocoge/log/ErrorLogger.java
|
domel8dp/flocoge
|
6be37ad788431817c9591ef622f4bd46d4088689
|
[
"MIT"
] | null | null | null |
src/main/java/pl/dpawlak/flocoge/log/ErrorLogger.java
|
domel8dp/flocoge
|
6be37ad788431817c9591ef622f4bd46d4088689
|
[
"MIT"
] | null | null | null | 26.785714 | 102 | 0.629333 | 1,002,596 |
package pl.dpawlak.flocoge.log;
public class ErrorLogger extends BaseLogger {
private final boolean printStack;
public ErrorLogger(boolean printStack, ModelPrinter bareModelPrinter, ModelPrinter modelPrinter) {
super(bareModelPrinter, modelPrinter);
this.printStack = printStack;
}
@Override
public void error(String msg) {
System.err.println(msg);
}
@Override
public void error(String msg, Object... objects) {
System.err.println(Formatter.buildMsg(msg, objects));
if (printStack) {
Object last = objects[objects.length - 1];
if (last instanceof Throwable) {
((Throwable)last).printStackTrace();
}
}
}
}
|
92434575c0832a47e1f91090749e010738eab823
| 3,074 |
java
|
Java
|
org/w3c/css/properties/css/CssBackgroundClip.java
|
BeckyDTP/css-validator
|
b86f61ae8c167cbaa174ec3adc7b2a266733a293
|
[
"W3C-19980720",
"W3C-20150513"
] | 194 |
2015-03-12T00:14:19.000Z
|
2022-03-29T20:09:37.000Z
|
org/w3c/css/properties/css/CssBackgroundClip.java
|
BeckyDTP/css-validator
|
b86f61ae8c167cbaa174ec3adc7b2a266733a293
|
[
"W3C-19980720",
"W3C-20150513"
] | 247 |
2015-01-05T14:14:32.000Z
|
2022-03-03T08:57:04.000Z
|
org/w3c/css/properties/css/CssBackgroundClip.java
|
BeckyDTP/css-validator
|
b86f61ae8c167cbaa174ec3adc7b2a266733a293
|
[
"W3C-19980720",
"W3C-20150513"
] | 106 |
2015-01-05T11:15:18.000Z
|
2022-03-22T15:14:21.000Z
| 25.798319 | 78 | 0.629316 | 1,002,597 |
// $Id$
// @author Yves Lafon <[email protected]>
//
// (c) COPYRIGHT 2010 World Wide Web Consortium (MIT, ERCIM, Keio University)
// Please first read the full copyright statement at
// http://www.w3.org/Consortium/Legal/copyright-software-19980720
package org.w3c.css.properties.css;
import org.w3c.css.parser.CssStyle;
import org.w3c.css.properties.css3.Css3Style;
import org.w3c.css.util.ApplContext;
import org.w3c.css.util.InvalidParamException;
import org.w3c.css.values.CssExpression;
/**
* @since CSS3
*/
public class CssBackgroundClip extends CssProperty {
/**
* Create a new CssBackgroundClip
*/
public CssBackgroundClip() {
}
/**
* Create a new CssBackgroundClip
*
* @param expression The expression for this property
* @throws InvalidParamException Incorrect value
*/
public CssBackgroundClip(ApplContext ac, CssExpression expression,
boolean check) throws InvalidParamException {
throw new InvalidParamException("unrecognized", ac);
}
public CssBackgroundClip(ApplContext ac, CssExpression expression)
throws InvalidParamException {
this(ac, expression, false);
}
/**
* Add this property to the CssStyle
*
* @param style The CssStyle
*/
public void addToStyle(ApplContext ac, CssStyle style) {
// TODO FIXME -> in CssStyle
if (((Css3Style) style).cssBackgroundClip != null)
style.addRedefinitionWarning(ac, this);
((Css3Style) style).cssBackgroundClip = this;
}
/**
* Get this property in the style.
*
* @param style The style where the property is
* @param resolve if true, resolve the style to find this property
*/
public CssProperty getPropertyInStyle(CssStyle style, boolean resolve) {
if (resolve) {
return ((Css3Style) style).getCssBackgroundClip();
} else {
return ((Css3Style) style).cssBackgroundClip;
}
}
/**
* Compares two properties for equality.
*
* @param property The other property.
*/
public boolean equals(CssProperty property) {
return (property instanceof CssBackgroundClip &&
value.equals(((CssBackgroundClip) property).value));
}
/**
* Returns the name of this property
*/
public final String getPropertyName() {
return "background-clip";
}
/**
* Returns the value of this property
*/
public Object get() {
return value;
}
/**
* Returns true if this property is "softly" inherited
*/
public boolean isSoftlyInherited() {
return inherit.equals(value);
}
/**
* Returns a string representation of the object
*/
public String toString() {
return value.toString();
}
/**
* Is the value of this property a default value
* It is used by all macro for the function <code>print</code>
*/
public boolean isDefault() {
return false;
}
}
|
924348def5791a806a950fc9118671f9d4fcc508
| 14,680 |
java
|
Java
|
engine/src/main/java/org/pentaho/di/trans/steps/mergerows/MergeRowsMeta.java
|
hzy1992/pentaho-kettle
|
5762bc329aea7d56c50fe797de2febdef9b6d7b2
|
[
"Apache-2.0"
] | 5,903 |
2015-01-07T01:32:02.000Z
|
2022-03-31T03:55:32.000Z
|
engine/src/main/java/org/pentaho/di/trans/steps/mergerows/MergeRowsMeta.java
|
hzy1992/pentaho-kettle
|
5762bc329aea7d56c50fe797de2febdef9b6d7b2
|
[
"Apache-2.0"
] | 5,944 |
2015-01-02T21:07:48.000Z
|
2022-03-28T14:53:13.000Z
|
engine/src/main/java/org/pentaho/di/trans/steps/mergerows/MergeRowsMeta.java
|
hzy1992/pentaho-kettle
|
5762bc329aea7d56c50fe797de2febdef9b6d7b2
|
[
"Apache-2.0"
] | 3,097 |
2015-01-01T19:57:19.000Z
|
2022-03-31T09:08:57.000Z
| 35.631068 | 134 | 0.67936 | 1,002,598 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.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.pentaho.di.trans.steps.mergerows;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleRowException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.injection.Injection;
import org.pentaho.di.core.injection.InjectionSupported;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaString;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransMeta.TransformationType;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepIOMeta;
import org.pentaho.di.trans.step.StepIOMetaInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.step.errorhandling.Stream;
import org.pentaho.di.trans.step.errorhandling.StreamIcon;
import org.pentaho.di.trans.step.errorhandling.StreamInterface;
import org.pentaho.di.trans.step.errorhandling.StreamInterface.StreamType;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
import java.util.List;
/*
* Created on 02-jun-2003
*
*/
@InjectionSupported( localizationPrefix = "MergeRows.Injection." )
public class MergeRowsMeta extends BaseStepMeta implements StepMetaInterface {
private static Class<?> PKG = MergeRowsMeta.class; // for i18n purposes, needed by Translator2!!
@Injection( name = "FLAG_FIELD" )
private String flagField;
@Injection( name = "KEY_FIELDS" )
private String[] keyFields;
@Injection( name = "VALUE_FIELDS" )
private String[] valueFields;
/**
* @return Returns the keyFields.
*/
public String[] getKeyFields() {
return keyFields;
}
/**
* @param keyFields
* The keyFields to set.
*/
public void setKeyFields( String[] keyFields ) {
this.keyFields = keyFields;
}
/**
* @return Returns the valueFields.
*/
public String[] getValueFields() {
return valueFields;
}
/**
* @param valueFields
* The valueFields to set.
*/
public void setValueFields( String[] valueFields ) {
this.valueFields = valueFields;
}
public MergeRowsMeta() {
super(); // allocate BaseStepMeta
}
@Override
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
readData( stepnode );
}
/**
* @return Returns the flagField.
*/
public String getFlagField() {
return flagField;
}
/**
* @param flagField
* The flagField to set.
*/
public void setFlagField( String flagField ) {
this.flagField = flagField;
}
public void allocate( int nrKeys, int nrValues ) {
keyFields = new String[nrKeys];
valueFields = new String[nrValues];
}
@Override
public Object clone() {
MergeRowsMeta retval = (MergeRowsMeta) super.clone();
int nrKeys = keyFields.length;
int nrValues = valueFields.length;
retval.allocate( nrKeys, nrValues );
System.arraycopy( keyFields, 0, retval.keyFields, 0, nrKeys );
System.arraycopy( valueFields, 0, retval.valueFields, 0, nrValues );
return retval;
}
@Override
public String getXML() {
StringBuilder retval = new StringBuilder();
retval.append( " <keys>" + Const.CR );
for ( int i = 0; i < keyFields.length; i++ ) {
retval.append( " " + XMLHandler.addTagValue( "key", keyFields[i] ) );
}
retval.append( " </keys>" + Const.CR );
retval.append( " <values>" + Const.CR );
for ( int i = 0; i < valueFields.length; i++ ) {
retval.append( " " + XMLHandler.addTagValue( "value", valueFields[i] ) );
}
retval.append( " </values>" + Const.CR );
retval.append( XMLHandler.addTagValue( "flag_field", flagField ) );
List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams();
retval.append( XMLHandler.addTagValue( "reference", infoStreams.get( 0 ).getStepname() ) );
retval.append( XMLHandler.addTagValue( "compare", infoStreams.get( 1 ).getStepname() ) );
retval.append( " <compare>" + Const.CR );
retval.append( " </compare>" + Const.CR );
return retval.toString();
}
private void readData( Node stepnode ) throws KettleXMLException {
try {
Node keysnode = XMLHandler.getSubNode( stepnode, "keys" );
Node valuesnode = XMLHandler.getSubNode( stepnode, "values" );
int nrKeys = XMLHandler.countNodes( keysnode, "key" );
int nrValues = XMLHandler.countNodes( valuesnode, "value" );
allocate( nrKeys, nrValues );
for ( int i = 0; i < nrKeys; i++ ) {
Node keynode = XMLHandler.getSubNodeByNr( keysnode, "key", i );
keyFields[i] = XMLHandler.getNodeValue( keynode );
}
for ( int i = 0; i < nrValues; i++ ) {
Node valuenode = XMLHandler.getSubNodeByNr( valuesnode, "value", i );
valueFields[i] = XMLHandler.getNodeValue( valuenode );
}
flagField = XMLHandler.getTagValue( stepnode, "flag_field" );
List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams();
StreamInterface referenceStream = infoStreams.get( 0 );
StreamInterface compareStream = infoStreams.get( 1 );
compareStream.setSubject( XMLHandler.getTagValue( stepnode, "compare" ) );
referenceStream.setSubject( XMLHandler.getTagValue( stepnode, "reference" ) );
} catch ( Exception e ) {
throw new KettleXMLException(
BaseMessages.getString( PKG, "MergeRowsMeta.Exception.UnableToLoadStepInfo" ), e );
}
}
@Override
public void setDefault() {
flagField = "flagfield";
allocate( 0, 0 );
}
@Override
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException {
try {
int nrKeys = rep.countNrStepAttributes( id_step, "key_field" );
int nrValues = rep.countNrStepAttributes( id_step, "value_field" );
allocate( nrKeys, nrValues );
for ( int i = 0; i < nrKeys; i++ ) {
keyFields[i] = rep.getStepAttributeString( id_step, i, "key_field" );
}
for ( int i = 0; i < nrValues; i++ ) {
valueFields[i] = rep.getStepAttributeString( id_step, i, "value_field" );
}
flagField = rep.getStepAttributeString( id_step, "flag_field" );
List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams();
StreamInterface referenceStream = infoStreams.get( 0 );
StreamInterface compareStream = infoStreams.get( 1 );
referenceStream.setSubject( rep.getStepAttributeString( id_step, "reference" ) );
compareStream.setSubject( rep.getStepAttributeString( id_step, "compare" ) );
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString(
PKG, "MergeRowsMeta.Exception.UnexpectedErrorReadingStepInfo" ), e );
}
}
@Override
public void searchInfoAndTargetSteps( List<StepMeta> steps ) {
List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams();
for ( StreamInterface stream : infoStreams ) {
stream.setStepMeta( StepMeta.findStep( steps, (String) stream.getSubject() ) );
}
}
@Override
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step ) throws KettleException {
try {
for ( int i = 0; i < keyFields.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, "key_field", keyFields[i] );
}
for ( int i = 0; i < valueFields.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, "value_field", valueFields[i] );
}
rep.saveStepAttribute( id_transformation, id_step, "flag_field", flagField );
List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams();
StreamInterface referenceStream = infoStreams.get( 0 );
StreamInterface compareStream = infoStreams.get( 1 );
rep.saveStepAttribute( id_transformation, id_step, "reference", referenceStream.getStepname() );
rep.saveStepAttribute( id_transformation, id_step, "compare", compareStream.getStepname() );
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString( PKG, "MergeRowsMeta.Exception.UnableToSaveStepInfo" )
+ id_step, e );
}
}
public boolean chosesTargetSteps() {
return false;
}
public String[] getTargetSteps() {
return null;
}
@Override
public void getFields( RowMetaInterface r, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
// We don't have any input fields here in "r" as they are all info fields.
// So we just merge in the info fields.
//
if ( info != null ) {
boolean found = false;
for ( int i = 0; i < info.length && !found; i++ ) {
if ( info[i] != null ) {
r.mergeRowMeta( info[i], name );
found = true;
}
}
}
if ( Utils.isEmpty( flagField ) ) {
throw new KettleStepException( BaseMessages.getString( PKG, "MergeRowsMeta.Exception.FlagFieldNotSpecified" ) );
}
ValueMetaInterface flagFieldValue = new ValueMetaString( flagField );
flagFieldValue.setOrigin( name );
r.addValueMeta( flagFieldValue );
}
@Override
public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta,
RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space,
Repository repository, IMetaStore metaStore ) {
CheckResult cr;
List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams();
StreamInterface referenceStream = infoStreams.get( 0 );
StreamInterface compareStream = infoStreams.get( 1 );
if ( referenceStream.getStepname() != null && compareStream.getStepname() != null ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "MergeRowsMeta.CheckResult.SourceStepsOK" ), stepMeta );
remarks.add( cr );
} else if ( referenceStream.getStepname() == null && compareStream.getStepname() == null ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "MergeRowsMeta.CheckResult.SourceStepsMissing" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "MergeRowsMeta.CheckResult.OneSourceStepMissing" ), stepMeta );
remarks.add( cr );
}
RowMetaInterface referenceRowMeta = null;
RowMetaInterface compareRowMeta = null;
try {
referenceRowMeta = transMeta.getPrevStepFields( referenceStream.getStepname() );
compareRowMeta = transMeta.getPrevStepFields( compareStream.getStepname() );
} catch ( KettleStepException kse ) {
new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "MergeRowsMeta.CheckResult.ErrorGettingPrevStepFields" ), stepMeta );
}
if ( referenceRowMeta != null && compareRowMeta != null ) {
boolean rowsMatch = false;
try {
MergeRows.checkInputLayoutValid( referenceRowMeta, compareRowMeta );
rowsMatch = true;
} catch ( KettleRowException kre ) {
rowsMatch = false;
}
if ( rowsMatch ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "MergeRowsMeta.CheckResult.RowDefinitionMatch" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "MergeRowsMeta.CheckResult.RowDefinitionNotMatch" ), stepMeta );
remarks.add( cr );
}
}
}
@Override
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta tr,
Trans trans ) {
return new MergeRows( stepMeta, stepDataInterface, cnr, tr, trans );
}
@Override
public StepDataInterface getStepData() {
return new MergeRowsData();
}
/**
* Returns the Input/Output metadata for this step.
*/
@Override
public StepIOMetaInterface getStepIOMeta() {
StepIOMetaInterface ioMeta = super.getStepIOMeta( false );
if ( ioMeta == null ) {
ioMeta = new StepIOMeta( true, true, false, false, false, false );
ioMeta.addStream( new Stream( StreamType.INFO, null, BaseMessages.getString(
PKG, "MergeRowsMeta.InfoStream.FirstStream.Description" ), StreamIcon.INFO, null ) );
ioMeta.addStream( new Stream( StreamType.INFO, null, BaseMessages.getString(
PKG, "MergeRowsMeta.InfoStream.SecondStream.Description" ), StreamIcon.INFO, null ) );
setStepIOMeta( ioMeta );
}
return ioMeta;
}
@Override
public void resetStepIoMeta() {
}
@Override
public TransformationType[] getSupportedTransformationTypes() {
return new TransformationType[] { TransformationType.Normal, };
}
}
|
924349726b1f3b5f98356b0782e467635d904c9a
| 11,824 |
java
|
Java
|
src/main/java/co/phoenixlab/discord/CommandDispatcher.java
|
vincentzhang96/VahrhedralBot
|
e19ea2fa0d105d4572ccc5bb08afde0ddb78ce54
|
[
"MIT"
] | 3 |
2016-01-03T02:31:33.000Z
|
2021-02-13T19:40:53.000Z
|
src/main/java/co/phoenixlab/discord/CommandDispatcher.java
|
vincentzhang96/VahrhedralBot
|
e19ea2fa0d105d4572ccc5bb08afde0ddb78ce54
|
[
"MIT"
] | 24 |
2016-04-20T20:00:58.000Z
|
2021-02-15T08:50:30.000Z
|
src/main/java/co/phoenixlab/discord/CommandDispatcher.java
|
vincentzhang96/VahrhedralBot
|
e19ea2fa0d105d4572ccc5bb08afde0ddb78ce54
|
[
"MIT"
] | 5 |
2015-12-08T14:57:57.000Z
|
2016-12-17T01:01:25.000Z
| 42.228571 | 123 | 0.630497 | 1,002,599 |
package co.phoenixlab.discord;
import co.phoenixlab.common.lang.SafeNav;
import co.phoenixlab.common.localization.Localizer;
import co.phoenixlab.discord.api.entities.Message;
import co.phoenixlab.discord.api.entities.Server;
import co.phoenixlab.discord.cfg.FeatureToggle;
import co.phoenixlab.discord.stats.RunningAverage;
import org.slf4j.Logger;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.BiPredicate;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
public class CommandDispatcher {
private static final Logger LOGGER = VahrhedralBot.LOGGER;
private final VahrhedralBot bot;
private final Map<String, CommandWrapper> commands;
private final Statistics statistics;
private final AtomicBoolean active;
private String commandPrefix;
private BiPredicate<CommandWrapper, MessageContext> customCommandDispatchChecker;
public CommandDispatcher(VahrhedralBot bot, String commandPrefix) {
this.bot = bot;
this.commandPrefix = commandPrefix;
active = new AtomicBoolean(true);
commands = new HashMap<>();
statistics = new Statistics();
customCommandDispatchChecker = (commandWrapper, message) -> true;
addHelpCommand();
}
public String getCommandPrefix() {
return commandPrefix;
}
public void setCommandPrefix(String commandPrefix) {
this.commandPrefix = commandPrefix;
}
public void setCustomCommandDispatchChecker(BiPredicate<CommandWrapper, MessageContext> customCommandDispatchChecker) {
this.customCommandDispatchChecker = customCommandDispatchChecker;
}
private void addHelpCommand() {
registerCommand("commands.help", this::help);
registerCommand("commands.commands", this::help);
}
private void help(MessageContext context, String args) {
Localizer l = context.getBot().getLocalizer();
if (!args.isEmpty()) {
showDetailedCommandHelp(context, args, l);
return;
}
LongAdder adder = new LongAdder();
StringJoiner joiner = new StringJoiner("\n", "", "");
commands.entrySet().stream().
filter(entry -> !entry.getValue().hidden).
forEach(entry -> {
joiner.add(l.localize("commands.help.response.entry",
commandPrefix, entry.getKey().toLowerCase(), entry.getValue().helpDesc));
adder.increment();
});
String header = l.localize("commands.help.response.head", adder.intValue());
final String result = header + joiner.toString();
context.getApiClient().sendMessage(result, context.getChannel());
}
private void showDetailedCommandHelp(MessageContext context, String args, Localizer l) {
CommandWrapper wrapper = commands.get(args.toUpperCase());
if (wrapper != null) {
if (wrapper.examples != null) {
context.getApiClient().sendMessage(l.localize("commands.help.response.detailed.examples",
args, wrapper.detailedHelp, wrapper.argumentsHelp, wrapper.examples),
context.getChannel());
} else {
context.getApiClient().sendMessage(l.localize("commands.help.response.detailed",
args, wrapper.detailedHelp, wrapper.argumentsHelp),
context.getChannel());
}
} else {
context.getApiClient().sendMessage(l.localize("commands.help.response.not_found",
args),
context.getChannel());
}
}
public void registerCommand(String commandNameBaseKey, Command command) {
registerCommand(commandNameBaseKey, command, false);
}
public void registerCommand(String commandNameBaseKey, Command command, boolean hidden) {
Localizer localizer = bot.getLocalizer();
String commandStr = localizer.localize(commandNameBaseKey + ".command").toUpperCase();
String helpStr = localizer.localize(commandNameBaseKey + ".help");
String detailedHelpStr = localizer.localize(commandNameBaseKey + ".detailed_help");
String argumentsStr = localizer.localize(commandNameBaseKey + ".arguments");
String examplesStr = null;
if (localizer.containsKey(commandNameBaseKey + ".examples")) {
examplesStr = localizer.localize(commandNameBaseKey + ".examples");
}
commands.put(commandStr, new CommandWrapper(command,
commandNameBaseKey, helpStr, detailedHelpStr, argumentsStr, examplesStr, false, hidden));
LOGGER.debug("Registered command \"{}\"", commandNameBaseKey);
}
public void registerAlwaysActiveCommand(String commandNameBaseKey, Command command) {
registerAlwaysActiveCommand(commandNameBaseKey, command, false);
}
public void registerAlwaysActiveCommand(String commandNameBaseKey, Command command, boolean hidden) {
Localizer localizer = bot.getLocalizer();
String commandStr = localizer.localize(commandNameBaseKey + ".command").toUpperCase();
String helpStr = localizer.localize(commandNameBaseKey + ".help");
String detailedHelpStr = localizer.localize(commandNameBaseKey + ".detailed_help");
String argumentsStr = localizer.localize(commandNameBaseKey + ".arguments");
String examplesStr = null;
if (localizer.containsKey(commandNameBaseKey + ".examples")) {
examplesStr = localizer.localize(commandNameBaseKey + ".examples");
}
commands.put(commandStr, new CommandWrapper(command,
commandNameBaseKey, helpStr, detailedHelpStr, argumentsStr, examplesStr, true, hidden));
LOGGER.debug("Registered command \"{}\"", commandNameBaseKey);
}
public boolean deleteCommandByName(String commandName) {
if (commandName != null) {
CommandWrapper wrapper = commands.remove(commandName.toUpperCase());
if (wrapper != null) {
LOGGER.debug("Deleted command \"{}\"", wrapper.command);
return true;
}
}
LOGGER.debug("Unable to delete command \"{}\"", commandName);
return false;
}
public boolean deleteCommandByBaseKey(String baseKey) {
String name = bot.getLocalizer().localize(baseKey + ".command");
if (name != null) {
CommandWrapper wrapper = commands.remove(name.toUpperCase());
if (wrapper != null) {
LOGGER.debug("Deleted command \"{}\"", wrapper.command);
return true;
}
}
LOGGER.debug("Unable to delete command key \"{}\"", baseKey);
return false;
}
public void handleCommand(Message msg) {
long cmdStartTime = System.nanoTime();
try {
statistics.commandsReceived.increment();
String content = msg.getContent();
MessageContext messageContext = new MessageContext(msg, bot, this);
String serverName = SafeNav.of(messageContext.getServer())
.next(Server::getName)
.orElse("a private message");
String serverId = SafeNav.of(messageContext.getServer())
.next(Server::getId)
.orElse("N/A");
LOGGER.info("Received command {} from {} ({}) in {} ({})",
content, msg.getAuthor().getUsername(), msg.getAuthor().getId(),
serverName, serverId);
// Remove prefix
String noPrefix = content.substring(commandPrefix.length());
// Split
String[] split = noPrefix.split(" ", 2);
if (split.length == 0) {
// Invalid command
LOGGER.info("Invalid command ignored: {}", content);
statistics.commandsRejected.increment();
return;
}
String cmd = split[0].toUpperCase();
String args = (split.length > 1 ? split[1] : "").trim();
CommandWrapper wrapper = commands.get(cmd);
if (wrapper != null) {
if (shouldCommandBeDispatched(wrapper, messageContext)) {
LOGGER.debug("Dispatching command {}", cmd);
long handleStartTime = System.nanoTime();
wrapper.command.handleCommand(messageContext, args);
statistics.acceptedCommandHandleTime.
add(MILLISECONDS.convert(System.nanoTime() - handleStartTime, NANOSECONDS));
if (bot.getConfig().isSelfBot()) {
bot.getApiClient().deleteMessage(msg.getChannelId(), msg.getId());
}
statistics.commandsHandledSuccessfully.increment();
return;
}
} else {
LOGGER.info("Unknown command \"{}\"", cmd);
}
statistics.commandsRejected.increment();
} finally {
statistics.commandHandleTime.add(MILLISECONDS.convert(System.nanoTime() - cmdStartTime, NANOSECONDS));
}
}
public Statistics getStatistics() {
return statistics;
}
public AtomicBoolean active() {
return active;
}
public boolean shouldCommandBeDispatched(CommandWrapper command, MessageContext context) {
if (command.alwaysActive) {
return true;
}
boolean generalAllow = active().get() &&
customCommandDispatchChecker.test(command, context);
VahrhedralBot bot = context.getBot();
FeatureToggle toggle = bot.getToggleConfig().getToggle(command.commandKey);
return toggle.use(context.getServer().getId(), context.getChannel().getId()) && generalAllow;
}
public static class Statistics {
public final RunningAverage acceptedCommandHandleTime;
public final RunningAverage commandHandleTime;
public final LongAdder commandsReceived;
public final LongAdder commandsHandledSuccessfully;
public final LongAdder commandsRejected;
Statistics() {
acceptedCommandHandleTime = new RunningAverage();
commandHandleTime = new RunningAverage();
commandsReceived = new LongAdder();
commandsHandledSuccessfully = new LongAdder();
commandsRejected = new LongAdder();
}
}
public static class CommandWrapper {
final Command command;
final String commandKey;
final String helpDesc;
final String detailedHelp;
final String argumentsHelp;
final String examples;
final boolean alwaysActive;
final boolean hidden;
public CommandWrapper(Command command, String helpDesc, String detailedHelp, String argumentsHelp,
String examples, String commandKey) {
this(command, commandKey, helpDesc, detailedHelp, argumentsHelp, examples, false, false);
}
public CommandWrapper(Command command, String commandKey, String helpDesc, String detailedHelp,
String argumentsHelp,
String examples,
boolean alwaysActive, boolean hidden) {
this.command = command;
this.commandKey = commandKey;
this.helpDesc = helpDesc;
this.detailedHelp = detailedHelp;
this.argumentsHelp = argumentsHelp;
this.examples = examples;
this.alwaysActive = alwaysActive;
this.hidden = hidden;
}
}
}
|
92434afc458c45a9a8da7f9977ac8d3a19fe0279
| 3,641 |
java
|
Java
|
commercetools/commercetools-sdk-java-history/src/main/java-generated/com/commercetools/history/models/change/SetValidFromAndUntilChangeBuilder.java
|
pintomau/commercetools-sdk-java-v2
|
503a767d35b1495b2740f96082a235cd2d82409f
|
[
"Apache-2.0"
] | 17 |
2020-09-23T10:01:29.000Z
|
2022-03-21T05:58:32.000Z
|
commercetools/commercetools-sdk-java-history/src/main/java-generated/com/commercetools/history/models/change/SetValidFromAndUntilChangeBuilder.java
|
pintomau/commercetools-sdk-java-v2
|
503a767d35b1495b2740f96082a235cd2d82409f
|
[
"Apache-2.0"
] | 130 |
2020-08-25T08:16:38.000Z
|
2022-03-31T10:19:58.000Z
|
commercetools/commercetools-sdk-java-history/src/main/java-generated/com/commercetools/history/models/change/SetValidFromAndUntilChangeBuilder.java
|
pintomau/commercetools-sdk-java-v2
|
503a767d35b1495b2740f96082a235cd2d82409f
|
[
"Apache-2.0"
] | 6 |
2021-06-17T08:42:53.000Z
|
2022-03-09T13:16:20.000Z
| 40.455556 | 185 | 0.747048 | 1,002,600 |
package com.commercetools.history.models.change;
import java.util.*;
import java.util.function.Function;
import io.vrap.rmf.base.client.Builder;
import io.vrap.rmf.base.client.utils.Generated;
@Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen")
public class SetValidFromAndUntilChangeBuilder implements Builder<SetValidFromAndUntilChange> {
private String change;
private com.commercetools.history.models.change_value.ValidFromAndUntilValue previousValue;
private com.commercetools.history.models.change_value.ValidFromAndUntilValue nextValue;
public SetValidFromAndUntilChangeBuilder change(final String change) {
this.change = change;
return this;
}
public SetValidFromAndUntilChangeBuilder previousValue(
Function<com.commercetools.history.models.change_value.ValidFromAndUntilValueBuilder, com.commercetools.history.models.change_value.ValidFromAndUntilValueBuilder> builder) {
this.previousValue = builder
.apply(com.commercetools.history.models.change_value.ValidFromAndUntilValueBuilder.of())
.build();
return this;
}
public SetValidFromAndUntilChangeBuilder previousValue(
final com.commercetools.history.models.change_value.ValidFromAndUntilValue previousValue) {
this.previousValue = previousValue;
return this;
}
public SetValidFromAndUntilChangeBuilder nextValue(
Function<com.commercetools.history.models.change_value.ValidFromAndUntilValueBuilder, com.commercetools.history.models.change_value.ValidFromAndUntilValueBuilder> builder) {
this.nextValue = builder.apply(com.commercetools.history.models.change_value.ValidFromAndUntilValueBuilder.of())
.build();
return this;
}
public SetValidFromAndUntilChangeBuilder nextValue(
final com.commercetools.history.models.change_value.ValidFromAndUntilValue nextValue) {
this.nextValue = nextValue;
return this;
}
public String getChange() {
return this.change;
}
public com.commercetools.history.models.change_value.ValidFromAndUntilValue getPreviousValue() {
return this.previousValue;
}
public com.commercetools.history.models.change_value.ValidFromAndUntilValue getNextValue() {
return this.nextValue;
}
public SetValidFromAndUntilChange build() {
Objects.requireNonNull(change, SetValidFromAndUntilChange.class + ": change is missing");
Objects.requireNonNull(previousValue, SetValidFromAndUntilChange.class + ": previousValue is missing");
Objects.requireNonNull(nextValue, SetValidFromAndUntilChange.class + ": nextValue is missing");
return new SetValidFromAndUntilChangeImpl(change, previousValue, nextValue);
}
/**
* builds SetValidFromAndUntilChange without checking for non null required values
*/
public SetValidFromAndUntilChange buildUnchecked() {
return new SetValidFromAndUntilChangeImpl(change, previousValue, nextValue);
}
public static SetValidFromAndUntilChangeBuilder of() {
return new SetValidFromAndUntilChangeBuilder();
}
public static SetValidFromAndUntilChangeBuilder of(final SetValidFromAndUntilChange template) {
SetValidFromAndUntilChangeBuilder builder = new SetValidFromAndUntilChangeBuilder();
builder.change = template.getChange();
builder.previousValue = template.getPreviousValue();
builder.nextValue = template.getNextValue();
return builder;
}
}
|
92434b1d3fee44041f75154d17bad7c5225240c7
| 1,849 |
java
|
Java
|
ddprofiler/src/main/java/sources/config/HiveSourceConfig.java
|
Florents-Tselai/aurum-datadiscovery
|
810c252981a0623df23b39fb186d212ab6076ca5
|
[
"MIT"
] | 60 |
2017-01-13T19:53:34.000Z
|
2022-01-06T07:00:43.000Z
|
ddprofiler/src/main/java/sources/config/HiveSourceConfig.java
|
Florents-Tselai/aurum-datadiscovery
|
810c252981a0623df23b39fb186d212ab6076ca5
|
[
"MIT"
] | 83 |
2016-10-08T14:07:55.000Z
|
2022-03-08T22:03:39.000Z
|
ddprofiler/src/main/java/sources/config/HiveSourceConfig.java
|
TheDataStation/aurum-dod-staging
|
4653be563bf6dd77eadb23bfc6bc1eb374ef313c
|
[
"MIT"
] | 44 |
2016-10-08T00:15:46.000Z
|
2021-12-31T02:42:45.000Z
| 19.260417 | 55 | 0.691184 | 1,002,601 |
package sources.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import sources.SourceType;
public class HiveSourceConfig implements SourceConfig {
private String sourceName;
private String relationName;
@JsonProperty
private String hive_server_ip;
@JsonProperty
private int hive_server_port;
@JsonProperty
private String path;
@JsonProperty
private String database_name;
// @JsonProperty
// private String db_username;
//
// @JsonProperty
// private String db_password;
public String getHive_server_ip() {
return hive_server_ip;
}
public int getHive_server_port() {
return hive_server_port;
}
public String getDatabase_name() {
return database_name;
}
@Override
public String getPath() {
return path;
}
//
// public String getDb_username() {
// return db_username;
// }
//
// public String getDb_password() {
// return db_password;
// }
@Override
public String getSourceName() {
return sourceName;
}
@Override
public void setSourceName(String sourceName) {
this.sourceName = sourceName;
}
@Override
public SourceType getSourceType() {
return SourceType.hive;
}
public String getRelationName() {
return relationName;
}
public void setRelationName(String relationName) {
this.relationName = relationName;
}
@Override
public SourceConfig selfCopy() {
HiveSourceConfig copy = new HiveSourceConfig();
copy.sourceName = this.sourceName;
copy.relationName = this.relationName;
// copy.database_name = this.database_name;
copy.hive_server_ip = this.hive_server_ip;
copy.hive_server_port = this.hive_server_port;
// copy.db_username = this.db_username;
// copy.db_password = this.db_password;
return copy;
}
}
|
92434c4f438dcb7922ffd7c8761333ba365ae2dc
| 265 |
java
|
Java
|
async-gateway-pipeline/src/main/java/com/gulf/async/gateway/pipeline/GatewayPipelineImpl.java
|
gulf-university/asyc-gateway
|
b8bce5c58ac67e388bec125b932ee7a3a54aa85b
|
[
"Apache-2.0"
] | 4 |
2019-09-09T17:35:17.000Z
|
2019-10-26T06:12:06.000Z
|
async-gateway-pipeline/src/main/java/com/gulf/async/gateway/pipeline/GatewayPipelineImpl.java
|
gulf-university/asyc-gateway
|
b8bce5c58ac67e388bec125b932ee7a3a54aa85b
|
[
"Apache-2.0"
] | null | null | null |
async-gateway-pipeline/src/main/java/com/gulf/async/gateway/pipeline/GatewayPipelineImpl.java
|
gulf-university/asyc-gateway
|
b8bce5c58ac67e388bec125b932ee7a3a54aa85b
|
[
"Apache-2.0"
] | 1 |
2019-10-08T11:43:33.000Z
|
2019-10-08T11:43:33.000Z
| 18.928571 | 65 | 0.739623 | 1,002,602 |
package com.gulf.async.gateway.pipeline;
import com.gulf.async.gateway.common.spi.Activate;
/**
* Created by xubai on 2020/01/08 8:33 PM.
*/
@Activate(group={"pipeline"}, tag = {"default"})
public class GatewayPipelineImpl extends AbstractGatewayPipeline{
}
|
92434cdc2c862865ea5aa8fd3d64870227bcc441
| 262 |
java
|
Java
|
src/main/java/de/friedrichs/malteser/data/service/PilotRepository.java
|
undso/rikscha
|
6faf897f8b2d980fee1d1423fbad1519bf4fb5c3
|
[
"Unlicense"
] | null | null | null |
src/main/java/de/friedrichs/malteser/data/service/PilotRepository.java
|
undso/rikscha
|
6faf897f8b2d980fee1d1423fbad1519bf4fb5c3
|
[
"Unlicense"
] | null | null | null |
src/main/java/de/friedrichs/malteser/data/service/PilotRepository.java
|
undso/rikscha
|
6faf897f8b2d980fee1d1423fbad1519bf4fb5c3
|
[
"Unlicense"
] | null | null | null | 20.153846 | 70 | 0.774809 | 1,002,603 |
package de.friedrichs.malteser.data.service;
import de.friedrichs.malteser.data.entity.Pilot;
import org.springframework.data.jpa.repository.JpaRepository;
/**
*
* @author AFR
*/
public interface PilotRepository extends JpaRepository<Pilot, String>{
}
|
92434d190a8d4f2a559043647c261b55cd225197
| 3,401 |
java
|
Java
|
Studio/plugins/com.wizzer.mle.studio.framework.ext32/src/com/wizzer/mle/studio/framework/ext/OleControlSiteEx.java
|
magic-lantern-studio/mle-studio
|
e962ecf8bc64a854fcd997196be1857d078a2781
|
[
"MIT"
] | null | null | null |
Studio/plugins/com.wizzer.mle.studio.framework.ext32/src/com/wizzer/mle/studio/framework/ext/OleControlSiteEx.java
|
magic-lantern-studio/mle-studio
|
e962ecf8bc64a854fcd997196be1857d078a2781
|
[
"MIT"
] | 28 |
2020-06-24T16:47:07.000Z
|
2020-08-06T05:15:59.000Z
|
Studio/plugins/com.wizzer.mle.studio.framework.ext32/src/com/wizzer/mle/studio/framework/ext/OleControlSiteEx.java
|
magic-lantern-studio/mle-studio
|
e962ecf8bc64a854fcd997196be1857d078a2781
|
[
"MIT"
] | null | null | null | 28.838983 | 99 | 0.70908 | 1,002,604 |
// COPYRIGHT_BEGIN
//
// Copyright (C) 2000-2011 Wizzer Works
//
// Wizzer Works makes available all content in this file ("Content").
// Unless otherwise indicated below, the Content is provided to you
// under the terms and conditions of the Common Public License Version 1.0
// ("CPL"). A copy of the CPL is available at
//
// http://opensource.org/licenses/cpl1.0.php
//
// For purposes of the CPL, "Program" will mean the Content.
//
// For information concerning this Makefile, contact Mark S. Millard,
// of Wizzer Works at [email protected].
//
// More information concerning Wizzer Works may be found at
//
// http://www.wizzerworks.com
//
// COPYRIGHT_END
// Declare package.
package com.wizzer.mle.studio.framework.ext;
// Import Eclipse classes.
import org.eclipse.swt.ole.win32.OleClientSite;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.internal.ole.win32.*;
import org.eclipse.swt.internal.win32.SIZE;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.graphics.Point;
/**
* This class extends <code>OleClientSite</code> for the creation of ActiveX controls,
* in or out-of-process.
*
* @author Mark S. Millard
*
* Uses CoCreateInstance to create a COM object (instead of OleCreate);
* this allows the creation of an out-of-process server.
*/
public class OleControlSiteEx extends OleClientSite implements IControlSite
{
/**
* A constructor that specifies the parent <code>OleFrame</code> in which to embed
* the COM object.
*
* @param parent A composite widget; must be an OleFrame.
* @param style The bitwise OR'ing of widget styles.
* @param progId The unique program identifier of an OLE Document application;
* the value of the ProgID key or the value of the VersionIndependentProgID key
* specified in the registry for the desired OLE Document (for example,
* the VersionIndependentProgID for Word is Word.Document) program identifier.
*/
public OleControlSiteEx(Composite parent, int style, String progId)
{
super(parent, style);
try
{
// Get the class identifier.
appClsid = getClassID(progId);
if (appClsid == null)
{
OLE.error(OLE.ERROR_INVALID_CLASSID);
}
// Create the object.
long[] ppvObject = new long[1];
int CLSCTX_ALL = COM.CLSCTX_INPROC_SERVER | COM.CLSCTX_LOCAL_SERVER | COM.CLSCTX_INPROC_HANDLER;
int hr = COM.CoCreateInstance(appClsid, 0, CLSCTX_ALL, COM.IIDIUnknown, ppvObject);
if (hr != COM.S_OK)
{
OLE.error(OLE.ERROR_CANNOT_CREATE_OBJECT, hr);
}
// Set the IUnknown pointer.
objIUnknown = new IUnknown(ppvObject[0]);
// Initialize sinks.
addObjectReferences();
}
catch(SWTError ex)
{
this.dispose();
disposeCOMInterfaces();
throw ex;
}
}
/**
* Get the extent of the embedded OLE native object.
*
* @return a <>Point<> is returned containing the x and y dimensions of the
* embedded OLE native object.
*/
public Point getExtent()
{
SIZE sizel = new SIZE();
// Get the current size of the embedded OLENatives object.
if (objIOleObject != null)
{
if (objIViewObject2 != null && !COM.OleIsRunning(objIOleObject.getAddress()))
{
objIViewObject2.GetExtent(COM.DVASPECT_CONTENT, -1, 0, sizel);
} else
{
objIOleObject.GetExtent(COM.DVASPECT_CONTENT, sizel);
}
}
return new Point(sizel.cx, sizel.cy);
}
};
|
92434d42a7535afaaec40ce97bc7d83d700c8aab
| 2,420 |
java
|
Java
|
Back End/com-cg-surveyportal/src/main/java/com/cg/surveyportal/entities/Feedback.java
|
mebhushanjoshi/SurveyPortalApp
|
89f428ec810dd22e262c12d8b61ccb35869d5b3f
|
[
"MIT"
] | null | null | null |
Back End/com-cg-surveyportal/src/main/java/com/cg/surveyportal/entities/Feedback.java
|
mebhushanjoshi/SurveyPortalApp
|
89f428ec810dd22e262c12d8b61ccb35869d5b3f
|
[
"MIT"
] | null | null | null |
Back End/com-cg-surveyportal/src/main/java/com/cg/surveyportal/entities/Feedback.java
|
mebhushanjoshi/SurveyPortalApp
|
89f428ec810dd22e262c12d8b61ccb35869d5b3f
|
[
"MIT"
] | 1 |
2021-05-17T15:21:42.000Z
|
2021-05-17T15:21:42.000Z
| 23.269231 | 114 | 0.754132 | 1,002,605 |
package com.cg.surveyportal.entities;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
@Entity
@Table
public class Feedback {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column
private LocalDateTime postedDateTime;
@ManyToOne(optional = true)
@JsonBackReference("surveys_feedback")
private Survey survey;
@ManyToOne(optional = true)
//@JsonBackReference("participant_feedback")
//@JsonManagedReference
private Participant participant;
@OneToOne
//@JsonBackReference("feedback_question")
private Question question;
@Column
private String chosenOption;
public Feedback() {}
public Feedback(Long id, LocalDateTime postedDateTime, Survey survey, Participant participant, Question question,
String chosenOption) {
super();
this.id = id;
this.postedDateTime = postedDateTime;
this.survey = survey;
this.participant = participant;
this.question = question;
this.chosenOption = chosenOption;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDateTime getPostedDateTime() {
return postedDateTime;
}
public void setPostedDateTime(LocalDateTime postedDateTime) {
this.postedDateTime = postedDateTime;
}
public Survey getSurvey() {
return survey;
}
public void setSurvey(Survey survey) {
this.survey = survey;
}
public Participant getParticipant() {
return participant;
}
public void setParticipant(Participant participant) {
this.participant = participant;
}
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
public String getChosenOption() {
return chosenOption;
}
public void setChosenOption(String chosenOption) {
this.chosenOption = chosenOption;
}
@Override
public String toString() {
return "Feedback [id=" + id + ", postedDateTime=" + postedDateTime + ", survey=" + survey + ", participant="
+ participant + ", question=" + question + ", chosenOption=" + chosenOption + "]";
}
}
|
92434de78c4e4c9c1a5e6f0d0113f06adc23663d
| 23,669 |
java
|
Java
|
src/me/kazik24/mtdm/KeyedData.java
|
Kazik24x/MultiTypeDataMap
|
b4695fafa5b986fa380b4a2fee29cb014b6f569b
|
[
"MIT"
] | null | null | null |
src/me/kazik24/mtdm/KeyedData.java
|
Kazik24x/MultiTypeDataMap
|
b4695fafa5b986fa380b4a2fee29cb014b6f569b
|
[
"MIT"
] | null | null | null |
src/me/kazik24/mtdm/KeyedData.java
|
Kazik24x/MultiTypeDataMap
|
b4695fafa5b986fa380b4a2fee29cb014b6f569b
|
[
"MIT"
] | null | null | null | 24.784293 | 117 | 0.62584 | 1,002,606 |
package me.kazik24.mtdm;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import me.kazik24.mtdm.KeyEntry.BinaryKeyEntry;
import me.kazik24.mtdm.KeyPiece.*;
public class KeyedData{
private static final int INIT_SIZE = 5;
private int size;
private KeyPiece[] binary;
private int property;
private KeyPiece getCell(int key){
KeyPiece[] bin = binary;
if(bin == null || bin.length <= 1) return null;
KeyPiece piece = bin[Math.abs(key%(bin.length-1))+1];
while(piece != null){
if(piece.key == key) return piece;
piece = piece.next;
}
return null;
}
private static KeyPiece[] tryRehash(KeyPiece[] bin){return bin;}
private static int incSize(KeyPiece[] bin){
KeyPiece p = bin[0];
if(p == null){
p = new KeyPiece(1);
bin[0] = p;
}
return p.key++;
}
private static boolean checkConst(KeyPiece[] bin){
if(bin == null) return false;
KeyPiece p = bin[0];
if(p == null) return false;
if(p.next == KeyPiece.CONST_GUARD) return true;
return false;
}
private static int decSize(KeyPiece[] bin){
KeyPiece p = bin[0];
if(p == null) return 0;
return p.key--;
}
private static KeyPiece[] newTable(KeyPiece first){
KeyPiece[] arr = new KeyPiece[INIT_SIZE];
arr[0] = new KeyPiece(1);
int idx = Math.abs(first.key%(INIT_SIZE-1))+1;
arr[idx] = first;
return arr;
}
public boolean containsKey(int key){
KeyPiece[] bin = binary;
if(bin == null || bin.length <= 1) return false;
int index = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[index];
while(piece != null){
if(piece.key == key) return true;
piece = piece.next;
}
return false;
}
public int size(){
KeyPiece[] bin = binary;
if(bin == null || bin.length <= 1) return 0;
KeyPiece piece = bin[0];
if(piece == null) return 0;
return piece.key;
}
public boolean remove(int key){
KeyPiece[] bin = binary;
if(bin == null || bin.length <= 1) return false;
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null) return false;
if(piece.key == key){
bin[idx] = piece.next;
decSize(bin);
return true;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null) return false;
if(next.key == key){
piece.next = next.next;
decSize(bin);
return true;
}
piece = next;
}
}
public void clear(){
binary = null;
}
public void setConst(boolean c){
}
public boolean isConst(){return checkConst(binary);}
public EntryType getType(int key){
KeyPiece piece = getCell(key);
if(piece == null) return null;
return piece.type();
}
public KeyEntry getEntry(int key){return getCell(key);}
public BinaryKeyEntry getBinaryEntry(int key){
KeyPiece p = getCell(key);
if(p != null && p.getClass() == BinPiece.class) return (BinPiece)p;
return null;
}
//single
public byte getByte(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != BytePiece.class) return 0;
return ((BytePiece)piece).data;
}
public boolean putByte(int key,byte data){
if(data == 0){
remove(key);
return false;
}
KeyPiece[] bin = binary;
KeyPiece[] old = bin;
if(bin == null){
binary = newTable(new BytePiece(key,data));
return true;
}
if(bin.length <= 1){
binary = newTable(new BytePiece(key,data));
return true;
}
bin = tryRehash(bin);
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null){
bin[idx] = new BytePiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(piece.key == key){
if(piece.getClass() == BytePiece.class){
((BytePiece)piece).data = data;
}else{
KeyPiece p = new BytePiece(key,data);
p.next = piece.next;
bin[idx] = p;
}
binary = bin;
return false;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null){
piece.next = new BytePiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(next.key == key){
if(next.getClass() == BytePiece.class){
((BytePiece)piece).data = data;
}else{
KeyPiece p = new BytePiece(key,data);
p.next = next.next;
piece.next = p;
}
binary = bin;
return false;
}
piece = next;
}
}
public boolean isByte(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != BytePiece.class) return false;
return true;
}
public short getShort(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != ShortPiece.class) return 0;
return ((ShortPiece)piece).data;
}
public boolean putShort(int key,short data){
if(data == 0){
remove(key);
return false;
}
KeyPiece[] bin = binary;
KeyPiece[] old = bin;
if(bin == null){
binary = newTable(new ShortPiece(key,data));
return true;
}
if(bin.length <= 1){
binary = newTable(new ShortPiece(key,data));
return true;
}
bin = tryRehash(bin);
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null){
bin[idx] = new ShortPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(piece.key == key){
if(piece.getClass() == ShortPiece.class){
((ShortPiece)piece).data = data;
}else{
KeyPiece p = new ShortPiece(key,data);
p.next = piece.next;
bin[idx] = p;
}
binary = bin;
return false;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null){
piece.next = new ShortPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(next.key == key){
if(next.getClass() == ShortPiece.class){
((ShortPiece)piece).data = data;
}else{
KeyPiece p = new ShortPiece(key,data);
p.next = next.next;
piece.next = p;
}
binary = bin;
return false;
}
piece = next;
}
}
public boolean isShort(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != ShortPiece.class) return false;
return true;
}
public char getChar(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != CharPiece.class) return 0;
return ((CharPiece)piece).data;
}
public boolean putChar(int key,char data){
if(data == 0){
remove(key);
return false;
}
KeyPiece[] bin = binary;
KeyPiece[] old = bin;
if(bin == null){
binary = newTable(new CharPiece(key,data));
return true;
}
if(bin.length <= 1){
binary = newTable(new CharPiece(key,data));
return true;
}
bin = tryRehash(bin);
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null){
bin[idx] = new CharPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(piece.key == key){
if(piece.getClass() == CharPiece.class){
((CharPiece)piece).data = data;
}else{
KeyPiece p = new CharPiece(key,data);
p.next = piece.next;
bin[idx] = p;
}
binary = bin;
return false;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null){
piece.next = new CharPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(next.key == key){
if(next.getClass() == CharPiece.class){
((CharPiece)piece).data = data;
}else{
KeyPiece p = new CharPiece(key,data);
p.next = next.next;
piece.next = p;
}
binary = bin;
return false;
}
piece = next;
}
}
public boolean isChar(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != CharPiece.class) return false;
return true;
}
public int getInt(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != IntPiece.class) return 0;
return ((IntPiece)piece).data;
}
public boolean putInt(int key,int data){
if(data == 0){
remove(key);
return false;
}
KeyPiece[] bin = binary;
KeyPiece[] old = bin;
if(bin == null){
binary = newTable(new IntPiece(key,data));
return true;
}
if(bin.length <= 1){
binary = newTable(new IntPiece(key,data));
return true;
}
bin = tryRehash(bin);
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null){
bin[idx] = new IntPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(piece.key == key){
if(piece.getClass() == IntPiece.class){
((IntPiece)piece).data = data;
}else{
KeyPiece p = new IntPiece(key,data);
p.next = piece.next;
bin[idx] = p;
}
binary = bin;
return false;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null){
piece.next = new IntPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(next.key == key){
if(next.getClass() == IntPiece.class){
((IntPiece)piece).data = data;
}else{
KeyPiece p = new IntPiece(key,data);
p.next = next.next;
piece.next = p;
}
binary = bin;
return false;
}
piece = next;
}
}
public boolean isInt(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != IntPiece.class) return false;
return true;
}
public float getFloat(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != FloatPiece.class) return 0;
return ((FloatPiece)piece).data;
}
public boolean putFloat(int key,float data){
if(data == 0){
remove(key);
return false;
}
KeyPiece[] bin = binary;
KeyPiece[] old = bin;
if(bin == null){
binary = newTable(new FloatPiece(key,data));
return true;
}
if(bin.length <= 1){
binary = newTable(new FloatPiece(key,data));
return true;
}
bin = tryRehash(bin);
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null){
bin[idx] = new FloatPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(piece.key == key){
if(piece.getClass() == FloatPiece.class){
((FloatPiece)piece).data = data;
}else{
KeyPiece p = new FloatPiece(key,data);
p.next = piece.next;
bin[idx] = p;
}
binary = bin;
return false;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null){
piece.next = new FloatPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(next.key == key){
if(next.getClass() == FloatPiece.class){
((FloatPiece)piece).data = data;
}else{
KeyPiece p = new FloatPiece(key,data);
p.next = next.next;
piece.next = p;
}
binary = bin;
return false;
}
piece = next;
}
}
public boolean isFloat(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != FloatPiece.class) return false;
return true;
}
public long getLong(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != LongPiece.class) return 0;
return ((LongPiece)piece).data;
}
public boolean putLong(int key,long data){
if(data == 0){
remove(key);
return false;
}
KeyPiece[] bin = binary;
KeyPiece[] old = bin;
if(bin == null){
binary = newTable(new LongPiece(key,data));
return true;
}
if(bin.length <= 1){
binary = newTable(new LongPiece(key,data));
return true;
}
bin = tryRehash(bin);
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null){
bin[idx] = new LongPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(piece.key == key){
if(piece.getClass() == LongPiece.class){
((LongPiece)piece).data = data;
}else{
KeyPiece p = new LongPiece(key,data);
p.next = piece.next;
bin[idx] = p;
}
binary = bin;
return false;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null){
piece.next = new LongPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(next.key == key){
if(next.getClass() == LongPiece.class){
((LongPiece)piece).data = data;
}else{
KeyPiece p = new LongPiece(key,data);
p.next = next.next;
piece.next = p;
}
binary = bin;
return false;
}
piece = next;
}
}
public boolean isLong(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != LongPiece.class) return false;
return true;
}
public double getDouble(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != DoublePiece.class) return 0;
return ((DoublePiece)piece).data;
}
public boolean putDouble(int key,double data){
if(data == 0){
remove(key);
return false;
}
KeyPiece[] bin = binary;
KeyPiece[] old = bin;
if(bin == null){
binary = newTable(new DoublePiece(key,data));
return true;
}
if(bin.length <= 1){
binary = newTable(new DoublePiece(key,data));
return true;
}
bin = tryRehash(bin);
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null){
bin[idx] = new DoublePiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(piece.key == key){
if(piece.getClass() == DoublePiece.class){
((DoublePiece)piece).data = data;
}else{
KeyPiece p = new DoublePiece(key,data);
p.next = piece.next;
bin[idx] = p;
}
binary = bin;
return false;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null){
piece.next = new DoublePiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(next.key == key){
if(next.getClass() == DoublePiece.class){
((DoublePiece)piece).data = data;
}else{
KeyPiece p = new DoublePiece(key,data);
p.next = next.next;
piece.next = p;
}
binary = bin;
return false;
}
piece = next;
}
}
public boolean isDouble(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != DoublePiece.class) return false;
return true;
}
public String getString(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != StringPiece.class) return null;
return ((StringPiece)piece).data;
}
public boolean putString(int key,String data){
if(data == null){
remove(key);
return false;
}
KeyPiece[] bin = binary;
KeyPiece[] old = bin;
if(bin == null){
binary = newTable(new StringPiece(key,data));
return true;
}
if(bin.length <= 1){
binary = newTable(new StringPiece(key,data));
return true;
}
bin = tryRehash(bin);
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null){
bin[idx] = new StringPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(piece.key == key){
if(piece.getClass() == StringPiece.class){
((StringPiece)piece).data = data;
}else{
KeyPiece p = new StringPiece(key,data);
p.next = piece.next;
bin[idx] = p;
}
binary = bin;
return false;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null){
piece.next = new StringPiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(next.key == key){
if(next.getClass() == StringPiece.class){
((StringPiece)piece).data = data;
}else{
KeyPiece p = new StringPiece(key,data);
p.next = next.next;
piece.next = p;
}
binary = bin;
return false;
}
piece = next;
}
}
public boolean isString(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != StringPiece.class) return false;
return true;
}
public InputStream getBinary(int key){
BinaryKeyEntry e = getBinaryEntry(key);
if(e == null) return null;
return e.openRead();
}
public boolean isBinary(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != BinPiece.class) return false;
return true;
}
//array
public byte[] getByteArray(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != ABytePiece.class) return null;
return ((ABytePiece)piece).data;
}
public byte[] getByteArrayCopy(int key){
byte[] arr = getByteArray(key);
if(arr != null) return arr.clone();
return null;
}
public boolean putByteArray(int key,byte[] data){
if(data == null || data.length == 0){
remove(key);
return false;
}
KeyPiece[] bin = binary;
KeyPiece[] old = bin;
if(bin == null){
binary = newTable(new ABytePiece(key,data));
return true;
}
if(bin.length <= 1){
binary = newTable(new ABytePiece(key,data));
return true;
}
bin = tryRehash(bin);
int idx = Math.abs(key%(bin.length-1))+1;
KeyPiece piece = bin[idx];
if(piece == null){
bin[idx] = new ABytePiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(piece.key == key){
if(piece.getClass() == ABytePiece.class){
((ABytePiece)piece).data = data;
}else{
KeyPiece p = new ABytePiece(key,data);
p.next = piece.next;
bin[idx] = p;
}
binary = bin;
return false;
}
KeyPiece next;
for(;;){
next = piece.next;
if(next == null){
piece.next = new ABytePiece(key,data);
incSize(bin);
binary = bin;
return true;
}
if(next.key == key){
if(next.getClass() == ABytePiece.class){
((ABytePiece)piece).data = data;
}else{
KeyPiece p = new ABytePiece(key,data);
p.next = next.next;
piece.next = p;
}
binary = bin;
return false;
}
piece = next;
}
}
public boolean putByteArrayCopy(int key,byte[] data){
if(data == null || data.length == 0){
remove(key);
return false;
}
return putByteArray(key,data.clone());
}
public short[] getShortArray(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != AShortPiece.class) return null;
return ((AShortPiece)piece).data;
}
public short[] getShortArrayCopy(int key){
short[] arr = getShortArray(key);
if(arr != null) return arr.clone();
return null;
}
public char[] getCharArray(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != ACharPiece.class) return null;
return ((ACharPiece)piece).data;
}
public char[] getCharArrayCopy(int key){
char[] arr = getCharArray(key);
if(arr != null) return arr.clone();
return null;
}
public int[] getIntArray(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != AIntPiece.class) return null;
return ((AIntPiece)piece).data;
}
public int[] getIntArrayCopy(int key){
int[] arr = getIntArray(key);
if(arr != null) return arr.clone();
return null;
}
public float[] getFloatArray(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != AFloatPiece.class) return null;
return ((AFloatPiece)piece).data;
}
public float[] getFloatArrayCopy(int key){
float[] arr = getFloatArray(key);
if(arr != null) return arr.clone();
return null;
}
public long[] getLongArray(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != ALongPiece.class) return null;
return ((ALongPiece)piece).data;
}
public long[] getLongArrayCopy(int key){
long[] arr = getLongArray(key);
if(arr != null) return arr.clone();
return null;
}
public double[] getDoubleArray(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != ADoublePiece.class) return null;
return ((ADoublePiece)piece).data;
}
public double[] getDoubleArrayCopy(int key){
double[] arr = getDoubleArray(key);
if(arr != null) return arr.clone();
return null;
}
public String[] getStringArray(int key){
KeyPiece piece = getCell(key);
if(piece == null || piece.getClass() != AStringPiece.class) return null;
return ((AStringPiece)piece).data;
}
public String[] getStringArrayCopy(int key){
String[] arr = getStringArray(key);
if(arr != null) return arr.clone();
return null;
}
//iterate
public KeyIterator iterator(KeyIterator ref){
if(ref == null) ref = new KeyIterator();
ref.reset();
ref.ref = this;
return ref;
}
public KeyIterator iterator(){return iterator(null);}
public boolean put(int key,Object value);
public Object get(int key){
KeyPiece piece = getCell(key);
if(piece == null) return null;
return piece.get();
}
public byte[] toByteArray();
public void fromByteArray(byte[] arr,int offset,int length);
public void writeTo(OutputStream out) throws IOException;
public void readFrom(InputStream in) throws IOException;
public static void writeToStream(KeyedData obj,OutputStream out) throws IOException{writeToStream(obj,out,null);}
public static void writeToStream(KeyedData obj,OutputStream out,RepositorySerializationMap rmap) throws IOException{
if(obj == null){
Utils.writeInt(-1,out);
return;
}
KeyPiece[] hash = obj.binary;
if(hash == null){
Utils.writeInt(0,out);
return;
}
int size = obj.size();
Utils.writeInt(size,out);
if(size == 0) return;
Utils.writeInt(hash.length,out);//write hashtable size for fast deserialization
int count = 0;
for(int i = 0;i<hash.length;i++){
for(KeyPiece piece = hash[i];piece != null;piece = piece.next){
Utils.writeInt(piece.key,out);
//entry serialization*************************
Class<?> type = piece.getClass();
if(!piece.isArray()){
if(type == BytePiece.class){
out.write(DataConstants.BYTE);
out.write(((BytePiece)piece).data);
}else if(type == ShortPiece.class){
out.write(DataConstants.SHORT);
Utils.writeShort(((ShortPiece)piece).data,out);
}else if(type == CharPiece.class){
out.write(DataConstants.CHAR);
Utils.writeChar(((CharPiece)piece).data,out);
}else if(type == IntPiece.class){
out.write(DataConstants.INT);
Utils.writeInt(((IntPiece)piece).data,out);
}else if(type == FloatPiece.class){
out.write(DataConstants.FLOAT);
Utils.writeFloat(((FloatPiece)piece).data,out);
}else if(type == LongPiece.class){
out.write(DataConstants.LONG);
Utils.writeLong(((LongPiece)piece).data,out);
}else if(type == DoublePiece.class){
out.write(DataConstants.DOUBLE);
Utils.writeDouble(((DoublePiece)piece).data,out);
}else if(type == StringPiece.class){
out.write(DataConstants.STRING);
Utils.writeString(((StringPiece)piece).data,out);
}else if(type == KeyedPiece.class){
if(rmap == null) rmap = new RepositorySerializationMap(32);
int rref = rmap.findAndContain(obj,-1);
if(rref != -1){
out.write(DataConstants.SERIAL_REF);
Utils.writeInt(rref,out);
}else{
out.write(DataConstants.KEY);
writeToStream(((KeyedPiece)piece).data,out,rmap);
}
}
}
count++;
if(count >= size) return;
}
}
}
public static boolean writePrimitiveEntry(KeyPiece piece,OutputStream out) throws IOException{
Class<?> type = piece.getClass();
if(type == BytePiece.class){
out.write(DataConstants.BYTE);
out.write(((BytePiece)piece).data);
}else if(type == ShortPiece.class){
out.write(DataConstants.SHORT);
Utils.writeShort(((ShortPiece)piece).data,out);
}else if(type == CharPiece.class){
out.write(DataConstants.CHAR);
Utils.writeChar(((CharPiece)piece).data,out);
}else if(type == IntPiece.class){
out.write(DataConstants.INT);
Utils.writeInt(((IntPiece)piece).data,out);
}else if(type == FloatPiece.class){
out.write(DataConstants.FLOAT);
Utils.writeFloat(((FloatPiece)piece).data,out);
}else if(type == LongPiece.class){
out.write(DataConstants.LONG);
Utils.writeLong(((LongPiece)piece).data,out);
}else if(type == DoublePiece.class){
out.write(DataConstants.DOUBLE);
Utils.writeDouble(((DoublePiece)piece).data,out);
}else return false;
return true;
}
public static KeyedData readFromStream(InputStream in) throws IOException{
}
}
|
92434ef10c90da2f718f00df0307c1300086b9ec
| 587 |
java
|
Java
|
app/src/main/java/com/coolweather/android/gson/Suggestion.java
|
chenhangjun/coolweather
|
b24aeb080598e3349123e3af2c9561aba673e465
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/coolweather/android/gson/Suggestion.java
|
chenhangjun/coolweather
|
b24aeb080598e3349123e3af2c9561aba673e465
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/coolweather/android/gson/Suggestion.java
|
chenhangjun/coolweather
|
b24aeb080598e3349123e3af2c9561aba673e465
|
[
"Apache-2.0"
] | null | null | null | 16.771429 | 50 | 0.632027 | 1,002,607 |
package com.coolweather.android.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by Administrator on 2018/3/5.
*/
public class Suggestion {
@SerializedName("comf")
public Comfort comfort;
@SerializedName("cw")
public CardWash cardWash;
public Sport sport;
public class Comfort {
@SerializedName("txt")
public String info;
}
public class CardWash {
@SerializedName("txt")
public String info;
}
public class Sport {
@SerializedName("txt")
public String info;
}
}
|
92435008500d0b0e2361167599a1637dd97f4612
| 336 |
java
|
Java
|
Aplicacao/app/src/main/java/com/example/egisquiz/capitulo4.java
|
StkaaPa/Android-App-EgisRoadPortugal
|
7ee1907ff697228987066945ed3900b96de1be42
|
[
"MIT"
] | null | null | null |
Aplicacao/app/src/main/java/com/example/egisquiz/capitulo4.java
|
StkaaPa/Android-App-EgisRoadPortugal
|
7ee1907ff697228987066945ed3900b96de1be42
|
[
"MIT"
] | null | null | null |
Aplicacao/app/src/main/java/com/example/egisquiz/capitulo4.java
|
StkaaPa/Android-App-EgisRoadPortugal
|
7ee1907ff697228987066945ed3900b96de1be42
|
[
"MIT"
] | null | null | null | 22.4 | 56 | 0.761905 | 1,002,608 |
package com.example.egisquiz;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class capitulo4 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capitulo4);
}
}
|
92435080152d4686ec9c30e4574fe46a01bf6d71
| 5,446 |
java
|
Java
|
library/src/main/java/com/pchmn/materialchips/util/MyWindowCallback.java
|
teusemanuel/MaterialChipsInput
|
c4360d79412344f1bd0743460e0a8f60f6953152
|
[
"Apache-2.0"
] | 2,847 |
2017-04-14T04:04:17.000Z
|
2022-03-23T06:02:57.000Z
|
library/src/main/java/com/pchmn/materialchips/util/MyWindowCallback.java
|
hallefy/MaterialChipsInput
|
c4360d79412344f1bd0743460e0a8f60f6953152
|
[
"Apache-2.0"
] | 124 |
2017-04-16T11:41:30.000Z
|
2022-03-23T06:08:50.000Z
|
library/src/main/java/com/pchmn/materialchips/util/MyWindowCallback.java
|
hallefy/MaterialChipsInput
|
c4360d79412344f1bd0743460e0a8f60f6953152
|
[
"Apache-2.0"
] | 443 |
2017-04-14T05:54:44.000Z
|
2022-03-23T06:03:00.000Z
| 31.298851 | 123 | 0.702901 | 1,002,609 |
package com.pchmn.materialchips.util;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SearchEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.pchmn.materialchips.views.ChipsInputEditText;
import com.pchmn.materialchips.views.DetailedChipView;
public class MyWindowCallback implements Window.Callback {
private Window.Callback mLocalCallback;
private Activity mActivity;
public MyWindowCallback(Window.Callback localCallback, Activity activity) {
mLocalCallback = localCallback;
mActivity = activity;
}
@Override
public boolean dispatchKeyEvent(KeyEvent keyEvent) {
return mLocalCallback.dispatchKeyEvent(keyEvent);
}
@Override
public boolean dispatchKeyShortcutEvent(KeyEvent keyEvent) {
return mLocalCallback.dispatchKeyShortcutEvent(keyEvent);
}
@Override
public boolean dispatchTouchEvent(MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
View v = mActivity.getCurrentFocus();
if(v instanceof DetailedChipView) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int) motionEvent.getRawX(), (int) motionEvent.getRawY())) {
((DetailedChipView) v).fadeOut();
}
}
if (v instanceof ChipsInputEditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int) motionEvent.getRawX(), (int) motionEvent.getRawY())
&& !((ChipsInputEditText) v).isFilterableListVisible()) {
InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return mLocalCallback.dispatchTouchEvent(motionEvent);
}
@Override
public boolean dispatchTrackballEvent(MotionEvent motionEvent) {
return mLocalCallback.dispatchTrackballEvent(motionEvent);
}
@Override
public boolean dispatchGenericMotionEvent(MotionEvent motionEvent) {
return mLocalCallback.dispatchGenericMotionEvent(motionEvent);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
return mLocalCallback.dispatchPopulateAccessibilityEvent(accessibilityEvent);
}
@Nullable
@Override
public View onCreatePanelView(int i) {
return mLocalCallback.onCreatePanelView(i);
}
@Override
public boolean onCreatePanelMenu(int i, Menu menu) {
return mLocalCallback.onCreatePanelMenu(i, menu);
}
@Override
public boolean onPreparePanel(int i, View view, Menu menu) {
return mLocalCallback.onPreparePanel(i, view, menu);
}
@Override
public boolean onMenuOpened(int i, Menu menu) {
return mLocalCallback.onMenuOpened(i, menu);
}
@Override
public boolean onMenuItemSelected(int i, MenuItem menuItem) {
return mLocalCallback.onMenuItemSelected(i, menuItem);
}
@Override
public void onWindowAttributesChanged(WindowManager.LayoutParams layoutParams) {
mLocalCallback.onWindowAttributesChanged(layoutParams);
}
@Override
public void onContentChanged() {
mLocalCallback.onContentChanged();
}
@Override
public void onWindowFocusChanged(boolean b) {
mLocalCallback.onWindowFocusChanged(b);
}
@Override
public void onAttachedToWindow() {
mLocalCallback.onAttachedToWindow();
}
@Override
public void onDetachedFromWindow() {
mLocalCallback.onDetachedFromWindow();
}
@Override
public void onPanelClosed(int i, Menu menu) {
mLocalCallback.onPanelClosed(i, menu);
}
@Override
public boolean onSearchRequested() {
return mLocalCallback.onSearchRequested();
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public boolean onSearchRequested(SearchEvent searchEvent) {
return mLocalCallback.onSearchRequested(searchEvent);
}
@Nullable
@Override
public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
return mLocalCallback.onWindowStartingActionMode(callback);
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Nullable
@Override
public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int i) {
return mLocalCallback.onWindowStartingActionMode(callback, i);
}
@Override
public void onActionModeStarted(ActionMode actionMode) {
mLocalCallback.onActionModeStarted(actionMode);
}
@Override
public void onActionModeFinished(ActionMode actionMode) {
mLocalCallback.onActionModeFinished(actionMode);
}
}
|
9243510e97afa296eedf4eac45be580b4b68d0a6
| 1,994 |
java
|
Java
|
src/test/java/name/valery1707/megatel/sorm/app/bro/BroConfigWriterTest.java
|
valery1707/test-sorm
|
fa1c72eaa9cae33bd1a55c71b58aa5c8ac99a5ac
|
[
"MIT"
] | null | null | null |
src/test/java/name/valery1707/megatel/sorm/app/bro/BroConfigWriterTest.java
|
valery1707/test-sorm
|
fa1c72eaa9cae33bd1a55c71b58aa5c8ac99a5ac
|
[
"MIT"
] | null | null | null |
src/test/java/name/valery1707/megatel/sorm/app/bro/BroConfigWriterTest.java
|
valery1707/test-sorm
|
fa1c72eaa9cae33bd1a55c71b58aa5c8ac99a5ac
|
[
"MIT"
] | null | null | null | 31.666667 | 105 | 0.750877 | 1,002,610 |
package name.valery1707.megatel.sorm.app.bro;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import javaslang.collection.List;
import org.apache.commons.io.output.StringBuilderWriter;
import org.junit.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BroConfigWriterTest {
@Test
public void testLoadIp_127() throws Exception {
assertThat(loadIp("127.0.0.1")).containsExactly("127.0.0.1");
}
@Test
public void testLoadIp_localhost() throws Exception {
assertThat(loadIp("localhost")).contains("127.0.0.1");
}
@Test
public void testLoadIp_ya_ru() throws Exception {
List<String> ipYaRu = loadIp("ya.ru");
assertThat(ipYaRu).contains("172.16.31.10");
assertThat(loadIp("ya.ru, ya.ru")).containsOnlyElementsOf(ipYaRu).hasSameSizeAs(ipYaRu);
}
@Test
public void testLoadIp_google_com() throws Exception {
List<String> ipGoogleCom = loadIp("google.com");
assertThat(ipGoogleCom).isNotEmpty();
}
@Test
public void testLoadIp_google_com_and_ya_ru() throws Exception {
List<String> ipYaRu = loadIp("ya.ru");
List<String> ipGoogleCom = loadIp("google.com");
List<String> ip = ipYaRu.appendAll(ipGoogleCom);
assertThat(loadIp("ya.ru, google.com")).containsOnlyElementsOf(ip);
}
private List<String> loadIp(String src) throws IOException {
StringBuilderWriter out = new StringBuilderWriter();
Template.Fragment frag = mock(Template.Fragment.class);
when(frag.execute()).thenReturn(src);
BroConfigWriter.loadIp(frag, out);
return List.of(out.toString().split(", "));
}
@Test
public void testMustacheLambda() throws Exception {
Mustache.Compiler compiler = Mustache.compiler();
Template template = compiler.compile("dst-ip == {{#loadIP}}127.0.0.1{{/loadIP}}");
assertThat(template.execute(BroConfigWriter.SIG_CONTEXT)).isEqualToIgnoringCase("dst-ip == 127.0.0.1");
}
}
|
92435154194087eefe67df9366c66a0ea2ae4aa8
| 18,420 |
java
|
Java
|
app/src/main/java/com/cathy/eth191114/presenter/MainPresenterImp.java
|
Catherinelhl/ETH191114
|
a843e5e0aa3b4a79ffc79d910b6fbe0017997439
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/cathy/eth191114/presenter/MainPresenterImp.java
|
Catherinelhl/ETH191114
|
a843e5e0aa3b4a79ffc79d910b6fbe0017997439
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/cathy/eth191114/presenter/MainPresenterImp.java
|
Catherinelhl/ETH191114
|
a843e5e0aa3b4a79ffc79d910b6fbe0017997439
|
[
"Apache-2.0"
] | null | null | null | 43.037383 | 152 | 0.548751 | 1,002,611 |
package com.cathy.eth191114.presenter;
import android.text.TextUtils;
import com.cathy.eth191114.constants.ETHParamConstants;
import com.cathy.eth191114.tool.LogTool;
import org.bouncycastle.util.encoders.Hex;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.RawTransactionManager;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.Transfer;
import org.web3j.utils.Convert;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.concurrent.Future;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import kotlin.Deprecated;
/**
* @author catherine.brainwilliam
* @since 2018/11/15
*/
public class MainPresenterImp implements MainContract.Presenter {
private String TAG = MainPresenterImp.class.getSimpleName();
private Web3j web3j;
private Credentials credentials;
private MainContract.View view;
private String transactionHash;//得到此次交易的hash
public MainPresenterImp(MainContract.View view) {
this.view = view;
}
@Override
public void createWallet() {
try {
ECKeyPair ecKeyPair = Keys.createEcKeyPair();
System.out.println("PrivateKey:" + ecKeyPair.getPrivateKey());
System.out.println("PublicKey:" + ecKeyPair.getPublicKey());
System.out.println("Address:" + Keys.getAddress(ecKeyPair));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过加载私钥来得到当前钱包的元数据
*/
@Override
public void loadWalletByPrivateKey(String privateKey) {
byte[] array = new BigInteger(privateKey).toByteArray();
if (array[0] == 0) {
byte[] tmp = new byte[array.length - 1];
System.arraycopy(array, 1, tmp, 0, tmp.length);
array = tmp;
}
String privateKeyConvert = Hex.toHexString(array);
credentials = Credentials.create(privateKeyConvert);
String address = credentials.getAddress();
LogTool.d(TAG, "address=" + address);
view.getAddressSuccess(address);
LogTool.d(TAG, " public key=" + credentials.getEcKeyPair().getPublicKey());
LogTool.d(TAG, " private key=" + credentials.getEcKeyPair().getPrivateKey());
}
/**
* 连接以太坊客户端
*/
@Override
public void connectETHClient() {
LogTool.d(TAG, "connectETHClient");
//连接方式:使用infura 提供的客户端
web3j = Web3j.build(new HttpService(ETHParamConstants.NetworkParameter));
Disposable subscribe = Observable.just(web3j.web3ClientVersion())
.map(new Function<Request<?, Web3ClientVersion>, String>() {
@Override
public String apply(Request<?, Web3ClientVersion> web3ClientVersionRequest) throws Exception {
return web3ClientVersionRequest.send().getWeb3ClientVersion();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>() {
@Override
public void accept(String web3ClientVersion) throws Exception {
//测试是否连接成功
view.success("version:" + web3ClientVersion);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
view.failure(throwable.getMessage());
}
});
}
/***********查询指定地址的余额***********/
/**
* 其中核心方法 web3j.ethGetBalance(address, defaultBlockParameter)
* 中的第二个参数比较特殊,指默认的区块参数。当请求余额的方法作用与以太坊的区块网络时,
* 这个参数决定了查询区块的高度。
* <p>
* <p>
* 一般情况下,选择“latest”即可。
* <p>
* 以太坊中,如果没有特殊标示,数字的单位都是小数点后18位,因此查询账户余额有必要将wei转化成ether。
* <p>
* HEX String - 一个整数块号
* String "earliest" 为最早/起源块
* String "latest" - 为最新的采矿块
* String "pending" - 待处理状态/交易
*
* @throws IOException
*/
@Override
public void getBalance(String address) {
if (web3j == null) return;
//第二个参数:区块的参数,建议选最新区块
Disposable subscribe = Observable.just(web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST))
.map(new Function<Request<?, EthGetBalance>, Future<EthGetBalance>>() {
@Override
public Future<EthGetBalance> apply(Request<?, EthGetBalance> ethGetBalanceRequest) throws Exception {
//这里可以有异步,也可以同步:send()
return ethGetBalanceRequest.sendAsync();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Future<EthGetBalance>>() {
@Override
public void accept(Future<EthGetBalance> ethGetBalanceFuture) throws Exception {
EthGetBalance ethGetBalance = ethGetBalanceFuture.get();
//格式转化 wei-ether
String balanceETH = Convert.fromWei(ethGetBalance.getBalance().toString(), Convert.Unit.ETHER).toPlainString().concat(" ether");
view.getBalanceSuccess(balanceETH);
LogTool.d(TAG, balanceETH);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
LogTool.e(TAG, throwable.getMessage());
view.getBalanceSFailure(throwable.getMessage());
}
});
}
@Override
public void getGasPrice() {
if (web3j == null) return;
Disposable subscribe = Observable.just(web3j.ethGasPrice()).map(new Function<Request<?, EthGasPrice>, Future<EthGasPrice>>() {
@Override
public Future<EthGasPrice> apply(Request<?, EthGasPrice> ethGasPriceRequest) throws Exception {
return ethGasPriceRequest.sendAsync();
}
}).subscribe(new Consumer<Future<EthGasPrice>>() {
@Override
public void accept(Future<EthGasPrice> ethGasPriceFuture) throws Exception {
BigInteger bigInteger = ethGasPriceFuture.get().getGasPrice();
view.gasPriceSuccess(bigInteger);
LogTool.d(TAG, "gasPrice:" + bigInteger);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
view.gasPriceFailure(throwable.getMessage());
}
});
}
@Override
public void getTXList(String address) {
if (web3j == null) return;
getTxListByEtherscan(address);
}
/**
* 通过Etherscan直接网络请求进行查询
* <p>
* module=account
* * &action=txlist
* * &address=0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121a
* * &startblock=0
* * &endblock=99999999
* * &sort=asc
* * &apikey=YourApiKeyToken
* <p>
* apikey 这里为null也行
*/
private void getTxListByEtherscan(String address) {
// //desc 从高到低
// //asc 从低到高
// interactor.getTXList("account", "txlist", address, "0",
// "99999999", "desc", Constants.APIKEY, new Callback<ETHTXListResponse>() {
// @Override
// public void onResponse(Call<ETHTXListResponse> call, Response<ETHTXListResponse> response) {
// if (response != null) {
// ETHTXListResponse ethtxListResponse = response.body();
// view.success(ethtxListResponse.toString());
// if (ethtxListResponse != null) {
// List<TXListBean> txListBeans = ethtxListResponse.getResult();
// if (txListBeans != null && txListBeans.size() > 0) {
// for (TXListBean txListBean : txListBeans) {
//// LogTool.d(TAG, response.body().getResult());
// LogTool.d(TAG, "Hash:" + txListBean.getHash() + ";status:" + txListBean.getConfirmations());
// }
// }
//
// }
// }
// }
//
// @Override
// public void onFailure(Call<ETHTXListResponse> call, Throwable t) {
// LogTool.e(TAG, t.getMessage());
//
// }
// });
}
@Deprecated(message = "unuse")
private void getTXListByWeb3j() {
Disposable subscribe = Observable.just(web3j.ethGetTransactionReceipt(transactionHash)).
map(new Function<Request<?, EthGetTransactionReceipt>, EthGetTransactionReceipt>() {
@Override
public EthGetTransactionReceipt apply(Request<?, EthGetTransactionReceipt> ethGetTransactionReceiptRequest) throws Exception {
return ethGetTransactionReceiptRequest.send();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<EthGetTransactionReceipt>() {
@Override
public void accept(EthGetTransactionReceipt ethGetTransactionReceipt) throws Exception {
LogTool.d(TAG, ethGetTransactionReceipt.getError());
LogTool.d(TAG, ethGetTransactionReceipt.getId());
LogTool.d(TAG, ethGetTransactionReceipt.getResult());
view.success(ethGetTransactionReceipt.getRawResponse());
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
view.failure(throwable.getMessage());
}
});
}
/****************交易*****************/
/**
* 作为一个钱包,除了保存账户资产外,最重要的就是转账或交易了,利用web3j可以便捷的实现eth的转移。
* 核心方法需要提供4个参数:
* <p>
* web3j实体
* Credentials 源账户所有信息
* address 转出地址
* value 数量
* unit 单位
* 等待片刻后,会返回转账结果
*
* @throws Exception
*/
@Override
public void publishTX(BigInteger gasPrice, String addressTo, String amountString, String privateKey) {
if (web3j == null) return;
if (credentials == null) {
loadWalletByPrivateKey(privateKey);
}
BigDecimal amount = new BigDecimal(amountString);
LogTool.d(TAG, "addressTo:" + addressTo);
LogTool.d(TAG, "amount:" + amount);
LogTool.d(TAG, "gasPrice:" + gasPrice);
LogTool.d(TAG, "privateKey:" + credentials.getEcKeyPair().getPrivateKey());
TransactionManager transactionManager = new RawTransactionManager(web3j, credentials);
Transfer transfer = new Transfer(web3j, transactionManager);
Disposable disposable = Observable.just(transfer.sendFunds(addressTo, amount, Convert.Unit.ETHER, gasPrice, BigInteger.valueOf(21000)))
.map(new Function<RemoteCall<TransactionReceipt>, TransactionReceipt>() {
@Override
public TransactionReceipt apply(RemoteCall<TransactionReceipt> transactionReceiptRemoteCall) throws Exception {
LogTool.d(TAG, "pushing");
return transactionReceiptRemoteCall.send();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<TransactionReceipt>() {
@Override
public void accept(TransactionReceipt send) throws Exception {
if (send == null) {
view.failure("failure send is null");
} else {
LogTool.d(TAG, "Transaction complete:");
LogTool.d(TAG, "trans hash=" + send.getTransactionHash());
LogTool.d(TAG, "block hash" + send.getBlockHash());
LogTool.d(TAG, "from :" + send.getFrom());
LogTool.d(TAG, "to:" + send.getTo());
LogTool.d(TAG, "gas used=" + send.getGasUsed());
LogTool.d(TAG, "status: " + send.getStatus());
transactionHash = send.getTransactionHash();
view.success(transactionHash);
view.getHashRaw(transactionHash);
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
view.failure(throwable.getMessage());
LogTool.e(TAG, throwable.getMessage());
}
});
}
@Override
public void checkTXInfo(String txHash) {
if (web3j == null) return;
if (TextUtils.isEmpty(txHash)) {
view.failure("transactionHash is empty!!");
return;
}
// Disposable subscribe = Observable.just(web3j.ethGetTransactionByHash(txHash))
// .map(new Function<Request<?, EthTransaction>, Future<EthTransaction>>() {
//
// @Override
// public Future<EthTransaction> apply(Request<?, EthTransaction> ethTransactionRequest) throws Exception {
// return ethTransactionRequest.sendAsync();
// }
// }).subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Consumer<Future<EthTransaction>>() {
// @Override
// public void accept(Future<EthTransaction> ethTransactionFuture) throws Exception {
// LogTool.d(TAG, "ethTransactionFuture:" + ethTransactionFuture);
// if (ethTransactionFuture == null) {
// return;
//
// }
// EthTransaction ethTransaction = ethTransactionFuture.get();
// LogTool.d(TAG, "ethTransaction:" + ethTransaction);
// if (ethTransaction == null) {
// return;
// }
// Transaction transaction = ethTransaction.getTransaction();
// LogTool.d(TAG, "transaction:" + transaction);
// if (transaction == null) {
// return;
// }
// LogTool.d(TAG, "getBlockNumber:" + transaction.getBlockNumber());
// LogTool.d(TAG, "getBlockHash:" + transaction.getBlockHash());
// LogTool.d(TAG, "getBlockNumberRaw:" + transaction.getBlockNumberRaw());
// LogTool.d(TAG, "getGasPriceRaw:" + transaction.getGasPriceRaw());
// LogTool.d(TAG, "getGasPrice:" + transaction.getGasPrice());
// LogTool.d(TAG, "getGasRaw:" + transaction.getGasRaw());
// LogTool.d(TAG, "getHash:" + transaction.getHash());
// LogTool.d(TAG, "getInput:" + transaction.getInput());
// LogTool.d(TAG, "getNonceRaw:" + transaction.getNonceRaw());
// LogTool.d(TAG, "getNonce:" + transaction.getNonce());
// LogTool.d(TAG, "getS:" + transaction.getS());
// LogTool.d(TAG, "getR:" + transaction.getR());
// LogTool.d(TAG, "getRaw:" + transaction.getRaw());
// LogTool.d(TAG, "getFrom:" + transaction.getFrom());
// LogTool.d(TAG, "getTo:" + transaction.getTo());
// LogTool.d(TAG, "getTransactionIndexRaw:" + transaction.getTransactionIndexRaw());
// LogTool.d(TAG, "getTransactionIndex:" + transaction.getTransactionIndex());
// LogTool.d(TAG, "getValue:" + transaction.getValue());
// LogTool.d(TAG, "getValueRaw:" + transaction.getValueRaw());
// LogTool.d(TAG, "getCreates:" + transaction.getCreates());
// if (transaction == null) {
// view.failure("transaction is empty!!");
// return;
// }
// view.success("getBlockNumber:" + transaction.getBlockNumber().toString());
// }
// }, new Consumer<Throwable>() {
// @Override
// public void accept(Throwable throwable) throws Exception {
// LogTool.e(TAG, throwable.getMessage());
// view.failure(throwable.getMessage());
// }
// });
}
@Override
public void cancelSubscribe() {
}
}
|
924351e0546f86aa47b00e280c9be230606a4ec4
| 1,790 |
java
|
Java
|
interoptester/src/main/java/org/apache/etch/interoptester/Token.java
|
apache/etch
|
5a875755019a7f342a07c8c368a50e3efb6ae68c
|
[
"ECL-2.0",
"Apache-2.0"
] | 9 |
2015-02-14T15:09:54.000Z
|
2021-11-10T15:09:45.000Z
|
interoptester/src/main/java/org/apache/etch/interoptester/Token.java
|
apache/etch
|
5a875755019a7f342a07c8c368a50e3efb6ae68c
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
interoptester/src/main/java/org/apache/etch/interoptester/Token.java
|
apache/etch
|
5a875755019a7f342a07c8c368a50e3efb6ae68c
|
[
"ECL-2.0",
"Apache-2.0"
] | 14 |
2015-04-20T10:35:00.000Z
|
2021-11-10T15:09:35.000Z
| 25.942029 | 72 | 0.705587 | 1,002,612 |
/* $Id$
*
* 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.etch.interoptester;
import java.util.Map;
import org.apache.etch.util.Assertion;
import org.apache.etch.util.core.xml.XmlParser.TagElement;
/**
* Token models an unnamed positional parameter to a program.
*/
public class Token
{
/**
* @param r
* @return the parsed Token.
*/
public static Token parse( TagElement r )
{
Assertion.check( r.matches( null, "token" ), "tag is token" );
String value = r.getAttr( null, "value" );
if (value == null && r.hasChildren())
value = r.getCdataValue();
return new Token( value );
}
private Token( String value )
{
this.value = value;
}
private final String value;
/**
* @param args named values which might be used as substitutions.
* @return the value of this arg. This might involve substituting named
* values from args.
*/
public String value( Map<String, String> args )
{
if (value == null)
return null;
return Substitutor.subst( value, args );
}
}
|
924353719a2bb8d283d7315e2343e80f5633d0b7
| 791 |
java
|
Java
|
app/src/main/java/com/gary/garytool/business/volley/VolleyManger.java
|
guogu82/garytool
|
4785f732114ea422b4ee63c988b7f473a9ed42e7
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/gary/garytool/business/volley/VolleyManger.java
|
guogu82/garytool
|
4785f732114ea422b4ee63c988b7f473a9ed42e7
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/gary/garytool/business/volley/VolleyManger.java
|
guogu82/garytool
|
4785f732114ea422b4ee63c988b7f473a9ed42e7
|
[
"Apache-2.0"
] | null | null | null | 21.378378 | 65 | 0.632111 | 1,002,613 |
package com.gary.garytool.business.volley;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
/**
* 本类用于封装Volley的操作。以适应未来更换http通信模块
* Created by Administrator on 2015/10/15.
*/
public class VolleyManger {
public static void initRequestQueue(Context context)
{
//理论不用双重判断锁。因为只是在app启动的时候才执行一次。
if(mRequestQueue==null)
{
synchronized (VolleyManger.class) {
if(mRequestQueue==null)
mRequestQueue = Volley.newRequestQueue(context);
}
}
}
private static RequestQueue mRequestQueue;
public static RequestQueue getVolleyRequestQueue()
{
return mRequestQueue;
}
}
|
92435376d3e894d0d53e81b41ddc4496da67db2c
| 1,472 |
java
|
Java
|
src/main/java/dev/galacticraft/api/teams/TeamsSync.java
|
glowiak/GalacticraftAPI
|
769afbafcc833ea59e43acef36cf255e2a09e438
|
[
"MIT"
] | 8 |
2021-04-15T07:13:57.000Z
|
2022-02-28T06:56:46.000Z
|
src/main/java/dev/galacticraft/api/teams/TeamsSync.java
|
glowiak/GalacticraftAPI
|
769afbafcc833ea59e43acef36cf255e2a09e438
|
[
"MIT"
] | 11 |
2020-01-11T22:51:00.000Z
|
2021-04-14T03:00:56.000Z
|
src/main/java/dev/galacticraft/api/teams/TeamsSync.java
|
glowiak/GalacticraftAPI
|
769afbafcc833ea59e43acef36cf255e2a09e438
|
[
"MIT"
] | 6 |
2020-05-04T21:13:57.000Z
|
2021-03-16T19:15:41.000Z
| 36.8 | 81 | 0.747962 | 1,002,614 |
/*
* Copyright (c) 2019-2021 Team Galacticraft
*
* 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 dev.galacticraft.api.teams;
import net.minecraft.world.PersistentState;
public class TeamsSync implements Runnable {
private final PersistentState compound;
public TeamsSync(PersistentState compound) {
this.compound = compound;
}
@Override
public void run() {
this.compound.markDirty();
}
}
|
924353c153b36e3d5dbaaf1a934283bd06b2e967
| 2,711 |
java
|
Java
|
src/test/java/eu/sanjin/kurelic/paintingsgarage/hashtag/service/HashtagServiceUnitTest.java
|
SanjinKurelic/PaintingsGarage
|
73771239b0f426163c8adbf5d4cce92a443abd6e
|
[
"MIT"
] | null | null | null |
src/test/java/eu/sanjin/kurelic/paintingsgarage/hashtag/service/HashtagServiceUnitTest.java
|
SanjinKurelic/PaintingsGarage
|
73771239b0f426163c8adbf5d4cce92a443abd6e
|
[
"MIT"
] | 6 |
2022-03-26T11:20:21.000Z
|
2022-03-26T14:03:59.000Z
|
src/test/java/eu/sanjin/kurelic/paintingsgarage/hashtag/service/HashtagServiceUnitTest.java
|
SanjinKurelic/PaintingsGarage
|
73771239b0f426163c8adbf5d4cce92a443abd6e
|
[
"MIT"
] | null | null | null | 29.791209 | 110 | 0.74917 | 1,002,615 |
package eu.sanjin.kurelic.paintingsgarage.hashtag.service;
import eu.sanjin.kurelic.paintingsgarage.hashtag.entity.Hashtag;
import eu.sanjin.kurelic.paintingsgarage.hashtag.mapper.HashtagMapper;
import eu.sanjin.kurelic.paintingsgarage.hashtag.repository.HashtagRepository;
import eu.sanjin.kurelic.paintingsgarage.search.model.SearchResult;
import eu.sanjin.kurelic.paintingsgarage.testutil.type.UnitTest;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@UnitTest
class HashtagServiceUnitTest {
@Mock
private HashtagRepository hashtagRepository;
@Mock
private HashtagMapper hashtagMapper;
@InjectMocks
private HashtagService hashtagService;
@Test
void shouldFindHashtag() {
// Given
var name = "test";
when(hashtagRepository.findByNameStartingWith(name)).thenReturn(List.of(mock(Hashtag.class)));
when(hashtagMapper.mapHashtagListToSearchResultList(any())).thenReturn(List.of(mock(SearchResult.class)));
// When
var result = hashtagService.findHashtag(name);
// Then
assertThat(result).hasSize(1);
verify(hashtagRepository, times(1)).findByNameStartingWith(name);
verify(hashtagMapper, times(1)).mapHashtagListToSearchResultList(any());
}
@Test
void shouldReturnEmptyListWhenFindHashtag() {
// Given
var name = "t";
// When
var result = hashtagService.findHashtag(name);
// Then
assertThat(result).isEmpty();
}
@Test
void shouldGetOrCreate() {
// Given
var hashtagNames = List.of("test", "abc");
var hashtag = Hashtag.builder().name(hashtagNames.get(1)).build();
when(hashtagRepository.getByName(hashtagNames.get(0))).thenReturn(Optional.of(mock(Hashtag.class)));
when(hashtagRepository.getByName(hashtagNames.get(1))).thenReturn(Optional.empty());
when(hashtagRepository.saveAndFlush(any())).thenReturn(hashtag);
// When
var result = hashtagService.getOrCreate(hashtagNames);
// Then
assertThat(result).hasSize(2);
verify(hashtagRepository, times(1)).getByName(hashtagNames.get(0));
verify(hashtagRepository, times(1)).getByName(hashtagNames.get(1));
verify(hashtagRepository, times(1)).saveAndFlush(any());
}
@Test
void shouldReturnEmptyListWhenGetOrCreate() {
// When
var result = hashtagService.getOrCreate(null);
// Then
assertThat(result).isEmpty();
}
}
|
924354627125a2c73bdab13399ea97855b088d70
| 1,608 |
java
|
Java
|
ninja-core/src/main/java/ninja/diagnostics/SourceSnippet.java
|
thibaultmeyer/ninja
|
e5f1945f5861850196f88423020e82f7e43224f9
|
[
"Apache-2.0"
] | 1,614 |
2015-01-02T03:51:57.000Z
|
2022-03-13T08:45:42.000Z
|
ninja-core/src/main/java/ninja/diagnostics/SourceSnippet.java
|
thibaultmeyer/ninja
|
e5f1945f5861850196f88423020e82f7e43224f9
|
[
"Apache-2.0"
] | 429 |
2015-01-03T20:04:08.000Z
|
2022-02-24T16:44:22.000Z
|
ninja-core/src/main/java/ninja/diagnostics/SourceSnippet.java
|
zoza/ninja
|
585900d434ad0f5fa727c0edcd3e96308a0cc4bf
|
[
"Apache-2.0"
] | 541 |
2015-01-03T13:42:34.000Z
|
2022-03-01T05:06:36.000Z
| 27.254237 | 104 | 0.690299 | 1,002,616 |
/**
* Copyright (C) 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 ninja.diagnostics;
import java.net.URI;
import java.util.List;
/**
* Represents a snippet of a source file (1 or more lines).
*
* @author Joe Lauer (https://twitter.com/jjlauer)
* @author Fizzed, Inc. (http://fizzed.com)
*/
public class SourceSnippet {
private final URI sourceLocation;
private final List<String> lines;
private final int lineNumberFrom;
private final int lineNumberTo;
public SourceSnippet(URI sourceLocation, List<String> lines, int lineNumberFrom, int lineNumberTo) {
this.sourceLocation = sourceLocation;
this.lines = lines;
this.lineNumberFrom = lineNumberFrom;
this.lineNumberTo = lineNumberTo;
}
public URI getSourceLocation() {
return sourceLocation;
}
public List<String> getLines() {
return lines;
}
public int getLineNumberFrom() {
return lineNumberFrom;
}
public int getLineNumberTo() {
return lineNumberTo;
}
}
|
9243547bebe320ff0512b839d86aa82d485533e9
| 3,834 |
java
|
Java
|
src/main/java/com/microsoft/azure/datalake/store/retrypolicies/ExponentialBackoffPolicy.java
|
imiller31/azure-data-lake-store-java
|
f5c270b8cb2ac68536b2cb123d355a874cade34c
|
[
"MIT"
] | 25 |
2016-11-22T19:19:34.000Z
|
2022-01-10T20:12:01.000Z
|
src/main/java/com/microsoft/azure/datalake/store/retrypolicies/ExponentialBackoffPolicy.java
|
ezras-microsoft/azure-data-lake-store-java
|
3cc94f34fdd2156a78d54b129820973129f42723
|
[
"MIT"
] | 31 |
2016-12-22T22:33:47.000Z
|
2021-12-14T23:19:56.000Z
|
src/main/java/com/microsoft/azure/datalake/store/retrypolicies/ExponentialBackoffPolicy.java
|
ezras-microsoft/azure-data-lake-store-java
|
3cc94f34fdd2156a78d54b129820973129f42723
|
[
"MIT"
] | 37 |
2017-01-06T19:34:11.000Z
|
2022-01-24T21:40:58.000Z
| 39.122449 | 143 | 0.603286 | 1,002,617 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
* See License.txt in the project root for license information.
*/
package com.microsoft.azure.datalake.store.retrypolicies;
/**
* implements different retry decisions based on the error.
*
* <UL>
* <LI>For nonretryable errors (3xx, most 4xx, and some 5xx return codes), do no retry.</LI>
* <LI>For throttling error, do a retry with exponential backoff</LI>
* <LI>for all other errors, do a retry with linear backoff</LI>
* </UL>
*/
public class ExponentialBackoffPolicy implements RetryPolicy {
private int retryCount = 0;
private int maxRetries = 4;
private int exponentialRetryInterval = 1000;
private int exponentialFactor = 4;
private long lastAttemptStartTime = System.nanoTime();
public ExponentialBackoffPolicy() {
}
/**
* @param maxRetries maximum number of retries
* @param linearRetryInterval interval to use for linear retries (in milliseconds).
* Deprecated, not used in the retry policy.
* @param exponentialRetryInterval (starting) interval to use for exponential backoff retries (in milliseconds)
*/
public ExponentialBackoffPolicy(int maxRetries, @Deprecated int linearRetryInterval, int exponentialRetryInterval) {
this.maxRetries = maxRetries;
this.exponentialRetryInterval = exponentialRetryInterval;
}
public ExponentialBackoffPolicy(int maxRetries, @Deprecated int linearRetryInterval, int exponentialRetryInterval, int exponentialFactor) {
this.maxRetries = maxRetries;
this.exponentialRetryInterval = exponentialRetryInterval;
this.exponentialFactor = exponentialFactor;
}
public boolean shouldRetry(int httpResponseCode, Exception lastException) {
// Non-retryable error
if ( (httpResponseCode >= 300 && httpResponseCode < 500 // 3xx and 4xx, except specific ones below
&& httpResponseCode != 408
&& httpResponseCode != 429
&& httpResponseCode != 401)
|| (httpResponseCode == 501) // Not Implemented
|| (httpResponseCode == 505) // Version Not Supported
) {
return false;
}
// Retryable error, retry with exponential backoff
if ( lastException!=null || httpResponseCode >=500 // exception or 5xx, + specific ones below
|| httpResponseCode == 408
|| httpResponseCode == 429
|| httpResponseCode == 401) {
if (retryCount < maxRetries) {
int timeSpent = (int)((System.nanoTime() - lastAttemptStartTime) / 1000000);
wait(exponentialRetryInterval - timeSpent);
exponentialRetryInterval *= exponentialFactor;
retryCount++;
lastAttemptStartTime = System.nanoTime();
return true;
} else {
return false; // max # of retries exhausted
}
}
// these are not errors - this method should never have been called with this
if (httpResponseCode >= 100 && httpResponseCode <300)
{
return false;
}
// Dont know what happened - we should never get here
return false;
}
private void wait(int milliseconds) {
if (milliseconds <= 0) {
return;
}
try {
Thread.sleep(milliseconds);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt(); // http://www.ibm.com/developerworks/library/j-jtp05236/
}
}
}
|
924354a41cf7c18ce2ca59c7e965f7c3c4b61755
| 3,367 |
java
|
Java
|
app/src/main/java/com/epicodus/pocketpomodoro/game/models/Bubble.java
|
Rosanio/Pocket-Pomodoro
|
daf39af9a60a1f95a9c0745062642b9454a28965
|
[
"Unlicense",
"MIT"
] | 1 |
2016-07-13T15:05:30.000Z
|
2016-07-13T15:05:30.000Z
|
app/src/main/java/com/epicodus/pocketpomodoro/game/models/Bubble.java
|
Rosanio/Pocket-Pomodoro
|
daf39af9a60a1f95a9c0745062642b9454a28965
|
[
"Unlicense",
"MIT"
] | null | null | null |
app/src/main/java/com/epicodus/pocketpomodoro/game/models/Bubble.java
|
Rosanio/Pocket-Pomodoro
|
daf39af9a60a1f95a9c0745062642b9454a28965
|
[
"Unlicense",
"MIT"
] | null | null | null | 24.576642 | 96 | 0.564301 | 1,002,618 |
package com.epicodus.pocketpomodoro.game.models;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.RectF;
import com.epicodus.pocketpomodoro.R;
public class Bubble {
private float x, y, screenX, screenY, width, height, startX, startY;
private RectF rect;
Bitmap bitmap;
public boolean isVisible;
Context context;
private int frameCount, currentFrame, frameLength;
private long lastFrameChangeTime;
private Rect frameToDraw;
private RectF hitbox;
public Bubble(float screenX, float screenY, Context context){
this.screenX = screenX;
this.screenY = screenY;
x = screenX;
y = screenY/2;
width = screenX/18;
height = screenY/12;
rect = new RectF();
this.context = context;
hitbox = new RectF();
frameCount = 2;
currentFrame = 0;
lastFrameChangeTime = 0;
frameLength = 1000;
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.bubble);
bitmap = Bitmap.createScaledBitmap(bitmap, (int) width*frameCount, (int) height, false);
frameToDraw = new Rect(0, 0, (int) width, (int) height);
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public float getWidth() {
return width;
}
public float getHeight() {
return height;
}
public Rect getFrameToDraw() {
return frameToDraw;
}
public boolean isVisible() {
return isVisible;
}
public RectF getHitbox() { return hitbox; }
public void setVisible(boolean visible) {
isVisible = visible;
}
public RectF getRect() {
return rect;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setRect(RectF rect) {
this.rect = rect;
}
public void setHitbox(RectF hitbox) {
this.hitbox = hitbox;
}
public void generate(float startY) {
this.startY = startY;
this.startX = screenX;
x = startX;
y = startY;
isVisible = true;
if (y < screenY/5) {
y = screenY/5;
}
if (y + height > screenY) {
y = screenY - height;
}
}
public void update(float scrollSpeed, float fps){
if (fps>0) {
x = x-scrollSpeed/fps;
rect.top = y;
rect.bottom = y+height;
rect.left = x;
rect.right = x+width;
hitbox.top = y + height/5;
hitbox.bottom = y + height - height/5;
hitbox.left = x + width/5;
hitbox.right = x + width-width/5;
if(rect.right < 0) {
isVisible = false;
}
}
}
public void getCurrentFrame() {
long time = System.currentTimeMillis();
if (time > lastFrameChangeTime + frameLength) {
lastFrameChangeTime = time;
currentFrame++;
if (currentFrame > frameCount-1) {
currentFrame = 0;
}
}
frameToDraw.left = currentFrame * (int) width;
frameToDraw.right = frameToDraw.left + (int) width;
}
}
|
924354b5209db450db3643d1dee8b4074112e3a8
| 5,090 |
java
|
Java
|
src/service/Utils.java
|
ikiranis/tzokerApp
|
f24ccf6f810f76f14fbf7ea0dfa0f0500b658ff3
|
[
"MIT"
] | null | null | null |
src/service/Utils.java
|
ikiranis/tzokerApp
|
f24ccf6f810f76f14fbf7ea0dfa0f0500b658ff3
|
[
"MIT"
] | null | null | null |
src/service/Utils.java
|
ikiranis/tzokerApp
|
f24ccf6f810f76f14fbf7ea0dfa0f0500b658ff3
|
[
"MIT"
] | null | null | null | 31.614907 | 98 | 0.557957 | 1,002,619 |
package service;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import model.Prize;
import model.WinNumber;
public class Utils {
// Επιστρέφει Formatter
public static SimpleDateFormat getFormatter() {
return new SimpleDateFormat("yyyy-MM-dd");
}
// Μετράει πόσες φορές έχει εμφανιστεί ένας αριθμός
public static int countOccurrences(List<WinNumber> numbersInDB, String number, char type) {
int counter = 0;
// Έλεγχος για κάθε αριθμό number, με τύπο type
for (WinNumber item : numbersInDB) {
if (number.equals(item.getNumber()) && item.getType() == type) {
counter++;
}
}
return counter;
}
// Επιστρέφει τις μεγαλύτερες entries τιμές από την λίστα items
public static Map sortNumbersByKey(Map<Integer, Long> items, int entries) {
Map<Integer, Long> sortedNumbers = new HashMap<>();
// Εκτελεί την διαδικασία για entries φορές
for (int i = 1; i <= entries; i++) {
long maxValue = 0;
int maxKey = 0;
// Βρίσκει την μεγαλύτερη από τις τιμές
for (Map.Entry<Integer, Long> item : items.entrySet()) {
if (item.getValue() > maxValue) {
maxValue = item.getValue();
maxKey = item.getKey();
}
}
// Σβήνει την μεγαλύτερη εγγραφή από την παλιά λίστα και την
// προσθέτει στην καινούργια
items.remove(maxKey);
sortedNumbers.put(maxKey, maxValue);
}
return sortedNumbers;
}
// Επιστρέφει την τελευταία κλήρωση που εμφανίστηκε ο αριθμός
public static int getLastDrawOfNumber(List<WinNumber> numbersInDB, String number, char type) {
int lastDraw = 0;
// Έλεγχος για κάθε αριθμό number, με τύπο type
for (WinNumber item : numbersInDB) {
if (number.equals(item.getNumber()) && item.getType() == type) {
lastDraw = item.getDrawId().getId();
}
}
return lastDraw;
}
// Επιστρέφει τον μέσο όρο κερδών για την κατηγορία κερδών categoryNumber
public static long getAvgPrize(List<Prize> categoriesInDB, int categoryNumber) {
long sum = 0;
int counter = 0;
// Έλεγχος σε κάθε κατηγορία κερδών για το categoryNumber
// Αν είναι η σωστή κατηγορία προσθέτει τα κέρδη
for (Prize category : categoriesInDB) {
if (category.getCategoryNumber() == categoryNumber) {
sum += category.getDivident();
counter++;
}
}
return (long) sum / counter;
}
// Επιστρέφει τα ονόματα των κατηγοριών
public static Map<Integer, String> getCategoryNames() {
Map<Integer, String> names = new HashMap<>();
names.put(1, "5+1");
names.put(2, "5");
names.put(3, "4+1");
names.put(4, "4");
names.put(5, "3+1");
names.put(6, "3");
names.put(7, "2+1");
names.put(8, "1+1");
return names;
}
// Επιστρέφει σε string την σημερινή ημερομηνία
public static String getTodayDate() {
return getFormatter().format(new Date());
}
// Επιστρέφει σε string την ημερομηνία από 3 μήνες πριν
public static String getThreeMonthsAgoDate() {
return getFormatter().format(Date
.from(LocalDate.parse(getTodayDate())
.minusMonths(3).atStartOfDay()
.toInstant(ZoneOffset.UTC)));
}
// Μετατροπή του ονόματος μήνα σε string
public static int getMonthNameToMonthNumber(String month) {
HashMap<String, String> map = new HashMap();
map.put("Ιανουάριος", "1");
map.put("Φεβρουάριος", "2");
map.put("Μάρτιος", "3");
map.put("Απρίλιος", "4");
map.put("Μάιος", "5");
map.put("Ιούνιος", "6");
map.put("Ιούλιος", "7");
map.put("Αύγουστος", "8");
map.put("Σεπτέμβριος", "9");
map.put("Οκτώβριος", "10");
map.put("Νοέμβριος", "11");
map.put("Δεκέμβριος", "12");
return Integer.parseInt(map.get(month));
}
// Μετατροπή του αριθμού μήνα σε string
public static String getMonthNumberToMonthName(String month) {
HashMap<String, String> map = new HashMap();
map.put("1", "Ιανουάριος");
map.put("2", "Φεβρουάριος");
map.put("3", "Μάρτιος");
map.put("4", "Απρίλιος");
map.put("5", "Μάιος");
map.put("6", "Ιούνιος");
map.put("7", "Ιούλιος");
map.put("8", "Αύγουστος");
map.put("9", "Σεπτέμβριος");
map.put("10", "Οκτώβριος");
map.put("11", "Νοέμβριος");
map.put("12", "Δεκέμβριος");
return map.get(month);
}
}
|
9243557ae4fa866ac651c7156c461605acca03be
| 1,883 |
java
|
Java
|
independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoQualifiersTest.java
|
sgregoire/quarkus
|
5d77d270c81160f4ea88043efcae87e7c725d916
|
[
"Apache-2.0"
] | 10,225 |
2019-03-07T11:55:54.000Z
|
2022-03-31T21:16:53.000Z
|
independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoQualifiersTest.java
|
sgregoire/quarkus
|
5d77d270c81160f4ea88043efcae87e7c725d916
|
[
"Apache-2.0"
] | 18,675 |
2019-03-07T11:56:33.000Z
|
2022-03-31T22:25:22.000Z
|
independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoQualifiersTest.java
|
jamesnetherton/quarkus
|
e86f7c5392bd14f2a1afdff215aa00025ebe1859
|
[
"Apache-2.0"
] | 2,190 |
2019-03-07T12:07:18.000Z
|
2022-03-30T05:41:35.000Z
| 36.921569 | 123 | 0.731811 | 1,002,620 |
package io.quarkus.arc.processor;
import static io.quarkus.arc.processor.Basics.index;
import static io.quarkus.arc.processor.Basics.name;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.quarkus.arc.processor.types.Bar;
import io.quarkus.arc.processor.types.Foo;
import io.quarkus.arc.processor.types.FooQualifier;
import java.io.IOException;
import java.util.AbstractCollection;
import java.util.AbstractList;
import java.util.Collection;
import java.util.List;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget.Kind;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.junit.jupiter.api.Test;
/**
*
* @author Martin Kouba
*/
public class BeanInfoQualifiersTest {
@Test
public void testQualifiers() throws IOException {
Index index = index(Foo.class, Bar.class, FooQualifier.class, AbstractList.class, AbstractCollection.class,
List.class, Collection.class, Object.class, String.class, Iterable.class);
DotName fooName = name(Foo.class);
DotName fooQualifierName = name(FooQualifier.class);
ClassInfo fooClass = index.getClassByName(fooName);
BeanInfo bean = Beans.createClassBean(fooClass,
BeanProcessor.builder().setBeanArchiveIndex(index).build().getBeanDeployment(),
null);
AnnotationInstance requiredFooQualifier = index.getAnnotations(fooQualifierName).stream()
.filter(a -> Kind.FIELD.equals(a.target().kind()) && a.target().asField().name().equals("foo")).findFirst()
.orElse(null);
assertNotNull(requiredFooQualifier);
// FooQualifier#alpha() is @Nonbinding
assertTrue(Beans.hasQualifier(bean, requiredFooQualifier));
}
}
|
9243558b40e56514414b6617009ee1eb1ae1c8c8
| 723 |
java
|
Java
|
src/main/java/fr/insee/rmes/bauhaus_services/CodeListService.java
|
MichaelC67/Bauhaus-Back-Office
|
0b59429231ff63ee846e62df24679aca71c54adf
|
[
"MIT"
] | 3 |
2020-04-21T07:45:20.000Z
|
2022-02-11T12:37:36.000Z
|
src/main/java/fr/insee/rmes/bauhaus_services/CodeListService.java
|
MichaelC67/Bauhaus-Back-Office
|
0b59429231ff63ee846e62df24679aca71c54adf
|
[
"MIT"
] | 8 |
2019-02-12T09:33:20.000Z
|
2022-02-09T09:49:30.000Z
|
src/main/java/fr/insee/rmes/bauhaus_services/CodeListService.java
|
MichaelC67/Bauhaus-Back-Office
|
0b59429231ff63ee846e62df24679aca71c54adf
|
[
"MIT"
] | 15 |
2018-03-29T07:54:32.000Z
|
2021-10-01T12:04:26.000Z
| 27.807692 | 86 | 0.824343 | 1,002,621 |
package fr.insee.rmes.bauhaus_services;
import fr.insee.rmes.exceptions.RmesException;
public interface CodeListService {
String getCodeListJson(String codeListUri) throws RmesException;
String getCode(String notation, String id) throws RmesException;
String getCodeUri(String notationCodeList, String notationCode) throws RmesException;
String getAllCodesLists() throws RmesException;
String geCodesListByIRI(String iri) throws RmesException;
String getDetailedCodesList(String notation) throws RmesException;
String getDetailedCodesListForSearch() throws RmesException;
String setCodesList(String body) throws RmesException;
String setCodesList(String id, String body) throws RmesException;
}
|
924355f3bd3e071c28d0ac5eff19219ba6ff5809
| 3,075 |
java
|
Java
|
arquillian/arquillian-tomee-tests/arquillian-tomee-jms-tests/src/test/java/org/apache/openejb/arquillian/tests/jms/MessageBean.java
|
tingung/tomee
|
c4d120e8cacf11fa39a2d5226abe7a460b47b46f
|
[
"Apache-2.0"
] | 378 |
2015-01-14T09:51:24.000Z
|
2022-03-26T05:26:01.000Z
|
arquillian/arquillian-tomee-tests/arquillian-tomee-jms-tests/src/test/java/org/apache/openejb/arquillian/tests/jms/MessageBean.java
|
tingung/tomee
|
c4d120e8cacf11fa39a2d5226abe7a460b47b46f
|
[
"Apache-2.0"
] | 393 |
2015-11-16T08:44:15.000Z
|
2022-03-31T07:05:40.000Z
|
arquillian/arquillian-tomee-tests/arquillian-tomee-jms-tests/src/test/java/org/apache/openejb/arquillian/tests/jms/MessageBean.java
|
tingung/tomee
|
c4d120e8cacf11fa39a2d5226abe7a460b47b46f
|
[
"Apache-2.0"
] | 767 |
2015-01-02T19:38:49.000Z
|
2022-03-28T16:59:10.000Z
| 28.472222 | 144 | 0.667642 | 1,002,622 |
/*
* 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.openejb.arquillian.tests.jms;
import javax.annotation.Resource;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.inject.Inject;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import java.lang.IllegalStateException;
import java.util.List;
@Singleton
@Lock(LockType.READ)
public class MessageBean {
@Resource
private ConnectionFactory cf;
@Resource(name = "red")
private Topic red;
@Resource(name = "blue")
private Topic blue;
@Resource(name = "nocolor")
private Topic noColor;
@Inject
private Color color;
public void callRed() {
try {
process(cf, red, "red", Session.SESSION_TRANSACTED);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public void callBlue() {
try {
process(cf, blue, "blue", Session.SESSION_TRANSACTED);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public void callNoColor() {
try {
process(cf, noColor, "nocolor", Session.SESSION_TRANSACTED);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public void clear() {
color.clear();
}
public List<String> getColors() {
return color.getColors();
}
protected void process(final ConnectionFactory cf, final Topic topic, final String payload, final int acknowledgeMode) throws JMSException {
Connection connection = null;
Session session = null;
try {
connection = cf.createConnection();
connection.start();
session = connection.createSession(false, acknowledgeMode);
final MessageProducer producer = session.createProducer(null);
final TextMessage textMessage = session.createTextMessage(payload);
producer.send(topic, textMessage);
} finally {
if (session != null) session.close();
if (connection != null) connection.close();
}
}
}
|
92435677ff8834def13003ef54ed7e109deea965
| 1,595 |
java
|
Java
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/vision/pipelines/BarcodeCVPipeline.java
|
Scarsdale-Robotics/2021-2022-Freight-Frenzy
|
dc979d7b3d13f06cca3f628fa018ce8e8324b31b
|
[
"MIT"
] | null | null | null |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/vision/pipelines/BarcodeCVPipeline.java
|
Scarsdale-Robotics/2021-2022-Freight-Frenzy
|
dc979d7b3d13f06cca3f628fa018ce8e8324b31b
|
[
"MIT"
] | null | null | null |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/vision/pipelines/BarcodeCVPipeline.java
|
Scarsdale-Robotics/2021-2022-Freight-Frenzy
|
dc979d7b3d13f06cca3f628fa018ce8e8324b31b
|
[
"MIT"
] | null | null | null | 27.982456 | 103 | 0.658307 | 1,002,623 |
package org.firstinspires.ftc.teamcode.vision.pipelines;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.openftc.easyopencv.OpenCvPipeline;
import java.util.ArrayList;
import java.util.List;
public class BarcodeCVPipeline extends OpenCvPipeline {
public int itemX = -1;
public int itemY = -1;
final Scalar lower_green = new Scalar(30, 175, 75);
final Scalar upper_green = new Scalar(100, 255, 200);
final Scalar rectangle_color = new Scalar(0, 255, 0);
Mat mask = new Mat();
Mat trashMat = new Mat();
Rect rect = new Rect();
@Override
public Mat processFrame(Mat frame) {
Imgproc.cvtColor(frame, mask, Imgproc.COLOR_BGR2HSV);
Core.inRange(mask, lower_green, upper_green, mask);
List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(mask, contours, trashMat, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
Imgproc.cvtColor(mask, mask, Imgproc.COLOR_GRAY2BGR);
int size = 0;
for (MatOfPoint c : contours) {
Rect currentRect = Imgproc.boundingRect(c);
if (currentRect.width * currentRect.height > size) {
rect = currentRect;
size = currentRect.height * currentRect.width;
}
}
Imgproc.rectangle(mask, rect, rectangle_color);
itemX = rect.x + rect.width / 2;
itemY = rect.y + rect.height / 2;
return mask;
}
}
|
92435796bc7afd48bd9a24036742bd2f99b8d701
| 3,032 |
java
|
Java
|
src/main/java/net/dengzixu/packet/PacketResolve.java
|
Dengzixu/Bilibili-live-danmaku
|
c307aa6703a042afe32b34b0d12bd151de2182f5
|
[
"WTFPL"
] | 1 |
2022-03-09T10:33:17.000Z
|
2022-03-09T10:33:17.000Z
|
src/main/java/net/dengzixu/packet/PacketResolve.java
|
Dengzixu/Bilibili-live-danmaku
|
c307aa6703a042afe32b34b0d12bd151de2182f5
|
[
"WTFPL"
] | null | null | null |
src/main/java/net/dengzixu/packet/PacketResolve.java
|
Dengzixu/Bilibili-live-danmaku
|
c307aa6703a042afe32b34b0d12bd151de2182f5
|
[
"WTFPL"
] | null | null | null | 34.850575 | 129 | 0.60653 | 1,002,624 |
package net.dengzixu.packet;
import net.dengzixu.constant.PacketProtocolVersionEnum;
import net.dengzixu.exception.UnknownProtocolVersionException;
import net.dengzixu.utils.UncompressUtils;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class PacketResolve {
private final byte[] rawData;
private final int rawDataLength;
private int currentOffset;
private List<Packet> resultPacketList = new ArrayList<>();
public PacketResolve(byte[] rawData) {
Objects.requireNonNull(rawData);
this.rawData = rawData;
this.rawDataLength = rawData.length;
}
public List<Packet> getPacketList() {
// 根据传入的数据分配空间
final ByteBuffer byteBuffer = ByteBuffer.allocate(rawDataLength);
// 数据装入
byteBuffer.put(rawData);
// 需要判断一下数据包里是不是只有一条数据
while (currentOffset < rawDataLength) {
if (rawDataLength - currentOffset < 16) {
break;
}
Packet resolvedPacket = new Packet() {{
setPacketLength(byteBuffer.getInt(currentOffset));
setHeaderLength(byteBuffer.getShort(currentOffset + 4));
setProtocolVersion(byteBuffer.getShort(currentOffset + 6));
setOperation(byteBuffer.getInt(currentOffset + 8));
setSequenceId(byteBuffer.getInt(currentOffset + 12));
byte[] bodyBytes = new byte[getPacketLength() - 16];
for (int i = 0; i < bodyBytes.length; i++) {
bodyBytes[i] = byteBuffer.get(currentOffset + 16 + i);
}
setPayload(bodyBytes);
}};
resultPacketList.add(resolvedPacket);
currentOffset += resolvedPacket.getPacketLength();
}
// TODO 猜测 如果大于 1 个数据包 数据包就不再可能是压缩的
if (resultPacketList.size() > 1) {
return resultPacketList;
}
// 根据 Protocol Version 进行处理
switch (PacketProtocolVersionEnum.getEnum(resultPacketList.get(0).getProtocolVersion())) {
// 如果协议版本为 0 或 1 直接返回
case PROTOCOL_VERSION_0:
case PROTOCOL_VERSION_1:
break;
// 如果协议版本为 2 就解压一下
case PROTOCOL_VERSION_2: {
byte[] compressedData = UncompressUtils.uncompress(resultPacketList.get(0).getPayload(), UncompressUtils.ZLIB);
// 递归一把梭
resultPacketList = new PacketResolve(compressedData).getPacketList();
break;
}
case PROTOCOL_VERSION_3: {
byte[] compressedData = UncompressUtils.uncompress(resultPacketList.get(0).getPayload(), UncompressUtils.BROTLI);
// 递归一把梭
resultPacketList = new PacketResolve(compressedData).getPacketList();
break;
}
default:
throw new UnknownProtocolVersionException();
}
return resultPacketList;
}
}
|
924357d8eccdc3af48f85f5df4ecf3ef97c79039
| 512 |
java
|
Java
|
src/com/techhounds/commands/drive_auton/FinishedControlLoop.java
|
frc868/2016-robot-src
|
5c9502c79b1008bb500d174120ea9fe84b0c3cc4
|
[
"MIT"
] | null | null | null |
src/com/techhounds/commands/drive_auton/FinishedControlLoop.java
|
frc868/2016-robot-src
|
5c9502c79b1008bb500d174120ea9fe84b0c3cc4
|
[
"MIT"
] | null | null | null |
src/com/techhounds/commands/drive_auton/FinishedControlLoop.java
|
frc868/2016-robot-src
|
5c9502c79b1008bb500d174120ea9fe84b0c3cc4
|
[
"MIT"
] | null | null | null | 15.058824 | 52 | 0.724609 | 1,002,625 |
package com.techhounds.commands.drive_auton;
import edu.wpi.first.wpilibj.command.Command;
public class FinishedControlLoop extends Command {
@Override
protected void initialize() {
}
@Override
protected void execute() {
}
@Override
protected boolean isFinished() {
return MotionControlLoop.getInstance().finished();
}
@Override
protected void end() {
MotionControlLoop.getInstance().stop();
}
@Override
protected void interrupted() {
// TODO Auto-generated method stub
}
}
|
92435819f46b7e162c535bf116bf732427e63cc9
| 980 |
java
|
Java
|
src/main/java/no/digdir/minidnotificationserver/api/versions/VersionsEndpoint.java
|
difi/minid-notification-server
|
c3f401e917a19d93bf6bea1b54ea298c693d4c9e
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/no/digdir/minidnotificationserver/api/versions/VersionsEndpoint.java
|
difi/minid-notification-server
|
c3f401e917a19d93bf6bea1b54ea298c693d4c9e
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/no/digdir/minidnotificationserver/api/versions/VersionsEndpoint.java
|
difi/minid-notification-server
|
c3f401e917a19d93bf6bea1b54ea298c693d4c9e
|
[
"BSD-3-Clause"
] | null | null | null | 35 | 80 | 0.818367 | 1,002,626 |
package no.digdir.minidnotificationserver.api.versions;
import lombok.RequiredArgsConstructor;
import no.digdir.minidnotificationserver.config.ConfigProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@ConditionalOnExpression("${digdir.api.app-endpoints-enabled:true}")
public class VersionsEndpoint {
private final ConfigProvider configProvider;
@GetMapping("/app/versions")
public ResponseEntity<ConfigProvider.AppVersions> getVersions() {
ConfigProvider.AppVersions cfg = configProvider.getAppVersions();
return new ResponseEntity<>(cfg, HttpStatus.OK);
}
}
|
924359393938b92b453f2533728e8ced40c4064b
| 710 |
java
|
Java
|
cordonbleu-main/src/test/java/com/benromberg/cordonbleu/main/resource/repository/ReadRepositoryResponse.java
|
NicolasFrossard/cordonbleu
|
b91079fce62e0b9024fbd6a5119ea46a3faf5f13
|
[
"MIT"
] | 3 |
2017-09-01T09:06:30.000Z
|
2018-02-12T17:32:48.000Z
|
cordonbleu-main/src/test/java/com/benromberg/cordonbleu/main/resource/repository/ReadRepositoryResponse.java
|
NicolasFrossard/cordonbleu
|
b91079fce62e0b9024fbd6a5119ea46a3faf5f13
|
[
"MIT"
] | 12 |
2017-02-14T11:03:02.000Z
|
2020-08-18T15:10:47.000Z
|
cordonbleu-main/src/test/java/com/benromberg/cordonbleu/main/resource/repository/ReadRepositoryResponse.java
|
NicolasFrossard/cordonbleu
|
b91079fce62e0b9024fbd6a5119ea46a3faf5f13
|
[
"MIT"
] | 4 |
2017-03-10T13:49:47.000Z
|
2019-02-05T17:01:39.000Z
| 19.722222 | 77 | 0.669014 | 1,002,627 |
package com.benromberg.cordonbleu.main.resource.repository;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ReadRepositoryResponse {
@JsonProperty
private String id;
@JsonProperty
private String name;
@JsonProperty
private String sourceUrl;
@JsonCreator
public ReadRepositoryResponse(String id, String name, String sourceUrl) {
this.id = id;
this.name = name;
this.sourceUrl = sourceUrl;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getSourceUrl() {
return sourceUrl;
}
}
|
92435974a44fa7615679a94d4399764cc664c09a
| 3,143 |
java
|
Java
|
src/Main.java
|
CC-4/Lab7
|
24a44c5c337dfcfbb0ffd4765e5b5303546a7801
|
[
"MIT"
] | null | null | null |
src/Main.java
|
CC-4/Lab7
|
24a44c5c337dfcfbb0ffd4765e5b5303546a7801
|
[
"MIT"
] | null | null | null |
src/Main.java
|
CC-4/Lab7
|
24a44c5c337dfcfbb0ffd4765e5b5303546a7801
|
[
"MIT"
] | null | null | null | 30.221154 | 77 | 0.66847 | 1,002,628 |
/*
MIT License
Copyright (c) 2016-2019 Andrés Castellanos
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 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.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import viper.syntax.Parser;
import viper.tree.Program;
/** Lab main class. */
public final class Main {
/** Prints help message. */
private static void help() {
System.out.println("Lab 7");
System.out.println();
System.out.println("usage: [options] <files>");
System.out.println();
System.out.println("Options:");
System.out.println(" -h, --help show this help message and exit");
System.exit(0);
}
/**
* Prints a cmd line error.
*
* @param msg error message
*/
private static void error(String msg, boolean help) {
System.out.println("Lab 7");
System.out.println();
System.out.println("error: " + msg);
if (help) {
System.out.println();
System.out.println("usage: [options] <files>");
System.out.println();
System.out.println("Options:");
System.out.println(" -h, --help show this help message and exit");
}
System.exit(0);
}
/**
* Lab main method.
*
* @param args command line arguments
*/
public static void main(String[] args) {
Options options = new Options();
options.addOption(Option.builder("h").longOpt("help").build());
try {
DefaultParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("help")) {
help();
}
String[] files = cmd.getArgs();
if (files.length != 0) {
File file = new File(files[0]);
if (file.exists()) {
Program program = Parser.parse(file);
program.semant();
program.dump(System.out);
} else {
error("file " + file + " not found", false);
}
} else {
error("no files passed", true);
}
} catch (ParseException e) {
error(e.getMessage().toLowerCase(), true);
}
}
}
|
92435a7e3fed9adb0c9af09d3d9b948ad2582059
| 2,810 |
java
|
Java
|
src/main/java/ufxcoder/formats/jpeg/JpegFrame.java
|
marco-schmidt/ufxcoder
|
c5d11b633b19a74e959427e5f9cc1e7b90b0959a
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/ufxcoder/formats/jpeg/JpegFrame.java
|
marco-schmidt/ufxcoder
|
c5d11b633b19a74e959427e5f9cc1e7b90b0959a
|
[
"Apache-2.0"
] | 85 |
2018-01-11T03:24:01.000Z
|
2022-03-30T12:06:00.000Z
|
src/main/java/ufxcoder/formats/jpeg/JpegFrame.java
|
marco-schmidt/ufxcoder
|
c5d11b633b19a74e959427e5f9cc1e7b90b0959a
|
[
"Apache-2.0"
] | null | null | null | 20.215827 | 78 | 0.7 | 1,002,629 |
/*
* Copyright 2017, 2018, 2019, 2020, 2021 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 ufxcoder.formats.jpeg;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Data class describing a JPEG frame.
*/
public class JpegFrame
{
private boolean baseline;
private boolean extended;
private boolean lossless;
private boolean progressive;
private int samplePrecision;
private int numComponents;
private int width;
private int height;
private final Map<Integer, JpegFrameComponent> components = new HashMap<>();
private final List<JpegScan> scans = new ArrayList<>();
public int getSamplePrecision()
{
return samplePrecision;
}
public void setSamplePrecision(final int samplePrecision)
{
this.samplePrecision = samplePrecision;
}
public boolean isBaseline()
{
return baseline;
}
public void setBaseline(final boolean baseline)
{
this.baseline = baseline;
}
public boolean isExtended()
{
return extended;
}
public void setExtended(final boolean extended)
{
this.extended = extended;
}
public boolean isLossless()
{
return lossless;
}
public void setLossless(final boolean lossless)
{
this.lossless = lossless;
}
public boolean isProgressive()
{
return progressive;
}
public void setProgressive(final boolean progressive)
{
this.progressive = progressive;
}
public int getNumComponents()
{
return numComponents;
}
public void setNumComponents(final int numComponents)
{
this.numComponents = numComponents;
}
public int getWidth()
{
return width;
}
public void setWidth(final int width)
{
this.width = width;
}
public int getHeight()
{
return height;
}
public void setHeight(final int height)
{
this.height = height;
}
public JpegFrameComponent findComponent(final int id)
{
return components.get(Integer.valueOf(id));
}
public void add(final JpegFrameComponent comp)
{
components.put(comp.getId(), comp);
}
public void add(final JpegScan scan)
{
scans.add(scan);
}
public JpegScan getLastScan()
{
return scans.isEmpty() ? null : scans.get(scans.size() - 1);
}
}
|
92435abd3ec4128329fccd061dfc1695b2652d6c
| 3,127 |
java
|
Java
|
oas-validator/oas-validator-compatibility/src/main/java/org/apache/servicecomb/toolkit/oasv/compatibility/factory/DefaultEncodingDiffValidatorFactory.java
|
mohneesh9797-puresoftware/servicecomb-toolkit
|
cae7dd5020ef81c44182daab3c00215fa3b4bde9
|
[
"Apache-2.0"
] | 564 |
2019-06-21T07:18:09.000Z
|
2022-01-17T02:52:34.000Z
|
oas-validator/oas-validator-compatibility/src/main/java/org/apache/servicecomb/toolkit/oasv/compatibility/factory/DefaultEncodingDiffValidatorFactory.java
|
mohneesh9797-puresoftware/servicecomb-toolkit
|
cae7dd5020ef81c44182daab3c00215fa3b4bde9
|
[
"Apache-2.0"
] | 54 |
2019-06-28T02:16:25.000Z
|
2020-09-21T06:04:03.000Z
|
oas-validator/oas-validator-compatibility/src/main/java/org/apache/servicecomb/toolkit/oasv/compatibility/factory/DefaultEncodingDiffValidatorFactory.java
|
mohneesh9797-puresoftware/servicecomb-toolkit
|
cae7dd5020ef81c44182daab3c00215fa3b4bde9
|
[
"Apache-2.0"
] | 41 |
2019-06-21T07:18:15.000Z
|
2022-01-31T12:13:11.000Z
| 48.107692 | 120 | 0.827311 | 1,002,630 |
/*
* 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.servicecomb.toolkit.oasv.compatibility.factory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.servicecomb.toolkit.oasv.compatibility.validators.encoding.EncodingAddNotAllowedDiffValidator;
import org.apache.servicecomb.toolkit.oasv.compatibility.validators.encoding.EncodingAllowedReservedChangeDiffValidator;
import org.apache.servicecomb.toolkit.oasv.compatibility.validators.encoding.EncodingContentTypeNotSameDiffValidator;
import org.apache.servicecomb.toolkit.oasv.compatibility.validators.encoding.EncodingDelNotAllowedDiffValidator;
import org.apache.servicecomb.toolkit.oasv.compatibility.validators.encoding.EncodingExplodeNotSameDiffValidator;
import org.apache.servicecomb.toolkit.oasv.compatibility.validators.encoding.EncodingStyleNotSameDiffValidator;
import org.apache.servicecomb.toolkit.oasv.diffvalidation.api.EncodingDiffValidator;
import org.apache.servicecomb.toolkit.oasv.diffvalidation.factory.EncodingDiffValidatorFactory;
import org.apache.servicecomb.toolkit.oasv.diffvalidation.factory.HeaderDiffValidatorFactory;
import org.apache.servicecomb.toolkit.oasv.diffvalidation.skeleton.encoding.EncodingHeadersDiffValidator;
import org.springframework.stereotype.Component;
@Component
public class DefaultEncodingDiffValidatorFactory implements EncodingDiffValidatorFactory {
private final HeaderDiffValidatorFactory headerDiffValidatorFactory;
public DefaultEncodingDiffValidatorFactory(
HeaderDiffValidatorFactory headerDiffValidatorFactory) {
this.headerDiffValidatorFactory = headerDiffValidatorFactory;
}
@Override
public List<EncodingDiffValidator> create() {
List<EncodingDiffValidator> validators = new ArrayList<>();
// skeletons
validators.add(new EncodingHeadersDiffValidator(headerDiffValidatorFactory.create()));
// concretes
validators.add(new EncodingAddNotAllowedDiffValidator());
validators.add(new EncodingDelNotAllowedDiffValidator());
validators.add(new EncodingAllowedReservedChangeDiffValidator());
validators.add(new EncodingContentTypeNotSameDiffValidator());
validators.add(new EncodingExplodeNotSameDiffValidator());
validators.add(new EncodingStyleNotSameDiffValidator());
return Collections.unmodifiableList(validators);
}
}
|
92435c6befaa82c821890054d359ffb1830fd7bf
| 2,176 |
java
|
Java
|
backend/de.metas.adempiere.adempiere/client/src/main/java/de/metas/process/ui/SwingProcessExecutionListener.java
|
dram/metasfresh
|
a1b881a5b7df8b108d4c4ac03082b72c323873eb
|
[
"RSA-MD"
] | 1,144 |
2016-02-14T10:29:35.000Z
|
2022-03-30T09:50:41.000Z
|
backend/de.metas.adempiere.adempiere/client/src/main/java/de/metas/process/ui/SwingProcessExecutionListener.java
|
dram/metasfresh
|
a1b881a5b7df8b108d4c4ac03082b72c323873eb
|
[
"RSA-MD"
] | 8,283 |
2016-04-28T17:41:34.000Z
|
2022-03-30T13:30:12.000Z
|
backend/de.metas.adempiere.adempiere/client/src/main/java/de/metas/process/ui/SwingProcessExecutionListener.java
|
dram/metasfresh
|
a1b881a5b7df8b108d4c4ac03082b72c323873eb
|
[
"RSA-MD"
] | 441 |
2016-04-29T08:06:07.000Z
|
2022-03-28T06:09:56.000Z
| 24.738636 | 122 | 0.745521 | 1,002,631 |
package de.metas.process.ui;
import javax.swing.SwingUtilities;
import com.google.common.base.MoreObjects;
import de.metas.process.IProcessExecutionListener;
import de.metas.process.ProcessInfo;
/*
* #%L
* de.metas.adempiere.adempiere.client
* %%
* Copyright (C) 2016 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
/**
* Wraps a given {@link IProcessExecutionListener} delegate and executes all the calls in Swing's Event Dispatcher Thread.
*
* @author metas-dev <[email protected]>
*
*/
/* package */final class SwingProcessExecutionListener implements IProcessExecutionListener
{
public static final IProcessExecutionListener of(final IProcessExecutionListener delegate)
{
if (delegate instanceof SwingProcessExecutionListener)
{
return delegate;
}
return new SwingProcessExecutionListener(delegate);
}
private final IProcessExecutionListener delegate;
private SwingProcessExecutionListener(final IProcessExecutionListener delegate)
{
super();
this.delegate = delegate;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this).addValue(delegate).toString();
}
@Override
public void lockUI(final ProcessInfo pi)
{
invokeInEDT(() -> delegate.lockUI(pi));
}
@Override
public void unlockUI(final ProcessInfo pi)
{
invokeInEDT(() -> delegate.unlockUI(pi));
}
private final void invokeInEDT(final Runnable runnable)
{
if (SwingUtilities.isEventDispatchThread())
{
runnable.run();
}
else
{
SwingUtilities.invokeLater(runnable);
}
}
}
|
92435e84cb2fb2d92766b7167b78a67fa91ea0f2
| 1,359 |
java
|
Java
|
part1/src/test/java/ru/kpakulov/triangle/PointTest.java
|
kpakulov/JavaFromScratch
|
7edaa2b5a45d54e72612d0026d04f4e1c23018d7
|
[
"Apache-2.0"
] | null | null | null |
part1/src/test/java/ru/kpakulov/triangle/PointTest.java
|
kpakulov/JavaFromScratch
|
7edaa2b5a45d54e72612d0026d04f4e1c23018d7
|
[
"Apache-2.0"
] | null | null | null |
part1/src/test/java/ru/kpakulov/triangle/PointTest.java
|
kpakulov/JavaFromScratch
|
7edaa2b5a45d54e72612d0026d04f4e1c23018d7
|
[
"Apache-2.0"
] | null | null | null | 21.234375 | 86 | 0.661516 | 1,002,632 |
package ru.kpakulov.triangle;
/**
* A unit test for the class Point.class.
* Testing the method distanceTo wich calculates the distance between two given points
*
* @author kpakulov
* @version 10/14/2016
*/
//import org.junit.Ignore;
import org.junit.Test;
import static org.hamcrest.number.IsCloseTo.closeTo;
import static org.junit.Assert.assertThat;
//@Ignore
/**
* Mandatory javadoc.
*/
public class PointTest {
/**
* Mandatory javadoc.
*/
private final double constOne = 12.0;
/**
* Mandatory javadoc.
*/
private final double constTwo = 35.0;
/**
* Mandatory javadoc.
*/
private final double constThree = 3.0;
/**
* Mandatory javadoc.
*/
private final double constFour = 66.0;
/**
* Mandatory javadoc.
*/
private final double constResult = 32.28;
/**
* Deviation which is 0.01.
*/
private final double constDevt = 0.01;
/**
* Mandatory javadoc.
* @throws Exception something
*/
@Test
public void whenTwoPointsThenResultDistance() throws Exception {
Point pointOne = new Point(constOne, constTwo);
Point pointTwo = new Point(constThree, constFour);
double expectedSpan = constResult;
double span = pointOne.distanceTo(pointTwo);
// System.out.print(span);
assertThat(expectedSpan, closeTo(span, constDevt));
}
}
|
92435fc9eeb25da629781d7d0c78e3aff6149345
| 2,579 |
java
|
Java
|
src/main/java/org/benchmarkdp/toolevaluator/tool/DocToTextTask.java
|
kduretec/ToolEvaluator
|
58dfd2450cded16dc844eb5e2c0097b218d5fbb3
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/benchmarkdp/toolevaluator/tool/DocToTextTask.java
|
kduretec/ToolEvaluator
|
58dfd2450cded16dc844eb5e2c0097b218d5fbb3
|
[
"Apache-2.0"
] | 29 |
2016-11-29T16:02:45.000Z
|
2017-10-12T14:05:55.000Z
|
src/main/java/org/benchmarkdp/toolevaluator/tool/DocToTextTask.java
|
kduretec/ToolEvaluator
|
58dfd2450cded16dc844eb5e2c0097b218d5fbb3
|
[
"Apache-2.0"
] | null | null | null | 35.819444 | 107 | 0.72974 | 1,002,633 |
package org.benchmarkdp.toolevaluator.tool;
import java.io.File;
import java.util.Arrays;
import org.benchmarkdp.toolevaluator.EvaluationProc;
import org.benchmarkdp.toolevaluator.extraction.ExtractionProc;
import org.benchmarkdp.toolevaluator.tool.parser.GenericParser;
import org.benchmarkdp.toolevaluator.tool.parser.GroundTruthParser;
import benchmarkdp.datagenerator.properties.ExperimentProperties;
import benchmarkdp.datagenerator.testcase.TestCase;
public class DocToTextTask extends AbstractToolTask{
protected String tool="bash /home/duretec/Programs/doctotext/doctotext.sh";
protected String toolName="DocToText";
protected String toolNameNice="DocToText v4.01512";
public DocToTextTask(ExperimentProperties ep, TestCase tc) {
super(ep, tc);
// TODO Auto-generated constructor stub
}
@Override
public ExtractionProc getExtractionProc() {
String command = "";
//String tool = "/home/duretec/Programs/tika-app-1.1.jar";
command = command + tool;
String inputFile = ep.getFullFolderPath() + tc.getGeneratedDocument();
String outputFile = ep.getFullFolderPath() + ep.getToolOutputFolder() + "/" + toolName + "/text/";
File oF = new File(outputFile);
if (!oF.exists()) {
oF.mkdirs();
}
outputFile = outputFile + tc.getTestCaseName() + ".txt";
oF = new File(outputFile);
if (oF.exists()) {
return null;
}
command = command + " " + inputFile + " > " + outputFile;
//System.out.println(command);
ExtractionProc eproc = new ExtractionProc(new String[] { "bash", "-c", command }, outputFile, this);
return eproc;
}
@Override
public EvaluationProc getEvaluationProc() {
String toolOutput = ep.getFullFolderPath() + ep.getToolOutputFolder();
String resultsOutput = ep.getFullFolderPath() + ep.getResultsFolder();
String groundTruth = ep.getFullFolderPath() + ep.getTextFolder();
String outputFile = resultsOutput + "/" + toolName + "/results/" + tc.getTestCaseName() + ".xml";
File oF = new File(outputFile);
if (oF.exists()) {
return null;
}
ITool tika = new SoftwareTool(toolNameNice, toolOutput + "/"+ toolName + "/text",
resultsOutput + "/" + toolName + "/results", new GenericParser(), Arrays.asList("docx", "odt", "pdf"));
String docFile = tc.getGeneratedDocument();
docFile = docFile.substring(docFile.lastIndexOf(File.separator) + 1);
ITool gtTool = new GroundTruthTool("GroundTruth", groundTruth, null, new GroundTruthParser());
EvaluationProc evalProc = new EvaluationProc(docFile, tika.getToolName(), tika.getResultsPath(), gtTool,
tika);
return evalProc;
}
}
|
92435fd6c9e9c87f1dec57ece2d561a8b58d440f
| 109 |
java
|
Java
|
src/main/java/com/github/gaboso/structure/decorator/component/Sandwich.java
|
Gaboso/java-design-patterns
|
c48c753c33bca2c3580c9c2b18a72be95c5e0648
|
[
"MIT"
] | 3 |
2021-07-28T03:30:43.000Z
|
2021-12-21T12:00:05.000Z
|
src/main/java/com/github/gaboso/structure/decorator/component/Sandwich.java
|
Gaboso/java-design-patterns
|
c48c753c33bca2c3580c9c2b18a72be95c5e0648
|
[
"MIT"
] | null | null | null |
src/main/java/com/github/gaboso/structure/decorator/component/Sandwich.java
|
Gaboso/java-design-patterns
|
c48c753c33bca2c3580c9c2b18a72be95c5e0648
|
[
"MIT"
] | null | null | null | 13.625 | 56 | 0.752294 | 1,002,634 |
package com.github.gaboso.structure.decorator.component;
public interface Sandwich {
String make();
}
|
9243612c52411c032774cb39b13584172d66230c
| 19,192 |
java
|
Java
|
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/RecurringExpenseEditActivity.java
|
hushbee/EasyBudget
|
677e60f65f9d50e5a6ffe2d0647e76a4fc71380d
|
[
"Apache-2.0"
] | 1 |
2018-11-12T20:32:49.000Z
|
2018-11-12T20:32:49.000Z
|
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/RecurringExpenseEditActivity.java
|
mph3140/EasyBudget
|
5384e7622da12c4c24e8ba71254182c1995eff0d
|
[
"Apache-2.0"
] | null | null | null |
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/RecurringExpenseEditActivity.java
|
mph3140/EasyBudget
|
5384e7622da12c4c24e8ba71254182c1995eff0d
|
[
"Apache-2.0"
] | 1 |
2018-10-08T10:45:19.000Z
|
2018-10-08T10:45:19.000Z
| 34.894545 | 234 | 0.572791 | 1,002,635 |
/*
* Copyright 2015 Benoit LETONDOR
*
* 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.benoitletondor.easybudgetapp.view;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.benoitletondor.easybudgetapp.R;
import com.benoitletondor.easybudgetapp.helper.Logger;
import com.benoitletondor.easybudgetapp.helper.UIHelper;
import com.benoitletondor.easybudgetapp.helper.CurrencyHelper;
import com.benoitletondor.easybudgetapp.model.Expense;
import com.benoitletondor.easybudgetapp.model.RecurringExpense;
import com.benoitletondor.easybudgetapp.model.RecurringExpenseType;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class RecurringExpenseEditActivity extends DBActivity
{
/**
* Save floating action button
*/
private FloatingActionButton fab;
/**
* Edit text that contains the description
*/
private EditText descriptionEditText;
/**
* Edit text that contains the amount
*/
private EditText amountEditText;
/**
* Button for date selection
*/
private Button dateButton;
/**
* Textview that displays the type of expense
*/
private TextView expenseType;
/**
* Spinner to display recurrence interval options
*/
private Spinner recurringTypeSpinner;
/**
* Expense that is being edited (will be null if it's a new one)
*/
private RecurringExpense expense;
/**
* The start date of the expense
*/
private Date dateStart;
/**
* The end date of the expense (not implemented yet)
*/
private Date dateEnd;
/**
* Is the new expense a revenue
*/
private boolean isRevenue = false;
// ------------------------------------------->
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recurring_expense_edit);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
dateStart = new Date(getIntent().getLongExtra("dateStart", 0));
if (getIntent().hasExtra("expense"))
{
expense = getIntent().getParcelableExtra("expense");
setTitle(R.string.title_activity_recurring_expense_edit);
}
setUpButtons();
setUpInputs();
setUpDateButton();
setResult(RESULT_CANCELED);
if ( UIHelper.willAnimateActivityEnter(this) )
{
UIHelper.animateActivityEnter(this, new AnimatorListenerAdapter()
{
@Override
public void onAnimationEnd(Animator animation)
{
UIHelper.setFocus(descriptionEditText);
UIHelper.showFAB(fab);
}
});
}
else
{
UIHelper.setFocus(descriptionEditText);
UIHelper.showFAB(fab);
}
}
@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();
//noinspection SimplifiableIfStatement
if( id == android.R.id.home ) // Back button of the actionbar
{
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// ----------------------------------->
/**
* Validate user inputs
*
* @return true if user inputs are ok, false otherwise
*/
private boolean validateInputs()
{
boolean ok = true;
String description = descriptionEditText.getText().toString();
if( description.trim().isEmpty() )
{
descriptionEditText.setError(getResources().getString(R.string.no_description_error));
ok = false;
}
String amount = amountEditText.getText().toString();
if( amount.trim().isEmpty() )
{
amountEditText.setError(getResources().getString(R.string.no_amount_error));
ok = false;
}
else
{
try
{
double value = Double.parseDouble(amount);
if( value <= 0 )
{
amountEditText.setError(getResources().getString(R.string.negative_amount_error));
ok = false;
}
}
catch(Exception e)
{
amountEditText.setError(getResources().getString(R.string.invalid_amount));
ok = false;
}
}
return ok;
}
/**
* Set-up revenue and payment buttons
*/
private void setUpButtons()
{
expenseType = (TextView) findViewById(R.id.expense_type_tv);
SwitchCompat expenseTypeSwitch = (SwitchCompat) findViewById(R.id.expense_type_switch);
expenseTypeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
isRevenue = isChecked;
setExpenseTypeTextViewLayout();
}
});
// Init value to checked if already a revenue (can be true if we are editing an expense)
if( isRevenue )
{
expenseTypeSwitch.setChecked(true);
setExpenseTypeTextViewLayout();
}
fab = (FloatingActionButton) findViewById(R.id.save_expense_fab);
fab.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if( validateInputs() )
{
double value = Double.parseDouble(amountEditText.getText().toString());
RecurringExpense expense = new RecurringExpense(descriptionEditText.getText().toString(), isRevenue? -value : value, dateStart, getRecurringTypeFromSpinnerSelection(recurringTypeSpinner.getSelectedItemPosition()));
new SaveRecurringExpenseTask().execute(expense);
}
}
});
}
/**
* Set revenue text view layout
*/
private void setExpenseTypeTextViewLayout()
{
if( isRevenue )
{
expenseType.setText(R.string.income);
expenseType.setTextColor(ContextCompat.getColor(this, R.color.budget_green));
setTitle(R.string.title_activity_recurring_income_add);
}
else
{
expenseType.setText(R.string.payment);
expenseType.setTextColor(ContextCompat.getColor(this, R.color.budget_red));
setTitle(R.string.title_activity_recurring_expense_add);
}
}
/**
* Set up text fields, spinner and focus behavior
*/
private void setUpInputs()
{
((TextInputLayout) findViewById(R.id.amount_inputlayout)).setHint(getResources().getString(R.string.amount, CurrencyHelper.getUserCurrency(this).getSymbol()));
descriptionEditText = (EditText) findViewById(R.id.description_edittext);
if( expense != null )
{
descriptionEditText.setText(expense.getTitle());
descriptionEditText.setSelection(descriptionEditText.getText().length()); // Put focus at the end of the text
}
amountEditText = (EditText) findViewById(R.id.amount_edittext);
UIHelper.preventUnsupportedInputForDecimals(amountEditText);
if( expense != null )
{
amountEditText.setText(CurrencyHelper.getFormattedAmountValue(Math.abs(expense.getAmount())));
}
recurringTypeSpinner = (Spinner) findViewById(R.id.expense_type_spinner);
final String[] recurringTypesString = new String[4];
recurringTypesString[0] = getString(R.string.recurring_interval_weekly);
recurringTypesString[1] = getString(R.string.recurring_interval_bi_weekly);
recurringTypesString[2] = getString(R.string.recurring_interval_monthly);
recurringTypesString[3] = getString(R.string.recurring_interval_yearly);
final ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.spinner_item, recurringTypesString);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
recurringTypeSpinner.setAdapter(adapter);
if( expense != null )
{
recurringTypeSpinner.setSelection(expense.getType().ordinal(), false);
}
else
{
recurringTypeSpinner.setSelection(2, false);
}
}
/**
* Get the recurring expense type associated with the spinner selection
*
* @param spinnerSelectedItem index of the spinner selection
* @return the corresponding expense type
*/
private RecurringExpenseType getRecurringTypeFromSpinnerSelection(int spinnerSelectedItem)
{
switch (spinnerSelectedItem)
{
case 0:
return RecurringExpenseType.WEEKLY;
case 1:
return RecurringExpenseType.BI_WEEKLY;
case 2:
return RecurringExpenseType.MONTHLY;
case 3:
return RecurringExpenseType.YEARLY;
}
throw new IllegalStateException("getRecurringTypeFromSpinnerSelection unable to get value for "+spinnerSelectedItem);
}
/**
* Set up the date button
*/
private void setUpDateButton()
{
dateButton = (Button) findViewById(R.id.date_button);
UIHelper.removeButtonBorder(dateButton); // Remove border on lollipop
updateDateButtonDisplay();
dateButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
DatePickerDialogFragment fragment = new DatePickerDialogFragment(dateStart, new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
dateStart = cal.getTime();
updateDateButtonDisplay();
}
});
fragment.show(getSupportFragmentManager(), "datePicker");
}
});
}
private void updateDateButtonDisplay()
{
SimpleDateFormat formatter = new SimpleDateFormat(getResources().getString(R.string.add_expense_date_format), Locale.getDefault());
dateButton.setText(formatter.format(dateStart));
}
// ------------------------------------------->
/**
* An asynctask to save recurring expense to DB
*/
private class SaveRecurringExpenseTask extends AsyncTask<RecurringExpense, Integer, Boolean>
{
/**
* Dialog used to display loading to the user
*/
private ProgressDialog dialog;
@Override
protected Boolean doInBackground(RecurringExpense... expenses)
{
for (RecurringExpense expense : expenses)
{
boolean inserted = db.addRecurringExpense(expense);
if( !inserted )
{
Logger.error(false, "Error while inserting recurring expense into DB: addRecurringExpense returned false");
return false;
}
if( !flattenExpensesForRecurringExpense(expense) )
{
Logger.error(false, "Error while flattening expenses for recurring expense: flattenExpensesForRecurringExpense returned false");
return false;
}
}
return true;
}
private boolean flattenExpensesForRecurringExpense(@NonNull RecurringExpense expense)
{
Calendar cal = Calendar.getInstance();
cal.setTime(dateStart);
switch (expense.getType())
{
case WEEKLY:
// Add up to 5 years of expenses
for (int i = 0; i < 12*4*5; i++)
{
boolean expenseInserted = db.persistExpense(new Expense(expense.getTitle(), expense.getAmount(), cal.getTime(), expense));
if (!expenseInserted)
{
Logger.error(false, "Error while inserting expense for recurring expense into DB: persistExpense returned false");
return false;
}
cal.add(Calendar.WEEK_OF_YEAR, 1);
if (dateEnd != null && cal.getTime().after(dateEnd)) // If we have an end date, stop to that one
{
break;
}
}
break;
case BI_WEEKLY:
// Add up to 5 years of expenses
for (int i = 0; i < 12*4*5; i++)
{
boolean expenseInserted = db.persistExpense(new Expense(expense.getTitle(), expense.getAmount(), cal.getTime(), expense));
if (!expenseInserted)
{
Logger.error(false, "Error while inserting expense for recurring expense into DB: persistExpense returned false");
return false;
}
cal.add(Calendar.WEEK_OF_YEAR, 2);
if (dateEnd != null && cal.getTime().after(dateEnd)) // If we have an end date, stop to that one
{
break;
}
}
break;
case MONTHLY:
// Add up to 10 years of expenses
for (int i = 0; i < 12 * 10; i++)
{
boolean expenseInserted = db.persistExpense(new Expense(expense.getTitle(), expense.getAmount(), cal.getTime(), expense));
if (!expenseInserted)
{
Logger.error(false, "Error while inserting expense for recurring expense into DB: persistExpense returned false");
return false;
}
cal.add(Calendar.MONTH, 1);
if (dateEnd != null && cal.getTime().after(dateEnd)) // If we have an end date, stop to that one
{
break;
}
}
break;
case YEARLY:
// Add up to 100 years of expenses
for (int i = 0; i < 100; i++)
{
boolean expenseInserted = db.persistExpense(new Expense(expense.getTitle(), expense.getAmount(), cal.getTime(), expense));
if (!expenseInserted)
{
Logger.error(false, "Error while inserting expense for recurring expense into DB: persistExpense returned false");
return false;
}
cal.add(Calendar.YEAR, 1);
if (dateEnd != null && cal.getTime().after(dateEnd)) // If we have an end date, stop to that one
{
break;
}
}
break;
}
return true;
}
@Override
protected void onPreExecute()
{
// Show a ProgressDialog
dialog = new ProgressDialog(RecurringExpenseEditActivity.this);
dialog.setIndeterminate(true);
dialog.setTitle(R.string.recurring_expense_add_loading_title);
dialog.setMessage(getResources().getString(isRevenue ? R.string.recurring_income_add_loading_message : R.string.recurring_expense_add_loading_message));
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
}
@Override
protected void onPostExecute(Boolean result)
{
// Dismiss the dialog
dialog.dismiss();
if (result)
{
setResult(RESULT_OK);
finish();
}
else
{
new AlertDialog.Builder(RecurringExpenseEditActivity.this)
.setTitle(R.string.recurring_expense_add_error_title)
.setMessage(getResources().getString(R.string.recurring_expense_add_error_message))
.setNegativeButton(R.string.ok, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.show();
}
}
}
}
|
9243616e750e649634fb6abbacb5626869e8c7a8
| 2,946 |
java
|
Java
|
src/main/java/org/kathra/harbor/client/model/Password.java
|
kathra-project/kathra-binaryrepositorymanager-harbor
|
0492b0fb0c589b5ab19d062befb637b259e21965
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/kathra/harbor/client/model/Password.java
|
kathra-project/kathra-binaryrepositorymanager-harbor
|
0492b0fb0c589b5ab19d062befb637b259e21965
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/kathra/harbor/client/model/Password.java
|
kathra-project/kathra-binaryrepositorymanager-harbor
|
0492b0fb0c589b5ab19d062befb637b259e21965
|
[
"Apache-2.0"
] | null | null | null | 24.966102 | 120 | 0.690088 | 1,002,636 |
/*
* Harbor API
* These APIs provide services for manipulating Harbor project.
*
* OpenAPI spec version: 1.10.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package org.kathra.harbor.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;
/**
* Password
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2020-06-20T18:34:04.523Z")
public class Password {
@SerializedName("old_password")
private String oldPassword = null;
@SerializedName("new_password")
private String newPassword = null;
public Password oldPassword(String oldPassword) {
this.oldPassword = oldPassword;
return this;
}
/**
* The user's existing password.
* @return oldPassword
**/
@ApiModelProperty(value = "The user's existing password.")
public String getOldPassword() {
return oldPassword;
}
public void setOldPassword(String oldPassword) {
this.oldPassword = oldPassword;
}
public Password newPassword(String newPassword) {
this.newPassword = newPassword;
return this;
}
/**
* New password for marking as to be updated.
* @return newPassword
**/
@ApiModelProperty(value = "New password for marking as to be updated.")
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Password password = (Password) o;
return Objects.equals(this.oldPassword, password.oldPassword) &&
Objects.equals(this.newPassword, password.newPassword);
}
@Override
public int hashCode() {
return Objects.hash(oldPassword, newPassword);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Password {\n");
sb.append(" oldPassword: ").append(toIndentedString(oldPassword)).append("\n");
sb.append(" newPassword: ").append(toIndentedString(newPassword)).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 ");
}
}
|
924362d0828c95b8edb9b4ec429749e7fbbb8fd3
| 571 |
java
|
Java
|
communication-protocol-analysis/src/main/java/io/github/guoxinl/protocol/analysis/model/anno/Protocol.java
|
GuoxinL/protocol
|
21fb0707dc8126bfb83e60bf1bb1b4e16a1b447b
|
[
"Apache-2.0"
] | 5 |
2018-07-23T16:49:52.000Z
|
2018-08-17T01:47:54.000Z
|
communication-protocol-analysis/src/main/java/io/github/guoxinl/protocol/analysis/model/anno/Protocol.java
|
GuoxinL/protocol
|
21fb0707dc8126bfb83e60bf1bb1b4e16a1b447b
|
[
"Apache-2.0"
] | null | null | null |
communication-protocol-analysis/src/main/java/io/github/guoxinl/protocol/analysis/model/anno/Protocol.java
|
GuoxinL/protocol
|
21fb0707dc8126bfb83e60bf1bb1b4e16a1b447b
|
[
"Apache-2.0"
] | 3 |
2018-08-23T07:57:31.000Z
|
2021-01-20T07:30:36.000Z
| 13.926829 | 55 | 0.565674 | 1,002,637 |
package io.github.guoxinl.protocol.analysis.model.anno;
import java.lang.annotation.*;
/**
* 用于将一个对象标注为协议对象
* <p>
* 警告:
* 1. 请给协议对象添加有效的构造函数
* 2. 请给协议对象添加空构造函数
* <p>
* Create by guoxin on 2018/6/13
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Protocol {
/**
* 协议头:命令索引
*
* @return skip
*/
short commandIndex();
/**
* 协议版本
*
* @return skip
*/
short version();
/**
* 描述
*
* @return skip
*/
String description() default "";
}
|
92436349a95f661c5ce23a3d1065a3174aa83c27
| 1,168 |
java
|
Java
|
SpotIT/app/src/main/java/com/it/spot/threading/Event.java
|
bogdanghita/spotit-client-android
|
c3567084b7d841355293a752442f1e85fd57719c
|
[
"MIT"
] | null | null | null |
SpotIT/app/src/main/java/com/it/spot/threading/Event.java
|
bogdanghita/spotit-client-android
|
c3567084b7d841355293a752442f1e85fd57719c
|
[
"MIT"
] | null | null | null |
SpotIT/app/src/main/java/com/it/spot/threading/Event.java
|
bogdanghita/spotit-client-android
|
c3567084b7d841355293a752442f1e85fd57719c
|
[
"MIT"
] | null | null | null | 16 | 70 | 0.587329 | 1,002,638 |
package com.it.spot.threading;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by Bogdan on 04/04/2016.
*/
public class Event {
Lock lock = new ReentrantLock();
Condition cond = lock.newCondition();
boolean flag;
public void doWait() throws InterruptedException {
lock.lock();
try {
while (!flag) {
cond.await();
}
}
finally {
lock.unlock();
}
}
public void doWait(float milliseconds) throws InterruptedException {
lock.lock();
try {
while (!flag) {
cond.await((int) (milliseconds), TimeUnit.MILLISECONDS);
}
}
finally {
lock.unlock();
}
}
public boolean isSet() {
lock.lock();
try {
return flag;
}
finally {
lock.unlock();
}
}
public void set() {
lock.lock();
try {
flag = true;
cond.signalAll();
}
finally {
lock.unlock();
}
}
public void clear() {
lock.lock();
try {
flag = false;
cond.signalAll();
}
finally {
lock.unlock();
}
}
}
|
924363a1abdffeb148e118874a8b1ee120265596
| 3,341 |
java
|
Java
|
src/main/java/ru/mail/polis/psaer/blockchain/BlockChainDAO.java
|
psaer/2018-highload-kv
|
660088d35a08a2e38093dd088dad623a20642190
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/ru/mail/polis/psaer/blockchain/BlockChainDAO.java
|
psaer/2018-highload-kv
|
660088d35a08a2e38093dd088dad623a20642190
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/ru/mail/polis/psaer/blockchain/BlockChainDAO.java
|
psaer/2018-highload-kv
|
660088d35a08a2e38093dd088dad623a20642190
|
[
"Apache-2.0"
] | null | null | null | 34.091837 | 121 | 0.694104 | 1,002,639 |
package ru.mail.polis.psaer.blockchain;
import org.jetbrains.annotations.NotNull;
import ru.mail.polis.KVDao;
import ru.mail.polis.psaer.blockchain.dto.FunctionParamDTO;
import ru.mail.polis.psaer.blockchain.service.TransactionService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
public class BlockChainDAO implements KVDao {
private static final String GET_FUNCTION = "get";
private static final String UPSERT_FUNCTION = "upsert";
private static final String REMOVE_FUNCTION = "remove";
private static final String CONTAINS_KEY_FUNCTION = "containsKey";
private static final Integer ZERO_NUMBER_CODE = 48;
@NotNull
private final TransactionService transactionService;
public BlockChainDAO() {
transactionService = new TransactionService();
}
@NotNull
@Override
public byte[] get(@NotNull byte[] key) throws NoSuchElementException, IOException {
List<FunctionParamDTO> paramList = getKeyOnlyParamList(key);
if (!keyExistsInStore(key, paramList))
throw new NoSuchElementException();
byte[] result = this.transactionService.makeStateFunction(GET_FUNCTION, paramList);
/* Blockchain problem with null(0 bytes) value, so this hardcode */
result = checkForNullValue(result);
return result;
}
@Override
public void upsert(@NotNull byte[] key, @NotNull byte[] value) throws IOException {
List<FunctionParamDTO> paramList = getInsertParamList(key, value);
transactionService.makeTransactionFunction(UPSERT_FUNCTION, paramList);
}
@Override
public void remove(@NotNull byte[] key) throws IOException {
List<FunctionParamDTO> paramList = getKeyOnlyParamList(key);
this.transactionService.makeTransactionFunction(REMOVE_FUNCTION, paramList);
}
@Override
public void close() throws IOException {
// NOTHING
}
private boolean keyExistsInStore(@NotNull byte[] key, @NotNull List<FunctionParamDTO> paramList) throws IOException {
byte[] response = this.transactionService.makeStateFunction(CONTAINS_KEY_FUNCTION, paramList);
/* Last bit ALWAYS mean true/false for boolean */
if (response.length != 0 && response[response.length - 1] == 1)
return true;
return false;
}
private static List<FunctionParamDTO> getInsertParamList(@NotNull byte[] key, @NotNull byte[] value) {
List<FunctionParamDTO> paramList = new ArrayList<>();
FunctionParamDTO paramKey = new FunctionParamDTO("bytes", key);
FunctionParamDTO paramValue = new FunctionParamDTO("bytes", value);
paramList.add(paramKey);
paramList.add(paramValue);
return paramList;
}
private static List<FunctionParamDTO> getKeyOnlyParamList(@NotNull byte[] key) {
List<FunctionParamDTO> paramList = new ArrayList<>();
FunctionParamDTO paramKey = new FunctionParamDTO("bytes", key);
paramList.add(paramKey);
return paramList;
}
private static byte[] checkForNullValue(@NotNull byte[] value) {
for (int i = 0; i < value.length; i++) {
if (value[i] != ZERO_NUMBER_CODE)
return value;
}
return new byte[0];
}
}
|
9243645e4eccae93c0d92d1b6a7cdcfdb7fbeef4
| 1,145 |
java
|
Java
|
src/main/java/net/aindrigo/ainTweaks/events/AinListener.java
|
aindrigo0/ainTweaks
|
548fbea5108416f9f90ad5f105cf2b6eb0814e71
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/net/aindrigo/ainTweaks/events/AinListener.java
|
aindrigo0/ainTweaks
|
548fbea5108416f9f90ad5f105cf2b6eb0814e71
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/net/aindrigo/ainTweaks/events/AinListener.java
|
aindrigo0/ainTweaks
|
548fbea5108416f9f90ad5f105cf2b6eb0814e71
|
[
"Apache-2.0"
] | null | null | null | 30.945946 | 65 | 0.750218 | 1,002,640 |
package net.aindrigo.ainTweaks.events;
import net.aindrigo.ainTweaks.customItems.ButteredBread;
import net.aindrigo.ainTweaks.customItems.CustomFood;
import net.aindrigo.ainTweaks.main.MainPlugin;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
public class AinListener implements org.bukkit.event.Listener {
ButteredBread bread = MainPlugin.bread;
@EventHandler
public void onConsume(PlayerItemConsumeEvent event){
ItemStack stack = event.getItem();
Player player = event.getPlayer();
CustomFood.processItem(player,stack);
}
@EventHandler
public void onCraft(CraftItemEvent event){
Recipe recipe = event.getRecipe();
Inventory inventory = event.getInventory();
if(MainPlugin.butter.isItem(recipe.getResult())){
inventory.addItem(new ItemStack(Material.BUCKET, 1));
}
}
}
|
9243677ae0a7c3a514eb20f5c7efaa3452d2db2b
| 5,222 |
java
|
Java
|
src/com/cbsb/backup/exporter/SimpleExporter.java
|
AlexandrBasan/CB_data_backup
|
212c374d2ce6547af5b7341dff0aee5327a2a028
|
[
"MIT"
] | 1 |
2019-02-14T17:32:23.000Z
|
2019-02-14T17:32:23.000Z
|
src/com/cbsb/backup/exporter/SimpleExporter.java
|
AlexandrBasan/CB_data_backup
|
212c374d2ce6547af5b7341dff0aee5327a2a028
|
[
"MIT"
] | null | null | null |
src/com/cbsb/backup/exporter/SimpleExporter.java
|
AlexandrBasan/CB_data_backup
|
212c374d2ce6547af5b7341dff0aee5327a2a028
|
[
"MIT"
] | null | null | null | 26.779487 | 174 | 0.665837 | 1,002,641 |
package com.cbsb.backup.exporter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Vector;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import com.cbsb.backup.BackupTask;
import com.cbsb.backup.R;
import com.cbsb.backup.Strings;
public abstract class SimpleExporter extends Exporter {
protected static final String EQUALS = "=\"";
protected Context context;
private String tag;
private String[] fields;
private Uri contentUri;
private boolean checkFields;
private String selection;
private String filename;
private String sortOrder;
private String[] optionalFields;
public SimpleExporter(String tag, String[] fields, Uri contentUri, boolean checkFields, String selection, String sortOrder, ExportTask exportTask, String[] optionalFields) {
super(exportTask);
this.context = exportTask.getContext();
this.tag = tag;
this.fields = fields;
this.contentUri = contentUri;
this.selection = selection;
this.checkFields = checkFields;
this.sortOrder = sortOrder;
this.optionalFields = optionalFields;
}
public SimpleExporter(String tag, String[] fields, Uri contentUri, boolean checkFields, String selection, ExportTask exportTask) {
this(tag, fields, contentUri, checkFields, selection, null, exportTask, null);
}
public SimpleExporter(String tag, String[] fields, Uri contentUri, boolean checkFields, ExportTask exportTask) {
this(tag, fields, contentUri, checkFields, null, exportTask);
}
public SimpleExporter(String tag, Uri contentUri, String selection, ExportTask exportTask) {
this(tag, null, contentUri, false, selection, exportTask);
}
public SimpleExporter(String tag, Uri contentUri, ExportTask exportTask) {
this(tag, contentUri, null, exportTask);
}
public final int export(String filename) throws Exception {
this.filename = filename;
Cursor cursor = context.getContentResolver().query(contentUri, null, selection, null, sortOrder);
if (checkFields && fields != null) {
if (cursor == null || !checkFieldNames(cursor.getColumnNames(), fields)) {
throw new Exception(context.getString(R.string.error_unsupporteddatabasestructure));
}
if (optionalFields != null && optionalFields.length > 0) {
fields = determineFields(cursor.getColumnNames(), fields, optionalFields);
}
} else if (fields == null) {
if (cursor == null) {
this.filename = null;
return 0;
} else {
fields = cursor.getColumnNames();
}
}
int count = cursor.getCount();
if (count == 0) {
this.filename = null;
return 0;
}
exportTask.progress(BackupTask.MESSAGE_COUNT, count);
exportTask.progress(BackupTask.MESSAGE_PROGRESS, 0);
int length = fields.length;
int[] positions = new int[length];
for (int n = 0; n < length; n++) {
positions[n] = cursor.getColumnIndex(fields[n]);
}
BufferedWriter writer = new BufferedWriter(new PrintWriter(filename, Strings.UTF8));
writeXmlStart(writer, tag, count);
int position = 0;
while (!canceled && cursor.moveToNext()) {
writer.write('<');
writer.write(tag);
for (int n = 0; n < length; n++) {
try {
String string = cursor.getString(positions[n]);
if (string != null && !BaseColumns._ID.equals(fields[n])) {
writer.write(' ');
writer.write(fields[n]);
writer.write(EQUALS);
writer.write(TextUtils.htmlEncode(string));
writer.write('"');
}
} catch (Exception e) {
// if there is blob data
}
}
writer.write('>');
addText(cursor, writer);
writer.write(ENDTAG_START);
writer.write(tag);
writer.write(TAG_END);
exportTask.progress(BackupTask.MESSAGE_PROGRESS, ++position);
}
cursor.close();
writeXmlEnd(writer, tag);
writer.close();
if (!canceled) {
return count;
} else {
new File(filename).delete();
this.filename = null;
return -1;
}
}
private String[] determineFields(String[] columnNames, String[] fields, String[] optionalFields) {
Vector<String> result = new Vector<String>();
for (String field : fields) {
result.add(field);
}
for (String field : optionalFields) {
if (Strings.indexOf(columnNames, field) > -1) {
result.add(field);
}
}
return result.toArray(new String[0]);
}
protected boolean checkFieldNames(String[] availableFieldNames, String[] neededFieldNames) {
for (int n = 0, i = neededFieldNames != null ? neededFieldNames.length : 0; n < i; n++) {
if (Strings.indexOf(availableFieldNames, neededFieldNames[n]) == -1) {
return false;
}
}
return true;
}
/*
* Override to use
*/
public void addText(Cursor cursor, Writer writer) throws IOException {
}
@Override
public String[] getExportedFilenames() {
return new String[] {filename};
}
public String getFilename() {
return filename;
}
}
|
9243683e6df613361fdcee53ee277f97e66a5ae3
| 159 |
java
|
Java
|
src/main/java/br/com/biot/integracaopagarmeapi/modulos/util/Aplicacao.java
|
vhnegrisoli/integracao-pagarme-api
|
5681e1b03621ea85ac7a89a5f9bb37bcf6d6f229
|
[
"MIT"
] | null | null | null |
src/main/java/br/com/biot/integracaopagarmeapi/modulos/util/Aplicacao.java
|
vhnegrisoli/integracao-pagarme-api
|
5681e1b03621ea85ac7a89a5f9bb37bcf6d6f229
|
[
"MIT"
] | null | null | null |
src/main/java/br/com/biot/integracaopagarmeapi/modulos/util/Aplicacao.java
|
vhnegrisoli/integracao-pagarme-api
|
5681e1b03621ea85ac7a89a5f9bb37bcf6d6f229
|
[
"MIT"
] | null | null | null | 17.666667 | 54 | 0.779874 | 1,002,642 |
package br.com.biot.integracaopagarmeapi.modulos.util;
public enum Aplicacao {
CADEIRA_LIVRE_EMPRESA,
CADEIRA_LIVRE_ADMIN,
NUTRICAO_ESPORTIVA;
}
|
924369058386030fc6338adbe0b95d98fadc223d
| 1,456 |
java
|
Java
|
testsuite/java_test/string_test/RT0154-rt-string-StringEqualsShort/TestStringEqualsShort.java
|
openmaple/MapleCompiler
|
1648e63144766563f1ec44a25e0b618415648627
|
[
"MulanPSL-1.0"
] | 5 |
2019-09-02T04:44:52.000Z
|
2021-11-08T12:23:51.000Z
|
testsuite/java_test/string_test/RT0154-rt-string-StringEqualsShort/TestStringEqualsShort.java
|
venshine/OpenArkCompiler
|
264cd4463834356658154f0d254672ef559f245f
|
[
"MulanPSL-1.0"
] | 2 |
2020-07-21T01:22:01.000Z
|
2021-12-06T08:07:16.000Z
|
testsuite/java_test/string_test/RT0154-rt-string-StringEqualsShort/TestStringEqualsShort.java
|
venshine/OpenArkCompiler
|
264cd4463834356658154f0d254672ef559f245f
|
[
"MulanPSL-1.0"
] | 4 |
2019-09-02T04:46:52.000Z
|
2020-09-10T11:30:03.000Z
| 35.512195 | 88 | 0.62294 | 1,002,643 |
/*
* Copyright (c) [2021] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
public class TestStringEqualsShort {
public static void main(String args[]) throws Exception {
StringEqualsShort test = new StringEqualsShort();
test.resultEqualsShort();
}
}
class StringEqualsShort {
private final String[][] shortStrings = new String[][]{
// Equal, constant comparison
{"a", "a"},
// Different constants, first character different
{":", " :"},
// Different constants, last character different, same length
{"ja M", "ja N"},
// Different constants, different lengths
{"$$$", "$$"},
// Force execution of code beyond reference equality check
{"hi", new String("hi")}
};
public void resultEqualsShort() {
for (int i = 0; i < shortStrings.length; i++) {
System.out.println(shortStrings[i][0].equals(shortStrings[i][1]));
}
}
}
|
92436a4041fe6996e43da8b987b7f436e8446d9f
| 2,643 |
java
|
Java
|
saml/src/main/java/pl/edu/icm/unity/saml/ecp/ECPServlet.java
|
unity-idm/test-import
|
246b06505afe193167daf894dabff8cc7ffd6787
|
[
"BSD-3-Clause"
] | null | null | null |
saml/src/main/java/pl/edu/icm/unity/saml/ecp/ECPServlet.java
|
unity-idm/test-import
|
246b06505afe193167daf894dabff8cc7ffd6787
|
[
"BSD-3-Clause"
] | null | null | null |
saml/src/main/java/pl/edu/icm/unity/saml/ecp/ECPServlet.java
|
unity-idm/test-import
|
246b06505afe193167daf894dabff8cc7ffd6787
|
[
"BSD-3-Clause"
] | null | null | null | 37.757143 | 104 | 0.81347 | 1,002,644 |
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.saml.ecp;
import java.io.IOException;
import java.util.function.Supplier;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import eu.unicore.samly2.validators.ReplayAttackChecker;
import pl.edu.icm.unity.engine.api.EntityManagement;
import pl.edu.icm.unity.engine.api.PKIManagement;
import pl.edu.icm.unity.engine.api.authn.remote.RemoteAuthnResultTranslator;
import pl.edu.icm.unity.engine.api.session.SessionManagement;
import pl.edu.icm.unity.engine.api.token.TokensManagement;
import pl.edu.icm.unity.rest.jwt.JWTAuthenticationConfig;
import pl.edu.icm.unity.saml.metadata.cfg.SPRemoteMetaManager;
import pl.edu.icm.unity.saml.sp.config.SAMLSPConfiguration;
import pl.edu.icm.unity.types.authn.AuthenticationRealm;
/**
* ECP servlet which performs the actual ECP profile processing over PAOS binding.
* <p>
* The GET request is used to ask for SAML request. The POST request is used to provide SAML response
* and obtain a JWT token which can be subsequently used with other Unity endpoints.
*
* @author K. Benedyczak
*/
public class ECPServlet extends HttpServlet
{
private final ECPStep1Handler step1Handler;
private final ECPStep2Handler step2Handler;
public ECPServlet(JWTAuthenticationConfig jwtConfig,
Supplier<SAMLSPConfiguration> configProvider,
SPRemoteMetaManager metadataManager,
ECPContextManagement samlContextManagement,
String myAddress, ReplayAttackChecker replayAttackChecker,
RemoteAuthnResultTranslator remoteAuthnProcessor,
TokensManagement tokensMan, PKIManagement pkiManagement, EntityManagement identitiesMan,
SessionManagement sessionMan, AuthenticationRealm realm, String address)
{
step1Handler = new ECPStep1Handler(configProvider, metadataManager, samlContextManagement, myAddress);
step2Handler = new ECPStep2Handler(jwtConfig, configProvider,
metadataManager, samlContextManagement, myAddress,
replayAttackChecker,
tokensMan, pkiManagement, remoteAuthnProcessor,
identitiesMan, sessionMan, realm, address);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
step1Handler.processECPGetRequest(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
step2Handler.processECPPostRequest(req, resp);
}
}
|
92436b3fb99c12ea4585ad7969ce88baf501ed1f
| 741 |
java
|
Java
|
src/main/java/br/com/study/theKnowledgeDungeon/validation/handle/EntityNonExistentForManipulateExceptionHandler.java
|
Nechelley/TheKnowledgeDungeon
|
1e525540d2854607ba3402a74333bfe698dc8f58
|
[
"MIT"
] | null | null | null |
src/main/java/br/com/study/theKnowledgeDungeon/validation/handle/EntityNonExistentForManipulateExceptionHandler.java
|
Nechelley/TheKnowledgeDungeon
|
1e525540d2854607ba3402a74333bfe698dc8f58
|
[
"MIT"
] | null | null | null |
src/main/java/br/com/study/theKnowledgeDungeon/validation/handle/EntityNonExistentForManipulateExceptionHandler.java
|
Nechelley/TheKnowledgeDungeon
|
1e525540d2854607ba3402a74333bfe698dc8f58
|
[
"MIT"
] | null | null | null | 39 | 101 | 0.859649 | 1,002,645 |
package br.com.study.theKnowledgeDungeon.validation.handle;
import br.com.study.theKnowledgeDungeon.validation.exception.EntityNonExistentForManipulateException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class EntityNonExistentForManipulateExceptionHandler {
@ResponseStatus(code = HttpStatus.NOT_FOUND)
@ExceptionHandler(EntityNonExistentForManipulateException.class)
public ResponseEntity<Object> handle() {
return ResponseEntity.notFound().build();
}
}
|
92436c8aff678e0db9c74c4e077df10e6f496f7f
| 10,951 |
java
|
Java
|
kettle-ext/src/main/java/org/flhy/ext/trans/steps/ExcelOutput.java
|
heatedcpu/webkettle
|
70f7df516c2a5bb430492a993c450ea17ad3afa5
|
[
"Apache-2.0"
] | 460 |
2018-05-23T08:05:20.000Z
|
2022-03-27T10:21:00.000Z
|
kettle-ext/src/main/java/org/flhy/ext/trans/steps/ExcelOutput.java
|
heatedcpu/webkettle
|
70f7df516c2a5bb430492a993c450ea17ad3afa5
|
[
"Apache-2.0"
] | 17 |
2018-09-08T01:27:30.000Z
|
2022-02-15T06:56:23.000Z
|
kettle-ext/src/main/java/org/flhy/ext/trans/steps/ExcelOutput.java
|
heatedcpu/webkettle
|
70f7df516c2a5bb430492a993c450ea17ad3afa5
|
[
"Apache-2.0"
] | 224 |
2018-07-18T03:57:31.000Z
|
2022-03-26T11:29:36.000Z
| 61.870056 | 259 | 0.703406 | 1,002,646 |
package org.flhy.ext.trans.steps;
import com.mxgraph.model.mxCell;
import com.mxgraph.util.mxUtils;
import org.flhy.ext.core.PropsUI;
import org.flhy.ext.trans.step.AbstractStep;
import org.flhy.ext.utils.JSONArray;
import org.flhy.ext.utils.JSONObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.exceloutput.ExcelField;
import org.pentaho.di.trans.steps.exceloutput.ExcelOutputMeta;
import org.pentaho.metastore.api.IMetaStore;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.List;
/**
* Created by cRAZY on 2017/5/24.
*/
@Component("ExcelOutput")
@Scope("prototype")
public class ExcelOutput extends AbstractStep{
public static Integer getIndex(String[] sources,String target){
Integer result=0;
if(null==target || target.equals("")){
result=0;
}else{
for(int i=0;i<sources.length;i++){
if(target.equalsIgnoreCase(sources[i])){
result=i;
break;
}
}
}
return result;
}
@Override
public void decode(StepMetaInterface stepMetaInterface, mxCell cell, List<DatabaseMeta> databases, IMetaStore metaStore) throws Exception {
ExcelOutputMeta excel=(ExcelOutputMeta)stepMetaInterface;
excel.setHeaderEnabled(cell.getAttribute("header").equalsIgnoreCase("Y"));
excel.setFooterEnabled(cell.getAttribute("footer").equalsIgnoreCase("Y"));
excel.setEncoding(cell.getAttribute("encoding"));
excel.setAppend(cell.getAttribute("append").equalsIgnoreCase("Y"));
String e=cell.getAttribute("add_to_result_filenames");
if(Const.isEmpty(e)) {
excel.setAddToResultFiles(true);
} else {
excel.setAddToResultFiles("Y".equalsIgnoreCase(e));
}
excel.setFileName(cell.getAttribute("name"));
excel.setExtension(cell.getAttribute("extention"));
excel.setDoNotOpenNewFileInit(cell.getAttribute("do_not_open_newfile_init").equalsIgnoreCase("Y"));
excel.setCreateParentFolder(cell.getAttribute("create_parent_folder").equalsIgnoreCase("Y"));
excel.setStepNrInFilename(cell.getAttribute("split").equalsIgnoreCase("Y"));
excel.setDateInFilename(cell.getAttribute("add_date").equalsIgnoreCase("Y"));
excel.setTimeInFilename(cell.getAttribute("add_time").equalsIgnoreCase("Y"));
excel.setSpecifyFormat(cell.getAttribute("SpecifyFormat").equalsIgnoreCase("Y"));
excel.setDateTimeFormat(cell.getAttribute("date_time_format"));
excel.setUseTempFiles(cell.getAttribute("usetempfiles").equalsIgnoreCase("Y"));
excel.setTempDirectory(cell.getAttribute("tempdirectory"));
excel.setAutoSizeColums(cell.getAttribute("autosizecolums").equalsIgnoreCase("Y"));
excel.setNullIsBlank(cell.getAttribute("nullisblank").equalsIgnoreCase("Y"));
excel.setProtectSheet(cell.getAttribute("protect_sheet").equalsIgnoreCase("Y"));
excel.setPassword(Encr.decryptPasswordOptionallyEncrypted(cell.getAttribute("password")));
excel.setSplitEvery(Const.toInt(cell.getAttribute("splitevery"), 0));
excel.setSheetname(cell.getAttribute("sheetname"));
excel.setTemplateEnabled(cell.getAttribute("enabled").equalsIgnoreCase("Y"));
excel.setTemplateAppend(cell.getAttribute("append").equalsIgnoreCase("Y"));
excel.setTemplateFileName(cell.getAttribute("filename"));
String fields=cell.getAttribute("fields");
JSONArray jsonArray=JSONArray.fromObject(fields);
if(jsonArray.size()>0){
ExcelField[] efs=new ExcelField[jsonArray.size()];
for(int i=0; i<jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ExcelField ef=new ExcelField();
ef.setName(jsonObject.optString("name"));
ef.setType(jsonObject.optString("type"));
ef.setFormat(jsonObject.optString("format"));
efs[i]=ef;
}
excel.setOutputFields(efs);
}
excel.setHeaderFontName(this.getIndex(excel.font_name_code,cell.getAttribute("header_font_name")));
excel.setHeaderFontSize(Const.NVL(cell.getAttribute("header_font_size"), "10"));
excel.setHeaderFontBold("Y".equalsIgnoreCase(cell.getAttribute("header_font_bold")));
excel.setHeaderFontItalic("Y".equalsIgnoreCase(cell.getAttribute("header_font_italic")));
excel.setHeaderFontUnderline(this.getIndex(excel.font_underline_code, cell.getAttribute("header_font_underline")));
excel.setHeaderFontOrientation(this.getIndex(excel.font_orientation_code,cell.getAttribute("header_font_orientation")));
excel.setHeaderFontColor(this.getIndex(excel.font_color_code,cell.getAttribute("header_font_color")));
excel.setHeaderRowHeight(cell.getAttribute("header_row_height"));
excel.setHeaderAlignment(this.getIndex(excel.font_alignment_code, cell.getAttribute("header_alignment")));
excel.setHeaderImage(cell.getAttribute("header_image"));
excel.setRowFontName(this.getIndex(excel.font_name_code,cell.getAttribute("row_font_name")));
excel.setRowFontSize(Const.NVL(cell.getAttribute("row_font_size"), "10"));
excel.setRowFontColor(this.getIndex(excel.font_color_code,cell.getAttribute("row_font_color")));
excel.setRowBackGroundColor(this.getIndex(excel.font_color_code,cell.getAttribute("row_background_color")));
}
@Override
public Element encode(StepMetaInterface stepMetaInterface) throws Exception {
ExcelOutputMeta excel=(ExcelOutputMeta)stepMetaInterface;
Document doc = mxUtils.createDocument();
Element e = doc.createElement(PropsUI.TRANS_STEP_NAME);
e.setAttribute("header", excel.isHeaderEnabled() ? "Y" : "N");
e.setAttribute("footer", excel.isFooterEnabled() ? "Y" : "N");
e.setAttribute("encoding", excel.getEncoding());
e.setAttribute("append", excel.isAppend() ? "Y" : "N");
e.setAttribute("add_to_result_filenames", excel.isAddToResultFiles() ? "Y" : "N");
e.setAttribute("name", excel.getFileName());
e.setAttribute("extention", excel.getExtension());
e.setAttribute("do_not_open_newfile_init", excel.isDoNotOpenNewFileInit() ? "Y" : "N");
e.setAttribute("create_parent_folder", excel.isCreateParentFolder() ? "Y" : "N");
e.setAttribute("split", excel.isStepNrInFilename() ? "Y" : "N");
e.setAttribute("add_date", excel.isDateInFilename() ? "Y" : "N");
e.setAttribute("add_time", excel.isTimeInFilename() ? "Y" : "N");
e.setAttribute("SpecifyFormat", excel.isSpecifyFormat() ? "Y" : "N");
e.setAttribute("date_time_format", excel.getDateTimeFormat());
e.setAttribute("sheetname", excel.getSheetname());
e.setAttribute("autosizecolums", excel.isAutoSizeColums() ? "Y" : "N");
e.setAttribute("nullisblank", excel.isNullBlank() ? "Y" : "N");
e.setAttribute("protect_sheet", excel.isSheetProtected() ? "Y" : "N");
e.setAttribute("password", Encr.encryptPasswordIfNotUsingVariables(excel.getPassword()));
e.setAttribute("splitevery", Integer.valueOf(excel.getSplitEvery()).toString());
e.setAttribute("usetempfiles", excel.isUseTempFiles() ? "Y" : "N");
e.setAttribute("tempdirectory", excel.getTempDirectory());
e.setAttribute("enabled", excel.isTemplateEnabled() ? "Y" : "N");
e.setAttribute("append", excel.isTemplateAppend() ? "Y" : "N");
e.setAttribute("filename", excel.getTemplateFileName());
JSONArray jsonArray = new JSONArray();
ExcelField[] excelFields = excel.getOutputFields();
for(int j=0; j<excelFields.length; j++) {
JSONObject jsonObject = new JSONObject();
ExcelField field = excelFields[j];
jsonObject.put("name", field.getName());
jsonObject.put("type", field.getTypeDesc());
jsonObject.put("format",field.getFormat());
jsonArray.add(jsonObject);
}
e.setAttribute("fields",jsonArray.toString());
e.setAttribute("header_font_name", excel.getHeaderFontName() >= 0 && excel.getHeaderFontName() < excel.font_name_code.length ? excel.font_name_code[excel.getHeaderFontName()] : excel.font_name_code[0]);
e.setAttribute("header_font_size", excel.getHeaderFontSize());
e.setAttribute("header_font_bold", excel.isHeaderFontBold() ? "Y" : "N");
e.setAttribute("header_font_italic", excel.isHeaderFontItalic() ? "Y" : "N");
e.setAttribute("header_font_underline", excel.getHeaderFontUnderline() >= 0 && excel.getHeaderFontUnderline() < excel.font_underline_code.length ? excel.font_underline_code[excel.getHeaderFontUnderline()] : excel.font_underline_code[0]);
e.setAttribute("header_font_orientation", excel.getHeaderFontOrientation() >= 0 && excel.getHeaderFontOrientation() < excel.font_orientation_code.length ? excel.font_orientation_code[excel.getHeaderFontOrientation()] : excel.font_orientation_code[0]);
e.setAttribute("header_font_color", excel.getHeaderFontColor() >= 0 && excel.getHeaderFontColor() < excel.font_color_code.length ? excel.font_color_code[excel.getHeaderFontColor()] : excel.font_color_code[0]);
e.setAttribute("header_background_color", excel.getHeaderBackGroundColor() >= 0 && excel.getHeaderBackGroundColor() < excel.font_color_code.length ? excel.font_color_code[excel.getHeaderBackGroundColor()] : excel.font_color_code[0]);
e.setAttribute("header_row_height", excel.getHeaderRowHeight());
e.setAttribute("header_alignment", excel.getHeaderAlignment() >= 0 && excel.getHeaderAlignment() < excel.font_alignment_code.length ? excel.font_alignment_code[excel.getHeaderAlignment()] : excel.font_alignment_code[0]);
e.setAttribute("header_image", excel.getHeaderImage());
e.setAttribute("row_font_name", excel.getRowFontName() >= 0 && excel.getRowFontName() < excel.font_name_code.length ? excel.font_name_code[excel.getRowFontName()] : excel.font_name_code[0]);
e.setAttribute("row_font_size", excel.getRowFontSize());
e.setAttribute("row_font_color", excel.getRowFontColor() >= 0 && excel.getRowFontColor() < excel.font_color_code.length ? excel.font_color_code[excel.getRowFontColor()] : excel.font_color_code[0]);
e.setAttribute("row_background_color", excel.getRowBackGroundColor()>=0&&excel.getRowBackGroundColor()<excel.font_color_code.length?excel.font_color_code[excel.getRowBackGroundColor()]:excel.font_color_code[0]);
return e;
}
}
|
92436d1c949f6b3d4b155217e398140076e3e8fe
| 4,121 |
java
|
Java
|
airbyte-integrations/connectors/source-mysql/src/test/java/io/airbyte/integrations/source/mysql/MySqlJdbcStandardTest.java
|
TeePublic/airbyte
|
0320b96617779f82d5e5bd44a83f5afffd78a6db
|
[
"MIT"
] | 3 |
2021-09-10T13:29:51.000Z
|
2021-11-17T10:44:43.000Z
|
airbyte-integrations/connectors/source-mysql/src/test/java/io/airbyte/integrations/source/mysql/MySqlJdbcStandardTest.java
|
TeePublic/airbyte
|
0320b96617779f82d5e5bd44a83f5afffd78a6db
|
[
"MIT"
] | 4 |
2021-04-30T08:10:26.000Z
|
2021-04-30T13:53:34.000Z
|
airbyte-integrations/connectors/source-mysql/src/test/java/io/airbyte/integrations/source/mysql/MySqlJdbcStandardTest.java
|
TeePublic/airbyte
|
0320b96617779f82d5e5bd44a83f5afffd78a6db
|
[
"MIT"
] | null | null | null | 32.195313 | 103 | 0.716574 | 1,002,647 |
/*
* MIT License
*
* Copyright (c) 2020 Airbyte
*
* 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 io.airbyte.integrations.source.mysql;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableMap;
import io.airbyte.commons.json.Jsons;
import io.airbyte.db.Database;
import io.airbyte.db.Databases;
import io.airbyte.integrations.source.jdbc.AbstractJdbcSource;
import io.airbyte.integrations.source.jdbc.test.JdbcSourceStandardTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.commons.lang3.RandomStringUtils;
import org.jooq.SQLDialect;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.testcontainers.containers.MySQLContainer;
class MySqlJdbcStandardTest extends JdbcSourceStandardTest {
private static final String TEST_USER = "test";
private static final String TEST_PASSWORD = "test";
private static MySQLContainer<?> container;
private JsonNode config;
private Database database;
@BeforeAll
static void init() throws SQLException {
container = new MySQLContainer<>("mysql:8.0")
.withUsername(TEST_USER)
.withPassword(TEST_PASSWORD)
.withEnv("MYSQL_ROOT_HOST", "%")
.withEnv("MYSQL_ROOT_PASSWORD", TEST_PASSWORD);
container.start();
Connection connection = DriverManager.getConnection(container.getJdbcUrl(), "root", TEST_PASSWORD);
connection.createStatement().execute("GRANT ALL PRIVILEGES ON *.* TO '" + TEST_USER + "'@'%';\n");
}
@BeforeEach
public void setup() throws Exception {
config = Jsons.jsonNode(ImmutableMap.builder()
.put("host", container.getHost())
.put("port", container.getFirstMappedPort())
.put("database", "db_" + RandomStringUtils.randomAlphabetic(10))
.put("username", TEST_USER)
.put("password", TEST_PASSWORD)
.build());
database = Databases.createDatabase(
config.get("username").asText(),
config.get("password").asText(),
String.format("jdbc:mysql://%s:%s",
config.get("host").asText(),
config.get("port").asText()),
MySqlSource.DRIVER_CLASS,
SQLDialect.MYSQL);
database.query(ctx -> {
ctx.fetch("CREATE DATABASE " + config.get("database").asText());
return null;
});
database.close();
super.setup();
}
@AfterEach
void tearDownMySql() throws Exception {
database.close();
super.tearDown();
}
@AfterAll
static void cleanUp() {
container.close();
}
// MySql does not support schemas in the way most dbs do. Instead we namespace by db name.
@Override
public boolean supportsSchemas() {
return false;
}
@Override
public AbstractJdbcSource getSource() {
return new MySqlSource();
}
@Override
public String getDriverClass() {
return MySqlSource.DRIVER_CLASS;
}
@Override
public JsonNode getConfig() {
return Jsons.clone(config);
}
}
|
92436da9373b4f38123e775e2887d7fc6f8e6dbd
| 564 |
java
|
Java
|
239-X-Server/src/main/java/com/minimal/service/front/FrontArticleService.java
|
239-X/239-x-server
|
21130a6c47ce30f7997c58fb56b4da6bae103c97
|
[
"Apache-2.0"
] | 1 |
2021-04-11T04:03:12.000Z
|
2021-04-11T04:03:12.000Z
|
239-X-Server/src/main/java/com/minimal/service/front/FrontArticleService.java
|
239-X/239-x-server
|
21130a6c47ce30f7997c58fb56b4da6bae103c97
|
[
"Apache-2.0"
] | null | null | null |
239-X-Server/src/main/java/com/minimal/service/front/FrontArticleService.java
|
239-X/239-x-server
|
21130a6c47ce30f7997c58fb56b4da6bae103c97
|
[
"Apache-2.0"
] | null | null | null | 16.588235 | 56 | 0.608156 | 1,002,648 |
package com.minimal.service.front;
import com.minimal.common.api.dto.front.FrontArticleDto;
import com.minimal.entity.model.ArticleComment;
/**
* 前端文章服务
*
* @author linzhiqiang
* @date 2021-05-05
*/
public interface FrontArticleService {
/**
* 查询文章列表信息
* @param frontArticleDto
* @return
*/
Object select(FrontArticleDto frontArticleDto);
/**
* 查询文章详情
* @param id
* @return
*/
Object detail(String id);
/**
* 搜索文章标题
* @param key
* @return
*/
Object search(String key);
}
|
92436ee2c5cf43df8e304e107ce3cecf621a2d78
| 625 |
java
|
Java
|
Assignment 2/3.java
|
tanujdey7/CoreJava
|
fa74e1dec25b3dfa4fd5174903ec65c9ed1ab836
|
[
"Unlicense"
] | null | null | null |
Assignment 2/3.java
|
tanujdey7/CoreJava
|
fa74e1dec25b3dfa4fd5174903ec65c9ed1ab836
|
[
"Unlicense"
] | null | null | null |
Assignment 2/3.java
|
tanujdey7/CoreJava
|
fa74e1dec25b3dfa4fd5174903ec65c9ed1ab836
|
[
"Unlicense"
] | null | null | null | 29.761905 | 60 | 0.6192 | 1,002,649 |
import java.util.Scanner;
class demo {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter num 1: ");
int num1=input.nextInt();
System.out.print("Enter num 2: ");
int num2=input.nextInt();
System.out.print("Enter num 3: ");
int num3=input.nextInt();
if(num1>num2 && num1>num3) {
System.out.print("Num 1 is greater than Num 2 & Num 3");
}
if(num2>num1 && num2>num3) {
System.out.print("Num 2 is greater than Num 1 & Num 3");
}
if(num3>num1 && num3>num2) {
System.out.print("Num 3 is greater than Num 1 & Num 2");
}
}
}
|
92436f4ee16cc3891c4d7240d944085e86b19123
| 4,171 |
java
|
Java
|
shared/health/src/main/java/io/pravega/shared/health/impl/HealthServiceUpdaterImpl.java
|
shshashwat/pravega
|
f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6
|
[
"Apache-2.0"
] | 1,840 |
2017-05-10T16:29:14.000Z
|
2022-03-31T07:02:11.000Z
|
shared/health/src/main/java/io/pravega/shared/health/impl/HealthServiceUpdaterImpl.java
|
shshashwat/pravega
|
f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6
|
[
"Apache-2.0"
] | 5,485 |
2017-05-10T16:56:17.000Z
|
2022-03-31T14:08:36.000Z
|
shared/health/src/main/java/io/pravega/shared/health/impl/HealthServiceUpdaterImpl.java
|
shshashwat/pravega
|
f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6
|
[
"Apache-2.0"
] | 443 |
2017-05-10T21:34:50.000Z
|
2022-03-31T07:02:14.000Z
| 34.758333 | 157 | 0.713018 | 1,002,650 |
/**
* Copyright Pravega Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pravega.shared.health.impl;
import com.google.common.util.concurrent.AbstractScheduledService;
import io.pravega.common.concurrent.ExecutorServiceHelpers;
import io.pravega.common.concurrent.Futures;
import io.pravega.common.concurrent.Services;
import io.pravega.shared.health.Health;
import io.pravega.shared.health.HealthContributor;
import io.pravega.shared.health.HealthServiceUpdater;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
@Slf4j
@RequiredArgsConstructor
public class HealthServiceUpdaterImpl extends AbstractScheduledService implements HealthServiceUpdater {
/**
* The {@link Health} the daemon should report in the case it has not started querying the {@link io.pravega.shared.health.HealthServiceManager}.
*/
private static final Health INITIAL_HEALTH = Health.builder().build();
/**
* Represents the most recent {@link Health} information provided by the {@link ScheduledExecutorService}.
*/
private final AtomicReference<Health> latest = new AtomicReference<Health>(INITIAL_HEALTH);
/**
* The {@link io.pravega.shared.health.HealthServiceManager} associated with this {@link HealthServiceUpdater}.
*/
private final HealthContributor root;
/**
* The interval at which to run the health check.
*/
@Getter
private final Duration interval;
/**
* The underlying {@link ScheduledExecutorService} used to executor the recurring service-level {@link Health} check.
*/
private final ScheduledExecutorService executorService = ExecutorServiceHelpers.newScheduledThreadPool(1, "health-service-updater", Thread.MIN_PRIORITY);
/**
* Provides the latest {@link Health} result of the recurring {@link io.pravega.shared.health.HealthEndpoint#getHealth()} calls.
* @return The latest {@link Health} result.
*/
@Override
public Health getLatestHealth() {
return latest.get();
}
@Override
protected ScheduledExecutorService executor() {
return this.executorService;
}
@Override
protected void runOneIteration() {
latest.set(root.getHealthSnapshot());
}
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedDelaySchedule(interval, interval);
}
/**
* Starts the underlying {@link ScheduledExecutorService} to repeatedly call {@link io.pravega.shared.health.HealthEndpoint#getHealth()}.
*/
@Override
protected void startUp() {
log.info("Starting the HealthServiceUpdater, running at {} intervals.", interval);
}
/**
* Permanently shuts down the {@link HealthServiceUpdater}'s {@link ScheduledExecutorService}. It will not be able to be restarted.
*
*/
@Override
protected void shutDown() {
log.info("Shutting down the HealthServiceUpdater.");
latest.set(INITIAL_HEALTH);
}
/**
* A {@link HealthServiceUpdater} is only reachable though a {@link io.pravega.shared.health.HealthServiceManager}.
*/
@Override
public void close() {
if (isRunning()) {
shutDown();
}
if (state() == State.RUNNING) {
Futures.await(Services.stopAsync(this, this.executorService));
}
log.info("Stopping ScheduledExecutorService.");
ExecutorServiceHelpers.shutdown(Duration.ofSeconds(5), executorService);
}
}
|
92436f7079c2961bdb817093bf30f67351bc145f
| 4,988 |
java
|
Java
|
parsley-toolbox/src/main/java/org/spicefactory/parsley/view/Configure.java
|
sylvainlecoy/parsley-core
|
db7ccd9c581d2a231e330875614748a47b34f119
|
[
"Apache-2.0"
] | null | null | null |
parsley-toolbox/src/main/java/org/spicefactory/parsley/view/Configure.java
|
sylvainlecoy/parsley-core
|
db7ccd9c581d2a231e330875614748a47b34f119
|
[
"Apache-2.0"
] | null | null | null |
parsley-toolbox/src/main/java/org/spicefactory/parsley/view/Configure.java
|
sylvainlecoy/parsley-core
|
db7ccd9c581d2a231e330875614748a47b34f119
|
[
"Apache-2.0"
] | null | null | null | 36.217391 | 142 | 0.758703 | 1,002,651 |
package org.spicefactory.parsley.view;
import java.awt.Component;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spicefactory.parsley.core.events.ViewConfigurationEvent;
import org.spicefactory.parsley.core.view.ViewConfiguration;
import org.spicefactory.parsley.core.view.ViewConfiguration.CompleteHandler;
import org.spicefactory.parsley.core.view.ViewProcessor;
/**
* Provides a fluent API for configuring a target in a view.
* <p>
* This API can be used in Java components (JavaFX or Swing) as an alternative to the <code>Configure</code> FXML tag for FXML components.
* @author Sylvain Lecoy <[email protected]>
*/
public final class Configure implements HierarchyListener {
private final Logger logger = LoggerFactory.getLogger(Configure.class);
/**
* The view that demarcates the life-cycle of the target instance to be configured.
* <p>
* The view may be the same instance as the target itself or a different one that just controls the life-cycle. A typical example for the two
* properties pointing to different instances would be the target being a presentation model that should get added to the Context for the
* time the view it belongs to is on the stage.
* @param view the view that demarcates the life-cycle of the target instance
* @return a new Configure instance for further setup options
*/
public static Configure view(Component view) {
return new Configure(view);
}
/**
* The target to get processed by the nearest Context in the view hierarchy.
* @param target the target to get processed by the nearest Context in the view hierarchy
* @return this Configure instance for method chaining
*/
public Configure target(Object target) {
this.target = target;
return this;
}
/**
* Indicates whether the target instance will be reused in subsequent life-cycles of the view. When set to false the configuration will only
* be processed once. This value should be true if the application keeps instances of the view in memory and adds them back to the stage
* later. It should be false if the view will get garbage collected once it has been removed from the stage.
* @param value indicates whether the target instance will be reused in subsequent life-cycles of the view
* @return this Configure instance for method chaining
*/
public Configure reuse(boolean value) {
this.reuse = value;
return this;
}
/**
* Indicates whether the target should be removed when the view is removed from the stage. Only has effect when no custom
* <code>ViewLifecycle</code> has been set.
* @param value indicates whether the target instance will be reused in subsequent life-cycles of the view
* @return this Configure instance for method chaining
*/
public Configure autoremove(boolean value) {
this.autoremove = value;
return this;
}
/**
* The configuration id to use to look up an object definition matching this target instance. If a definition has already been set for this
* configuration instance, this value will be ignored.
* @param configId the configuration id to use to look up an object definition matching this target instance
* @return this Configure instance for method chaining
*/
public Configure configId(String configId) {
this.configId = configId;
return this;
}
/**
* A callback to invoke when the processing of the view configuration has been completed.
* @param callback a callback to invoke when the processing of the view configuration has been completed
* @return this Configure instance for method chaining
*/
public Configure complete(CompleteHandler callback) {
this.completeHandler = callback;
return this;
}
/**
* Executes this view configuration at the nearest Context in the view hierarchy.
*/
public void execute() {
if (view.getParent() == null) {
view.addHierarchyListener(this);
} else {
dispatchEvent();
}
}
@Override
public void hierarchyChanged(HierarchyEvent evt) {
if ((evt.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) {
view.removeHierarchyListener(this);
dispatchEvent();
}
}
private void dispatchEvent() {
ViewConfiguration config = new ViewConfiguration(view, target, configId);
config.reuse = reuse;
config.autoremove = autoremove;
config.processor = processor;
ViewConfigurationEvent event = ViewConfigurationEvent.forConfigurations(new ViewConfiguration[] {config}, completeHandler);
view.dispatchEvent(event);
if (!event.received()) {
logger.warn("View configuration could not be processed for target {}: no Context found in view hierarchy.", config.target);
}
}
private final Component view;
private Object target;
private boolean reuse;
private boolean autoremove;
private ViewProcessor processor;
private String configId;
private CompleteHandler completeHandler;
// Private
private Configure(Component view) {
this.view = view;
}
}
|
924372387940aaf51f8c8e1d3341128684848557
| 14,461 |
java
|
Java
|
2A/S7/IDM/TP/TP7/fr.n7.pdl2.ui/src-gen/fr/n7/ui/AbstractPDL2UiModule.java
|
MOUDDENEHamza/ENSEEIHT
|
a90b1dee0c8d18a9578153a357278d99405bb534
|
[
"Apache-2.0"
] | 4 |
2020-05-02T12:32:32.000Z
|
2022-01-12T20:20:35.000Z
|
2A/S7/IDM/TP/TP7/fr.n7.pdl2.ui/src-gen/fr/n7/ui/AbstractPDL2UiModule.java
|
MOUDDENEHamza/ENSEEIHT
|
a90b1dee0c8d18a9578153a357278d99405bb534
|
[
"Apache-2.0"
] | 2 |
2021-01-14T20:03:26.000Z
|
2022-01-30T01:10:00.000Z
|
2A/S7/IDM/TP/TP7/fr.n7.pdl2.ui/src-gen/fr/n7/ui/AbstractPDL2UiModule.java
|
MOUDDENEHamza/ENSEEIHT
|
a90b1dee0c8d18a9578153a357278d99405bb534
|
[
"Apache-2.0"
] | 13 |
2020-11-11T21:28:11.000Z
|
2022-02-19T13:54:22.000Z
| 49.187075 | 167 | 0.842127 | 1,002,652 |
/*
* generated by Xtext 2.17.1
*/
package fr.n7.ui;
import com.google.inject.Binder;
import com.google.inject.Provider;
import com.google.inject.name.Names;
import fr.n7.ide.contentassist.antlr.PDL2Parser;
import fr.n7.ide.contentassist.antlr.PartialPDL2ContentAssistParser;
import fr.n7.ide.contentassist.antlr.internal.InternalPDL2Lexer;
import fr.n7.ui.contentassist.PDL2ProposalProvider;
import fr.n7.ui.labeling.PDL2DescriptionLabelProvider;
import fr.n7.ui.labeling.PDL2LabelProvider;
import fr.n7.ui.outline.PDL2OutlineTreeProvider;
import fr.n7.ui.quickfix.PDL2QuickfixProvider;
import fr.n7.validation.PDL2ValidatorConfigurationBlock;
import org.eclipse.compare.IViewerCreator;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.xtext.builder.BuilderParticipant;
import org.eclipse.xtext.builder.EclipseOutputConfigurationProvider;
import org.eclipse.xtext.builder.IXtextBuilderParticipant;
import org.eclipse.xtext.builder.builderState.IBuilderState;
import org.eclipse.xtext.builder.clustering.CurrentDescriptions;
import org.eclipse.xtext.builder.impl.PersistentDataAwareDirtyResource;
import org.eclipse.xtext.builder.nature.NatureAddingEditorCallback;
import org.eclipse.xtext.builder.preferences.BuilderPreferenceAccess;
import org.eclipse.xtext.generator.IContextualOutputConfigurationProvider;
import org.eclipse.xtext.ide.LexerIdeBindings;
import org.eclipse.xtext.ide.editor.contentassist.antlr.IContentAssistParser;
import org.eclipse.xtext.ide.editor.contentassist.antlr.internal.Lexer;
import org.eclipse.xtext.ide.editor.partialEditing.IPartialEditingContentAssistParser;
import org.eclipse.xtext.parser.antlr.AntlrTokenDefProvider;
import org.eclipse.xtext.parser.antlr.ITokenDefProvider;
import org.eclipse.xtext.parser.antlr.LexerProvider;
import org.eclipse.xtext.resource.IResourceDescriptions;
import org.eclipse.xtext.resource.containers.IAllContainersState;
import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider;
import org.eclipse.xtext.service.SingletonBinding;
import org.eclipse.xtext.ui.DefaultUiModule;
import org.eclipse.xtext.ui.UIBindings;
import org.eclipse.xtext.ui.codetemplates.ui.AccessibleCodetemplatesActivator;
import org.eclipse.xtext.ui.codetemplates.ui.partialEditing.IPartialEditingContentAssistContextFactory;
import org.eclipse.xtext.ui.codetemplates.ui.partialEditing.PartialEditingContentAssistContextFactory;
import org.eclipse.xtext.ui.codetemplates.ui.preferences.AdvancedTemplatesPreferencePage;
import org.eclipse.xtext.ui.codetemplates.ui.preferences.TemplatesLanguageConfiguration;
import org.eclipse.xtext.ui.codetemplates.ui.registry.LanguageRegistrar;
import org.eclipse.xtext.ui.codetemplates.ui.registry.LanguageRegistry;
import org.eclipse.xtext.ui.compare.DefaultViewerCreator;
import org.eclipse.xtext.ui.editor.DocumentBasedDirtyResource;
import org.eclipse.xtext.ui.editor.IXtextEditorCallback;
import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext;
import org.eclipse.xtext.ui.editor.contentassist.FQNPrefixMatcher;
import org.eclipse.xtext.ui.editor.contentassist.IContentProposalProvider;
import org.eclipse.xtext.ui.editor.contentassist.IProposalConflictHelper;
import org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher;
import org.eclipse.xtext.ui.editor.contentassist.antlr.AntlrProposalConflictHelper;
import org.eclipse.xtext.ui.editor.contentassist.antlr.DelegatingContentAssistContextFactory;
import org.eclipse.xtext.ui.editor.outline.IOutlineTreeProvider;
import org.eclipse.xtext.ui.editor.outline.impl.IOutlineTreeStructureProvider;
import org.eclipse.xtext.ui.editor.preferences.IPreferenceStoreInitializer;
import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionProvider;
import org.eclipse.xtext.ui.editor.templates.XtextTemplatePreferencePage;
import org.eclipse.xtext.ui.refactoring.IDependentElementsCalculator;
import org.eclipse.xtext.ui.refactoring.IReferenceUpdater;
import org.eclipse.xtext.ui.refactoring.IRenameRefactoringProvider;
import org.eclipse.xtext.ui.refactoring.IRenameStrategy;
import org.eclipse.xtext.ui.refactoring.impl.DefaultDependentElementsCalculator;
import org.eclipse.xtext.ui.refactoring.impl.DefaultReferenceUpdater;
import org.eclipse.xtext.ui.refactoring.impl.DefaultRenameRefactoringProvider;
import org.eclipse.xtext.ui.refactoring.impl.DefaultRenameStrategy;
import org.eclipse.xtext.ui.refactoring.ui.DefaultRenameSupport;
import org.eclipse.xtext.ui.refactoring.ui.IRenameSupport;
import org.eclipse.xtext.ui.refactoring.ui.RefactoringPreferences;
import org.eclipse.xtext.ui.resource.ResourceServiceDescriptionLabelProvider;
import org.eclipse.xtext.ui.shared.Access;
import org.eclipse.xtext.ui.validation.AbstractValidatorConfigurationBlock;
/**
* Manual modifications go to {@link PDL2UiModule}.
*/
@SuppressWarnings("all")
public abstract class AbstractPDL2UiModule extends DefaultUiModule {
public AbstractPDL2UiModule(AbstractUIPlugin plugin) {
super(plugin);
}
// contributed by org.eclipse.xtext.xtext.generator.ImplicitFragment
public Provider<? extends IAllContainersState> provideIAllContainersState() {
return Access.getJavaProjectsState();
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends IProposalConflictHelper> bindIProposalConflictHelper() {
return AntlrProposalConflictHelper.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureContentAssistLexer(Binder binder) {
binder.bind(Lexer.class)
.annotatedWith(Names.named(LexerIdeBindings.CONTENT_ASSIST))
.to(InternalPDL2Lexer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureHighlightingLexer(Binder binder) {
binder.bind(org.eclipse.xtext.parser.antlr.Lexer.class)
.annotatedWith(Names.named(LexerIdeBindings.HIGHLIGHTING))
.to(fr.n7.parser.antlr.internal.InternalPDL2Lexer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureHighlightingTokenDefProvider(Binder binder) {
binder.bind(ITokenDefProvider.class)
.annotatedWith(Names.named(LexerIdeBindings.HIGHLIGHTING))
.to(AntlrTokenDefProvider.class);
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends ContentAssistContext.Factory> bindContentAssistContext$Factory() {
return DelegatingContentAssistContextFactory.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends IContentAssistParser> bindIContentAssistParser() {
return PDL2Parser.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureContentAssistLexerProvider(Binder binder) {
binder.bind(InternalPDL2Lexer.class).toProvider(LexerProvider.create(InternalPDL2Lexer.class));
}
// contributed by org.eclipse.xtext.xtext.generator.validation.ValidatorFragment2
public Class<? extends AbstractValidatorConfigurationBlock> bindAbstractValidatorConfigurationBlock() {
return PDL2ValidatorConfigurationBlock.class;
}
// contributed by org.eclipse.xtext.xtext.generator.exporting.QualifiedNamesFragment2
public Class<? extends PrefixMatcher> bindPrefixMatcher() {
return FQNPrefixMatcher.class;
}
// contributed by org.eclipse.xtext.xtext.generator.exporting.QualifiedNamesFragment2
public Class<? extends IDependentElementsCalculator> bindIDependentElementsCalculator() {
return DefaultDependentElementsCalculator.class;
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public void configureIResourceDescriptionsBuilderScope(Binder binder) {
binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.NAMED_BUILDER_SCOPE)).to(CurrentDescriptions.ResourceSetAware.class);
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public Class<? extends IXtextEditorCallback> bindIXtextEditorCallback() {
return NatureAddingEditorCallback.class;
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public Class<? extends IContextualOutputConfigurationProvider> bindIContextualOutputConfigurationProvider() {
return EclipseOutputConfigurationProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public void configureIResourceDescriptionsPersisted(Binder binder) {
binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(IBuilderState.class);
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public Class<? extends DocumentBasedDirtyResource> bindDocumentBasedDirtyResource() {
return PersistentDataAwareDirtyResource.class;
}
// contributed by org.eclipse.xtext.xtext.generator.generator.GeneratorFragment2
public Class<? extends IXtextBuilderParticipant> bindIXtextBuilderParticipant() {
return BuilderParticipant.class;
}
// contributed by org.eclipse.xtext.xtext.generator.generator.GeneratorFragment2
public IWorkspaceRoot bindIWorkspaceRootToInstance() {
return ResourcesPlugin.getWorkspace().getRoot();
}
// contributed by org.eclipse.xtext.xtext.generator.generator.GeneratorFragment2
public void configureBuilderPreferenceStoreInitializer(Binder binder) {
binder.bind(IPreferenceStoreInitializer.class)
.annotatedWith(Names.named("builderPreferenceInitializer"))
.to(BuilderPreferenceAccess.Initializer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.ui.labeling.LabelProviderFragment2
public Class<? extends ILabelProvider> bindILabelProvider() {
return PDL2LabelProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.labeling.LabelProviderFragment2
public void configureResourceUIServiceLabelProvider(Binder binder) {
binder.bind(ILabelProvider.class).annotatedWith(ResourceServiceDescriptionLabelProvider.class).to(PDL2DescriptionLabelProvider.class);
}
// contributed by org.eclipse.xtext.xtext.generator.ui.outline.OutlineTreeProviderFragment2
public Class<? extends IOutlineTreeProvider> bindIOutlineTreeProvider() {
return PDL2OutlineTreeProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.outline.OutlineTreeProviderFragment2
public Class<? extends IOutlineTreeStructureProvider> bindIOutlineTreeStructureProvider() {
return PDL2OutlineTreeProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.quickfix.QuickfixProviderFragment2
public Class<? extends IssueResolutionProvider> bindIssueResolutionProvider() {
return PDL2QuickfixProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.contentAssist.ContentAssistFragment2
public Class<? extends IContentProposalProvider> bindIContentProposalProvider() {
return PDL2ProposalProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public void configureIPreferenceStoreInitializer(Binder binder) {
binder.bind(IPreferenceStoreInitializer.class)
.annotatedWith(Names.named("RefactoringPreferences"))
.to(RefactoringPreferences.Initializer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public Class<? extends IRenameStrategy> bindIRenameStrategy() {
return DefaultRenameStrategy.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public Class<? extends IReferenceUpdater> bindIReferenceUpdater() {
return DefaultReferenceUpdater.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public Class<? extends IRenameRefactoringProvider> bindIRenameRefactoringProvider() {
return DefaultRenameRefactoringProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public Class<? extends IRenameSupport.Factory> bindIRenameSupport$Factory() {
return DefaultRenameSupport.Factory.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Provider<? extends TemplatesLanguageConfiguration> provideTemplatesLanguageConfiguration() {
return AccessibleCodetemplatesActivator.getTemplatesLanguageConfigurationProvider();
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Provider<? extends LanguageRegistry> provideLanguageRegistry() {
return AccessibleCodetemplatesActivator.getLanguageRegistry();
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
@SingletonBinding(eager=true)
public Class<? extends LanguageRegistrar> bindLanguageRegistrar() {
return LanguageRegistrar.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Class<? extends XtextTemplatePreferencePage> bindXtextTemplatePreferencePage() {
return AdvancedTemplatesPreferencePage.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Class<? extends IPartialEditingContentAssistParser> bindIPartialEditingContentAssistParser() {
return PartialPDL2ContentAssistParser.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Class<? extends IPartialEditingContentAssistContextFactory> bindIPartialEditingContentAssistContextFactory() {
return PartialEditingContentAssistContextFactory.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.compare.CompareFragment2
public Class<? extends IViewerCreator> bindIViewerCreator() {
return DefaultViewerCreator.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.compare.CompareFragment2
public void configureCompareViewerTitle(Binder binder) {
binder.bind(String.class).annotatedWith(Names.named(UIBindings.COMPARE_VIEWER_TITLE)).toInstance("PDL2 Compare");
}
}
|
924372d685b75cddadd479ff357519ae7298351a
| 4,211 |
java
|
Java
|
nutzfw-common/src/main/java/com/nutzfw/core/common/util/SCaptchaUtil.java
|
threefish/NutzFw
|
0c74504af4dca4ac72d7db786f74dfa7fae16250
|
[
"Apache-2.0"
] | 131 |
2019-02-15T06:18:09.000Z
|
2022-03-08T06:06:07.000Z
|
nutzfw-common/src/main/java/com/nutzfw/core/common/util/SCaptchaUtil.java
|
youfuu/NutzFw
|
a07ff74798cf9504dbd317ff683a75bc55f507d1
|
[
"Apache-2.0"
] | 1 |
2020-10-03T09:31:56.000Z
|
2021-02-19T01:19:54.000Z
|
nutzfw-common/src/main/java/com/nutzfw/core/common/util/SCaptchaUtil.java
|
threefish/NutzFw
|
0c74504af4dca4ac72d7db786f74dfa7fae16250
|
[
"Apache-2.0"
] | 47 |
2019-08-27T19:17:08.000Z
|
2022-03-20T09:02:20.000Z
| 26.484277 | 116 | 0.547613 | 1,002,653 |
/*
* Copyright (c) 2019- 2019 threefish(https://gitee.com/threefish https://github.com/threefish) All Rights Reserved.
* 本项目完全开源,商用完全免费。但请勿侵犯作者合法权益,如申请软著等。
* 最后修改时间:2019/10/07 18:32:07
* 源 码 地 址:https://gitee.com/threefish/NutzFw
*/
package com.nutzfw.core.common.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.ThreadLocalRandom;
/**
* 验证码生成器
*/
public class SCaptchaUtil {
// 图片的宽度。
private int width = 120;
// 图片的高度。
private int height = 40;
// 验证码字符个数
private int codeCount = 4;
// 验证码干扰线数
private int lineCount = 50;
// 验证码
private String code = null;
// 验证码图片Buffer
private BufferedImage buffImg = null;
private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
// 生成随机数
private ThreadLocalRandom random = ThreadLocalRandom.current();
public SCaptchaUtil() {
this.createCode();
}
/**
* @param width 图片宽
* @param height 图片高
*/
public SCaptchaUtil(int width, int height) {
this.width = width;
this.height = height;
this.createCode();
}
/**
* @param width 图片宽
* @param height 图片高
*/
public SCaptchaUtil(int width, int height, char[] codeSequence) {
this.width = width;
this.height = height;
this.codeSequence = codeSequence;
this.createCode();
}
/**
* @param width 图片宽
* @param height 图片高
* @param codeCount 字符个数
* @param lineCount 干扰线条数
*/
public SCaptchaUtil(int width, int height, int codeCount, int lineCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
this.createCode();
}
public void createCode() {
// 字体的高度
int fontHeight = height - 10;
// 每个字符的宽度
int codeX = width / (codeCount + 2);
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 创建字体
Font font = ImgUtil.getFont(fontHeight);
g.setFont(font);
// 绘制干扰线
for (int i = 0; i < lineCount; i++) {
int xs = getRandomNumber(width);
int ys = getRandomNumber(height);
int xe = xs + getRandomNumber(width / 8);
int ye = ys + getRandomNumber(height / 8);
g.setColor(getRandomColor());
g.drawLine(xs, ys, xe, ye);
}
StringBuffer randomCode = new StringBuffer();
// 随机产生验证码字符
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random
.nextInt(codeSequence.length)]);
// 设置字体颜色
g.setColor(getRandomColor());
// 设置字体位置
g.drawString(strRand, (i + 1) * codeX,
getRandomNumber(height / 2) + 30);
randomCode.append(strRand);
}
code = randomCode.toString();
}
/**
* 获取随机颜色
*/
private Color getRandomColor() {
int r = getRandomNumber(255);
int g = getRandomNumber(255);
int b = getRandomNumber(255);
return new Color(r, g, b);
}
/**
* 获取随机数
*/
private int getRandomNumber(int number) {
return random.nextInt(number);
}
public void write(String path) throws IOException {
this.write(new FileOutputStream(path));
}
public void write(OutputStream sos) throws IOException {
ImageIO.write(buffImg, "png", sos);
sos.close();
}
public BufferedImage getBuffImg() {
return buffImg;
}
public String getCode() {
return code;
}
}
|
92437387893453dd89f1b27897a21701b3d12214
| 4,843 |
java
|
Java
|
src/main/java/info/novatec/beantest/extension/InjectionHelper.java
|
NovaTecConsulting/BeanTest
|
667755b009f26fe1e7bb658e5c99139348777fee
|
[
"Apache-2.0"
] | 19 |
2015-02-14T09:32:03.000Z
|
2018-04-09T18:45:31.000Z
|
src/main/java/info/novatec/beantest/extension/InjectionHelper.java
|
NovatecConsulting/BeanTest
|
667755b009f26fe1e7bb658e5c99139348777fee
|
[
"Apache-2.0"
] | 20 |
2015-01-14T09:17:37.000Z
|
2016-12-16T11:30:11.000Z
|
src/main/java/info/novatec/beantest/extension/InjectionHelper.java
|
NovaTecConsulting/BeanTest
|
667755b009f26fe1e7bb658e5c99139348777fee
|
[
"Apache-2.0"
] | 11 |
2015-01-28T14:39:53.000Z
|
2017-01-11T14:33:58.000Z
| 40.475 | 168 | 0.677785 | 1,002,654 |
/*
* Bean Testing.
*
* 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 info.novatec.beantest.extension;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMember;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.inject.Inject;
import javax.persistence.PersistenceContext;
import org.apache.deltaspike.core.util.metadata.builder.AnnotatedTypeBuilder;
/**
* This class provides general convenience methods for injection and validation.
*
* @author Carlos Barragan ([email protected])
*/
public final class InjectionHelper {
private static final Set<Class<? extends Annotation>> JAVA_EE_ANNOTATIONS = createJavaEEAnnotationSet();
private static Set<Class<? extends Annotation>> createJavaEEAnnotationSet() {
Set<Class<? extends Annotation>> javaEEAnnotations = new HashSet<Class<? extends Annotation>>();
javaEEAnnotations.add(Resource.class);
javaEEAnnotations.add(EJB.class);
javaEEAnnotations.add(PersistenceContext.class);
return Collections.unmodifiableSet(javaEEAnnotations);
}
private InjectionHelper() {
// Empty on purpose.
}
/**
* Returns <code>true</code> if the member is NOT annotated with {@link Inject} and is annotated with one of the following annotations:
* <ul>
* <li> {@link EJB}
* <li> {@link PersistenceContext}
* <li> {@link Resource}
* </ul>
* Otherwise, it returns <code>false</code>.
*
* @param <X>
* the type of the annotated member
* @param member
* the annotated member whose annotations should be verified.
* @return <code>true</code> if the member is NOT annotated with {@link Inject} and is annotated with {@link EJB},
* {@link PersistenceContext} or {@link Resource}
*/
public static <X> boolean shouldInjectionAnnotationBeAddedToMember(AnnotatedMember<? super X> member) {
return !member.isAnnotationPresent(Inject.class) && hasJavaEEAnnotations(member);
}
/**
* Returns <code>true</code> if at least one of the following Java EE annotations is present in the given member:
* <ul>
* <li> {@link EJB}
* <li> {@link PersistenceContext}
* <li> {@link Resource}
* </ul>
* Otherwise, it returns <code>false</code>.
* @param <X> the type of the annotated member.
* @param member the member whose annotations should be verified.
* @return <code>true</code> if the member is at least annotated with one of the following annotations: {@link EJB}, {@link PersistenceContext} or {@link Resource}.
*/
private static <X> boolean hasJavaEEAnnotations(AnnotatedMember<? super X> member) {
for(Class<? extends Annotation> javaEEannotation : JAVA_EE_ANNOTATIONS) {
if (member.isAnnotationPresent(javaEEannotation)) {
return true;
}
}
return false;
}
/**
* Adds the {@link Inject} annotation to the fields and setters of the annotated type if required.
*
* @param <X>
* the type of the annotated type
* @param annotatedType
* the annotated type whose fields and setters the inject annotation should be added to
* @param builder
* the builder that should be used to add the annotation.
* @see #shouldInjectionAnnotationBeAddedToMember(AnnotatedMember)
*/
public static <X> void addInjectAnnotation(final AnnotatedType<X> annotatedType, AnnotatedTypeBuilder<X> builder) {
for (AnnotatedField<? super X> field : annotatedType.getFields()) {
if (shouldInjectionAnnotationBeAddedToMember(field)) {
builder.addToField(field, AnnotationInstances.INJECT);
}
}
for (AnnotatedMethod<? super X> method : annotatedType.getMethods()) {
if (shouldInjectionAnnotationBeAddedToMember(method)) {
builder.addToMethod(method, AnnotationInstances.INJECT);
}
}
}
}
|
9243740f2248d7a15bfbf1eec03dd98682c34e98
| 846 |
java
|
Java
|
src/main/java/com/alibaba/tamper/core/introspect/ThisSymbolGetExecutor.java
|
huangchengmin97/tamper
|
cdfbbb2957db80fd333d0002c5da04ceebc4cfb0
|
[
"Apache-2.0"
] | 221 |
2015-01-23T06:57:37.000Z
|
2022-03-15T13:48:31.000Z
|
src/main/java/com/alibaba/tamper/core/introspect/ThisSymbolGetExecutor.java
|
huangchengmin97/tamper
|
cdfbbb2957db80fd333d0002c5da04ceebc4cfb0
|
[
"Apache-2.0"
] | 12 |
2016-03-18T15:04:57.000Z
|
2020-10-23T01:08:23.000Z
|
src/main/java/com/alibaba/tamper/core/introspect/ThisSymbolGetExecutor.java
|
huangchengmin97/tamper
|
cdfbbb2957db80fd333d0002c5da04ceebc4cfb0
|
[
"Apache-2.0"
] | 101 |
2015-04-18T12:05:48.000Z
|
2022-01-14T13:13:57.000Z
| 22.864865 | 84 | 0.661939 | 1,002,655 |
package com.alibaba.tamper.core.introspect;
import com.alibaba.tamper.core.BeanMappingException;
/**
* 处理下特殊符号的get操作,比如针对"this"返回当前对象的引用
*
* @author jianghang 2011-6-27 下午07:58:25
*/
public class ThisSymbolGetExecutor extends AbstractExecutor implements GetExecutor {
private boolean flag = false;
public ThisSymbolGetExecutor(Introspector is, Class<?> clazz, String key){
super(clazz, key);
flag = discover(property);
}
@Override
public Object invoke(Object obj) throws BeanMappingException {
if (flag) {
return obj;
}
throw new BeanMappingException("error flag");
}
public static boolean discover(String key) {
return "this".equalsIgnoreCase(key) ? true : false;
}
@Override
public boolean isAlive() {
return flag;
}
}
|
9243743b8c9789a951408aff91618eb069071ff2
| 462 |
java
|
Java
|
src/main/java/app/lifeni/bms/service/StudentService.java
|
Lifeni/boring-management-system
|
498e616afb82995991f16371c3d2ca7644851696
|
[
"MIT"
] | 2 |
2021-07-30T06:24:03.000Z
|
2021-12-10T02:15:11.000Z
|
src/main/java/app/lifeni/bms/service/StudentService.java
|
Lifeni/boring-management-system
|
498e616afb82995991f16371c3d2ca7644851696
|
[
"MIT"
] | null | null | null |
src/main/java/app/lifeni/bms/service/StudentService.java
|
Lifeni/boring-management-system
|
498e616afb82995991f16371c3d2ca7644851696
|
[
"MIT"
] | null | null | null | 25.666667 | 65 | 0.796537 | 1,002,656 |
package app.lifeni.bms.service;
import app.lifeni.bms.entity.api.request.EditStudentRequest;
import app.lifeni.bms.entity.api.response.StudentInfoResponse;
import app.lifeni.bms.entity.model.Student;
import java.util.List;
public interface StudentService {
List<StudentInfoResponse> queryAllStudents();
boolean addStudent(Student student);
boolean editStudent(long userId, EditStudentRequest payload);
boolean removeStudent(long userId);
}
|
9243745f01abc645f6efbc74ad583a1e07b29c14
| 82 |
java
|
Java
|
mdd-core/src/main/java/io/mateu/bpm/sample/SampleProcessSate.java
|
tone-ok/mateu-mdd
|
af33f1e0fede5ba294966c965e890435cc20652e
|
[
"Beerware"
] | 41 |
2018-06-28T09:07:19.000Z
|
2022-01-20T15:09:04.000Z
|
mdd-core/src/main/java/io/mateu/bpm/sample/SampleProcessSate.java
|
tone-ok/mateu-mdd
|
af33f1e0fede5ba294966c965e890435cc20652e
|
[
"Beerware"
] | 49 |
2018-11-13T16:45:47.000Z
|
2022-03-31T19:30:48.000Z
|
mdd-core/src/main/java/io/mateu/bpm/sample/SampleProcessSate.java
|
tone-ok/mateu-mdd
|
af33f1e0fede5ba294966c965e890435cc20652e
|
[
"Beerware"
] | 14 |
2018-01-01T10:21:37.000Z
|
2022-03-12T19:25:20.000Z
| 11.714286 | 31 | 0.731707 | 1,002,657 |
package io.mateu.bpm.sample;
public enum SampleProcessSate {
INITIAL, END
}
|
9243752d08da513e286c03743480d473ebdc99d7
| 3,149 |
java
|
Java
|
src/com/facebook/buck/core/select/impl/UnconfiguredSelectorListResolver.java
|
FightJames/buck
|
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
|
[
"Apache-2.0"
] | 8,027 |
2015-01-02T05:31:44.000Z
|
2022-03-31T07:08:09.000Z
|
src/com/facebook/buck/core/select/impl/UnconfiguredSelectorListResolver.java
|
FightJames/buck
|
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
|
[
"Apache-2.0"
] | 2,355 |
2015-01-01T15:30:53.000Z
|
2022-03-30T20:21:16.000Z
|
src/com/facebook/buck/core/select/impl/UnconfiguredSelectorListResolver.java
|
FightJames/buck
|
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
|
[
"Apache-2.0"
] | 1,280 |
2015-01-09T03:29:04.000Z
|
2022-03-30T15:14:14.000Z
| 36.616279 | 95 | 0.760876 | 1,002,658 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.core.select.impl;
import com.facebook.buck.core.exceptions.DependencyStack;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.select.AbstractSelectorListResolver;
import com.facebook.buck.core.select.Selectable;
import com.facebook.buck.core.select.SelectableConfigurationContext;
import com.facebook.buck.core.select.SelectableResolver;
import com.facebook.buck.core.select.Selector;
import com.facebook.buck.core.select.SelectorKey;
import com.facebook.buck.core.select.SelectorListResolver;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A {@link SelectorListResolver} which handles selectors differently by concatenating all list
* values of the dictionary and maintains default behavior for values of different types.
*/
public class UnconfiguredSelectorListResolver extends AbstractSelectorListResolver {
public UnconfiguredSelectorListResolver(SelectableResolver selectableResolver) {
super(selectableResolver);
}
@Override
@Nullable
@SuppressWarnings("unchecked")
protected <T> T resolveSelector(
SelectableConfigurationContext configurationContext,
BuildTarget buildTarget,
DependencyStack dependencyStack,
String attributeName,
Selector<T> selector) {
Map<Selectable, Object> matchingConditions =
findMatchingConditions(configurationContext, selector, dependencyStack);
Object matchingResult = null;
assertNotMultipleMatches(matchingConditions, attributeName, buildTarget);
if (matchingConditions.size() == 1) {
matchingResult = Iterables.getOnlyElement(matchingConditions.values());
}
if (matchingResult == null) {
assertSelectorHasDefault(buildTarget, dependencyStack, attributeName, selector);
matchingResult = selector.getDefaultConditionValue();
}
if (matchingResult == null) {
return null;
}
ImmutableList.Builder<String> builder = new ImmutableList.Builder<String>();
if (selector.getDefaultConditionValue() instanceof ImmutableList) {
ImmutableMap<SelectorKey, ImmutableList<String>> conditions =
(ImmutableMap<SelectorKey, ImmutableList<String>>) selector.getConditions();
for (ImmutableList<String> list : conditions.values()) {
builder.addAll(list);
}
return (T) builder.build();
}
return (T) matchingResult;
}
}
|
92437559d6b44d6273599566524c3962e56b2020
| 836 |
java
|
Java
|
spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/Target.java
|
alek-sys/spring-cloud-app-broker
|
88d988e6440a663c3c48a404cd91f77d804fc6c4
|
[
"Apache-2.0"
] | 22 |
2019-01-29T03:51:47.000Z
|
2022-02-06T13:29:48.000Z
|
spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/Target.java
|
alek-sys/spring-cloud-app-broker
|
88d988e6440a663c3c48a404cd91f77d804fc6c4
|
[
"Apache-2.0"
] | 321 |
2018-12-13T21:16:15.000Z
|
2022-03-28T15:34:33.000Z
|
spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/Target.java
|
alek-sys/spring-cloud-app-broker
|
88d988e6440a663c3c48a404cd91f77d804fc6c4
|
[
"Apache-2.0"
] | 27 |
2018-12-27T19:37:33.000Z
|
2022-01-23T03:33:47.000Z
| 32.153846 | 94 | 0.755981 | 1,002,659 |
/*
* Copyright 2002-2020 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
*
* 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 org.springframework.cloud.appbroker.extensions.targets;
import java.util.Map;
public interface Target {
ArtifactDetails apply(Map<String, String> properties, String name, String serviceInstanceId);
}
|
924376b51114a76fc9a91b0c8ec0490e498a0c11
| 2,828 |
java
|
Java
|
jp/cssj/homare/impl/a/c/b/f.java
|
MewX/contendo-viewer-v1.6.3
|
69fba3cea4f9a43e48f43148774cfa61b388e7de
|
[
"Apache-2.0"
] | 2 |
2021-07-16T10:43:25.000Z
|
2021-12-15T13:54:10.000Z
|
jp/cssj/homare/impl/a/c/b/f.java
|
MewX/contendo-viewer-v1.6.3
|
69fba3cea4f9a43e48f43148774cfa61b388e7de
|
[
"Apache-2.0"
] | 1 |
2021-10-12T22:24:55.000Z
|
2021-10-12T22:24:55.000Z
|
jp/cssj/homare/impl/a/c/b/f.java
|
MewX/contendo-viewer-v1.6.3
|
69fba3cea4f9a43e48f43148774cfa61b388e7de
|
[
"Apache-2.0"
] | null | null | null | 30.408602 | 86 | 0.427511 | 1,002,660 |
/* */ package jp.cssj.homare.impl.a.c.b;
/* */
/* */ import java.net.URI;
/* */ import java.util.ArrayList;
/* */ import java.util.List;
/* */ import jp.cssj.homare.css.c;
/* */ import jp.cssj.homare.css.c.b;
/* */ import jp.cssj.homare.css.c.j;
/* */ import jp.cssj.homare.css.c.l;
/* */ import jp.cssj.homare.css.f.C;
/* */ import jp.cssj.homare.css.f.H;
/* */ import jp.cssj.homare.css.f.V;
/* */ import jp.cssj.homare.css.f.ad;
/* */ import jp.cssj.homare.css.f.ae;
/* */ import jp.cssj.homare.ua.m;
/* */ import jp.cssj.sakae.sac.css.LexicalUnit;
/* */
/* */
/* */
/* */
/* */ public class f
/* */ extends b
/* */ {
/* 24 */ public static final j a = (j)new f();
/* */
/* */ public static String[] c(c style) {
/* 27 */ ad value = style.a(a);
/* 28 */ if (value.a() == 1007) {
/* 29 */ return null;
/* */ }
/* 31 */ ae valueList = (ae)value;
/* 32 */ ad[] values = valueList.b();
/* 33 */ String[] names = new String[values.length];
/* 34 */ for (int i = 0; i < names.length; i++) {
/* 35 */ names[i] = ((V)values[i]).b();
/* */ }
/* 37 */ return names;
/* */ }
/* */
/* */ private f() {
/* 41 */ super("-cssj-page-content-clear");
/* */ }
/* */
/* */ public ad a(ad value, c style) {
/* 45 */ return value;
/* */ }
/* */
/* */ public ad b(c style) {
/* 49 */ return (ad)H.a;
/* */ }
/* */
/* */ public boolean c() {
/* 53 */ return false;
/* */ }
/* */
/* */ public ad a(LexicalUnit lu, m ua, URI uri) throws l {
/* 57 */ if (lu.getLexicalUnitType() == 12) {
/* 58 */ return (ad)C.a;
/* */ }
/* 60 */ List<ad> list = new ArrayList<>(); do {
/* */ V v2, v1;
/* */ String ident;
/* 63 */ short luType = lu.getLexicalUnitType();
/* 64 */ switch (luType) {
/* */ case 35:
/* 66 */ ident = lu.getStringValue().toLowerCase();
/* 67 */ if (ident.equals("none")) {
/* 68 */ H h = H.a; break;
/* */ }
/* 70 */ v2 = new V(lu.getStringValue());
/* */ break;
/* */
/* */
/* */ case 36:
/* 75 */ v1 = new V(lu.getStringValue());
/* */ break;
/* */
/* */ default:
/* 79 */ throw new l();
/* */ }
/* 81 */ list.add(v1);
/* 82 */ lu = lu.getNextLexicalUnit();
/* 83 */ } while (lu != null);
/* */
/* 85 */ return (ad)new ae(list.<ad>toArray(new ad[list.size()]));
/* */ }
/* */ }
/* Location: /mnt/r/ConTenDoViewer.jar!/jp/cssj/homare/impl/a/c/b/f.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
9243772b0556d2473d2cd1879f7b4163c2cb115f
| 283 |
java
|
Java
|
src/main/java/com/sdcuike/springboot/dao/EnumDemoDao.java
|
sdcuike/spring-boot2-extend
|
893b7623e16c50f8d3776108e2f06b65eede5d7e
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/sdcuike/springboot/dao/EnumDemoDao.java
|
sdcuike/spring-boot2-extend
|
893b7623e16c50f8d3776108e2f06b65eede5d7e
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/sdcuike/springboot/dao/EnumDemoDao.java
|
sdcuike/spring-boot2-extend
|
893b7623e16c50f8d3776108e2f06b65eede5d7e
|
[
"Apache-2.0"
] | 1 |
2019-12-09T07:06:43.000Z
|
2019-12-09T07:06:43.000Z
| 20.214286 | 59 | 0.770318 | 1,002,661 |
package com.sdcuike.springboot.dao;
import com.sdcuike.extend.dynamic.datasource.annotation.DS;
import com.sdcuike.springboot.domain.EnumDemo;
import java.util.List;
@DS("dataSource")
public interface EnumDemoDao {
int insert(EnumDemo record);
List<EnumDemo> select();
}
|
924378936728e3ba9b141c871e4ab28c1b18e623
| 1,303 |
java
|
Java
|
InsPorte_android/app/src/main/java/br/com/badrequest/insporte/activity/base/FullTranslucentActivity.java
|
badrequest/inSPorte
|
5a3626dc5d020aeabbb4b58e48e49d69cd7e12b7
|
[
"BSD-3-Clause"
] | null | null | null |
InsPorte_android/app/src/main/java/br/com/badrequest/insporte/activity/base/FullTranslucentActivity.java
|
badrequest/inSPorte
|
5a3626dc5d020aeabbb4b58e48e49d69cd7e12b7
|
[
"BSD-3-Clause"
] | 1 |
2021-02-16T13:11:50.000Z
|
2021-02-16T13:11:50.000Z
|
InsPorte_android/app/src/main/java/br/com/badrequest/insporte/activity/base/FullTranslucentActivity.java
|
badrequest/inSPorte
|
5a3626dc5d020aeabbb4b58e48e49d69cd7e12b7
|
[
"BSD-3-Clause"
] | null | null | null | 37.228571 | 139 | 0.719877 | 1,002,662 |
package br.com.badrequest.insporte.activity.base;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import com.readystatesoftware.systembartint.SystemBarTintManager;
/**
* Created by gmarques on 5/3/14.
*/
public class FullTranslucentActivity extends InsporteBaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int id = getResources().getIdentifier("config_enableTranslucentDecor", "bool", "android");
if (id != 0) { //KitKat or higher
boolean translucentBarSupported = getResources().getBoolean(id);
if (translucentBarSupported) {
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
}
protected void systemBarTint() {
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setTintColor(Color.parseColor("#CF2B2F"));
}
}
|
924379636c772d31610a4727fe123a92dd86e788
| 692 |
java
|
Java
|
com/raj/frs/service/Administrator.java
|
devrohitraj/GoAir
|
3760b9ff087b2b548d30d765cc350ecd2461d890
|
[
"Apache-2.0"
] | null | null | null |
com/raj/frs/service/Administrator.java
|
devrohitraj/GoAir
|
3760b9ff087b2b548d30d765cc350ecd2461d890
|
[
"Apache-2.0"
] | null | null | null |
com/raj/frs/service/Administrator.java
|
devrohitraj/GoAir
|
3760b9ff087b2b548d30d765cc350ecd2461d890
|
[
"Apache-2.0"
] | null | null | null | 21.625 | 52 | 0.764451 | 1,002,663 |
package com.raj.frs.service;
import java.util.ArrayList;
import com.raj.frs.bean.FlightBean;
import com.raj.frs.bean.RouteBean;
import com.raj.frs.bean.ScheduleBean;
import com.raj.frs.util.User;
public interface Administrator{
String addFlight(FlightBean flightBean);
boolean modifyFlight(FlightBean flightBean);
int removeFlight(ArrayList<String> flightID);
String addSchedule(ScheduleBean scheduleBean);
boolean modifySchedule(ScheduleBean scheduleBean);
int removeSchedule(ArrayList<String> scheduleId);
String addRoute(RouteBean routeBean);
boolean modifyRoute(RouteBean routeBean);
int removeRoute(ArrayList<String> routeId);
}
|
9243796469d1722eb4a19ba6165fd6c462d0a1be
| 1,173 |
java
|
Java
|
core/src/main/java/com/alibaba/datax/dataxservice/face/domain/enums/ExecuteMode.java
|
chenzhaoplus/DataX
|
d131bcc2b0bf9fed69efa931597e51c68d348132
|
[
"Apache-2.0"
] | 14,564 |
2015-12-10T07:48:57.000Z
|
2022-03-31T08:20:41.000Z
|
core/src/main/java/com/alibaba/datax/dataxservice/face/domain/enums/ExecuteMode.java
|
chenzhaoplus/DataX
|
d131bcc2b0bf9fed69efa931597e51c68d348132
|
[
"Apache-2.0"
] | 1,390 |
2015-12-27T07:33:57.000Z
|
2022-03-30T08:11:59.000Z
|
core/src/main/java/com/alibaba/datax/dataxservice/face/domain/enums/ExecuteMode.java
|
chenzhaoplus/DataX
|
d131bcc2b0bf9fed69efa931597e51c68d348132
|
[
"Apache-2.0"
] | 5,545 |
2015-12-11T08:20:31.000Z
|
2022-03-31T08:58:30.000Z
| 23.46 | 73 | 0.618073 | 1,002,664 |
package com.alibaba.datax.dataxservice.face.domain.enums;
public enum ExecuteMode implements EnumStrVal {
STANDALONE("standalone"),
LOCAL("local"),
DISTRIBUTE("distribute");
String value;
ExecuteMode(String value) {
this.value = value;
}
@Override
public String value() {
return value;
}
public String getValue() {
return this.value;
}
public static boolean isLocal(String mode) {
return equalsIgnoreCase(LOCAL.getValue(), mode);
}
public static boolean isDistribute(String mode) {
return equalsIgnoreCase(DISTRIBUTE.getValue(), mode);
}
public static ExecuteMode toExecuteMode(String modeName) {
for (ExecuteMode mode : ExecuteMode.values()) {
if (mode.value().equals(modeName)) {
return mode;
}
}
throw new RuntimeException("no such mode :" + modeName);
}
private static boolean equalsIgnoreCase(String str1, String str2) {
return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
}
@Override
public String toString() {
return this.value;
}
}
|
924379f24a921510609c61ea4b10749bf97db478
| 855 |
java
|
Java
|
src/securityProject/SecurityProject.java
|
amrsaud/cipher
|
957a4f3e210ee591441106d4e32229cc0ccde77e
|
[
"MIT"
] | 1 |
2021-10-30T22:06:34.000Z
|
2021-10-30T22:06:34.000Z
|
src/securityProject/SecurityProject.java
|
amrsaud/cipher
|
957a4f3e210ee591441106d4e32229cc0ccde77e
|
[
"MIT"
] | null | null | null |
src/securityProject/SecurityProject.java
|
amrsaud/cipher
|
957a4f3e210ee591441106d4e32229cc0ccde77e
|
[
"MIT"
] | null | null | null | 24.428571 | 76 | 0.651462 | 1,002,665 |
package securityProject;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* @author Ola Galal
*/
public class SecurityProject extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setResizable(false);
stage.initStyle(StageStyle.UNDECORATED);
stage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
|
92437a5d94e3683e898c2eadc088c54a138cc41e
| 2,002 |
java
|
Java
|
repository/api/src/main/java/com/bloomreach/xm/repository/security/AbstractRoleBean.java
|
athenagroup/brxm
|
58d3c299f2b925a857e55d689e0cb4ee0258d82c
|
[
"Apache-2.0"
] | null | null | null |
repository/api/src/main/java/com/bloomreach/xm/repository/security/AbstractRoleBean.java
|
athenagroup/brxm
|
58d3c299f2b925a857e55d689e0cb4ee0258d82c
|
[
"Apache-2.0"
] | 28 |
2020-10-29T15:59:43.000Z
|
2022-03-02T12:50:38.000Z
|
repository/api/src/main/java/com/bloomreach/xm/repository/security/AbstractRoleBean.java
|
ajbanck/brxm
|
79d55e2d88a320719a78e3b4534799495336b572
|
[
"Apache-2.0"
] | null | null | null | 26 | 76 | 0.666334 | 1,002,666 |
/*
* Copyright 2019 Hippo B.V. (http://www.onehippo.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.bloomreach.xm.repository.security;
import java.util.HashSet;
/**
* Simple (abstract) POJO bean implementation of {@link AbstractRole}
*/
public abstract class AbstractRoleBean implements AbstractRole {
private String name;
private String description;
private boolean system;
private final HashSet<String> roles = new HashSet<>();
public AbstractRoleBean() {
}
public AbstractRoleBean(final String name, final String description) {
this.name = name;
this.description = description;
}
public AbstractRoleBean(final AbstractRole role) {
this.name = role.getName();
this.description = role.getDescription();
this.system = role.isSystem();
this.roles.addAll(role.getRoles());
}
@Override
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
@Override
public boolean isSystem() {
return system;
}
public void setSystem(final boolean system) {
this.system = system;
}
@Override
public HashSet<String> getRoles() {
return roles;
}
}
|
92437a826c6046d134e1043fccafcfeca7891248
| 6,336 |
java
|
Java
|
src/main/java/org/ncic/bioinfo/sparkseq/algorithms/walker/haplotypecaller/annotator/DepthPerSampleHC.java
|
liguo668/SparkSeq
|
45dcc57dc74f8f3cbbcbb7f70a055a4e449cd949
|
[
"Apache-2.0"
] | 153 |
2020-07-15T02:50:59.000Z
|
2021-12-16T03:07:01.000Z
|
src/main/java/org/ncic/bioinfo/sparkseq/algorithms/walker/haplotypecaller/annotator/DepthPerSampleHC.java
|
liguo668/SparkSeq
|
45dcc57dc74f8f3cbbcbb7f70a055a4e449cd949
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/ncic/bioinfo/sparkseq/algorithms/walker/haplotypecaller/annotator/DepthPerSampleHC.java
|
liguo668/SparkSeq
|
45dcc57dc74f8f3cbbcbb7f70a055a4e449cd949
|
[
"Apache-2.0"
] | 129 |
2020-07-15T02:51:03.000Z
|
2021-12-16T03:07:02.000Z
| 58.666667 | 333 | 0.732008 | 1,002,667 |
/*
* Copyright (c) 2017 NCIC, Institute of Computing Technology, Chinese Academy of Sciences
*
* 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.ncic.bioinfo.sparkseq.algorithms.walker.haplotypecaller.annotator;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.Genotype;
import htsjdk.variant.variantcontext.GenotypeBuilder;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.vcf.VCFConstants;
import htsjdk.variant.vcf.VCFFormatHeaderLine;
import htsjdk.variant.vcf.VCFStandardHeaderLines;
import org.ncic.bioinfo.sparkseq.algorithms.data.reference.RefMetaDataTracker;
import org.ncic.bioinfo.sparkseq.algorithms.data.reference.ReferenceContext;
import org.ncic.bioinfo.sparkseq.algorithms.data.sam.AlignmentContext;
import org.ncic.bioinfo.sparkseq.algorithms.data.sam.GATKSAMRecord;
import org.ncic.bioinfo.sparkseq.algorithms.walker.haplotypecaller.MostLikelyAllele;
import org.ncic.bioinfo.sparkseq.algorithms.walker.haplotypecaller.PerReadAlleleLikelihoodMap;
import org.ncic.bioinfo.sparkseq.algorithms.walker.haplotypecaller.annotator.interfaces.AnnotatorCompatible;
import org.ncic.bioinfo.sparkseq.algorithms.walker.haplotypecaller.annotator.interfaces.GenotypeAnnotation;
import java.util.*;
/**
* Depth of informative coverage for each sample.
* <p>
* <p>This annotation is similar to the sample-level DP annotation, which counts read depth after general filtering, but with an extra layer of stringency. Its purpose is to provide the count of reads that are actually considered informative by HaplotypeCaller (HC), using pre-read likelihoods that are produced internally by HC.</p>
* <p>In this context, an informative read is defined as one that allows the allele it carries to be easily distinguished. In contrast, a read might be considered uninformative if, for example, it only partially overlaps a short tandem repeat and it is not clear whether the read contains the reference allele or an extra repeat.</p>
* <p>
* <p>See the method documentation on <a href="http://www.broadinstitute.org/gatk/guide/article?id=4721">using coverage information</a> for important interpretation details.</p>
* <p>
* <h3>Caveats</h3>
* <ul>
* <li>This annotation can only be generated by HaplotypeCaller (it will not work when called from VariantAnnotator).</li>
* </ul>
* <p>
* <h3>Related annotations</h3>
* <ul>
* <li><b><a href="https://www.broadinstitute.org/gatk/guide/tooldocs/org_broadinstitute_gatk_tools_walkers_annotator_DepthPerAlleleBySample.php">DepthPerAlleleBySample</a></b> calculates depth of coverage for each allele per sample (AD).</li>
* <li><b><a href="https://www.broadinstitute.org/gatk/guide/tooldocs/org_broadinstitute_gatk_tools_walkers_annotator_Coverage.php">Coverage</a></b> gives the filtered depth of coverage for each sample and the unfiltered depth across all samples.</li>
* </ul>
*/
public class DepthPerSampleHC extends GenotypeAnnotation {
public void annotate(final RefMetaDataTracker tracker,
final AnnotatorCompatible walker,
final ReferenceContext ref,
final AlignmentContext stratifiedContext,
final VariantContext vc,
final Genotype g,
final GenotypeBuilder gb,
final PerReadAlleleLikelihoodMap alleleLikelihoodMap) {
if (g == null || !g.isCalled() || (stratifiedContext == null && alleleLikelihoodMap == null))
return;
if (alleleLikelihoodMap == null)
throw new IllegalStateException("DepthPerSampleHC can only be used with likelihood based annotations in the HaplotypeCaller");
// the depth for the HC is the sum of the informative alleles at this site. It's not perfect (as we cannot
// differentiate between reads that align over the event but aren't informative vs. those that aren't even
// close) but it's a pretty good proxy and it matches with the AD field (i.e., sum(AD) = DP).
int dp = 0;
if (alleleLikelihoodMap.isEmpty()) {
// there are no reads
} else {
final Set<Allele> alleles = new HashSet<>(vc.getAlleles());
// make sure that there's a meaningful relationship between the alleles in the perReadAlleleLikelihoodMap and our VariantContext
if (!alleleLikelihoodMap.getAllelesSet().containsAll(alleles))
throw new IllegalStateException("VC alleles " + alleles + " not a strict subset of per read allele map alleles " + alleleLikelihoodMap.getAllelesSet());
for (Map.Entry<GATKSAMRecord, Map<Allele, Double>> el : alleleLikelihoodMap.getLikelihoodReadMap().entrySet()) {
final MostLikelyAllele a = PerReadAlleleLikelihoodMap.getMostLikelyAllele(el.getValue(), alleles);
if (a.isInformative()) {
dp++;
}
}
gb.DP(dp);
}
}
public List<String> getKeyNames() {
return Collections.singletonList(VCFConstants.DEPTH_KEY);
}
public List<VCFFormatHeaderLine> getDescriptions() {
return Collections.singletonList(VCFStandardHeaderLines.getFormatLine(VCFConstants.DEPTH_KEY));
}
}
|
92437b31c197330bf13389762694db00f45d1eda
| 492 |
java
|
Java
|
src/main/java/com/github/hexsmith/netty/protocol/request/MessageRequestPacket.java
|
yuzhiping/JavaNIO
|
1ad1eba21797964c49e9a216ac84c73ed016c7c3
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/github/hexsmith/netty/protocol/request/MessageRequestPacket.java
|
yuzhiping/JavaNIO
|
1ad1eba21797964c49e9a216ac84c73ed016c7c3
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/github/hexsmith/netty/protocol/request/MessageRequestPacket.java
|
yuzhiping/JavaNIO
|
1ad1eba21797964c49e9a216ac84c73ed016c7c3
|
[
"Apache-2.0"
] | null | null | null | 17.571429 | 58 | 0.678862 | 1,002,668 |
package com.github.hexsmith.netty.protocol.request;
import com.github.hexsmith.netty.protocol.AbstractPacket;
import com.github.hexsmith.netty.protocol.Command;
import lombok.Data;
/**
* @author hexsmith
* @version v1.0
* @since 2019-07-29 16:38
*/
@Data
public class MessageRequestPacket extends AbstractPacket {
private String message;
/**
* 指令
*
* @return
*/
@Override
public Byte getCommand() {
return Command.MESSAGE_REQUEST;
}
}
|
92437b3225c5cc3023e02d11624fa09654f884e8
| 847 |
java
|
Java
|
src/main/java/Client.java
|
mark99-19/SDP-Lab_Esercise2-theatre
|
676c95b47d69ce538fa6712357da39fdb9ff693a
|
[
"MIT"
] | null | null | null |
src/main/java/Client.java
|
mark99-19/SDP-Lab_Esercise2-theatre
|
676c95b47d69ce538fa6712357da39fdb9ff693a
|
[
"MIT"
] | null | null | null |
src/main/java/Client.java
|
mark99-19/SDP-Lab_Esercise2-theatre
|
676c95b47d69ce538fa6712357da39fdb9ff693a
|
[
"MIT"
] | null | null | null | 28.233333 | 117 | 0.661157 | 1,002,669 |
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
String data;
//Create connection
System.out.println("[+] Connecting to server...");
Socket connection = new Socket("localhost", 6789);
System.out.println("["+connection.getLocalPort()+"] Successfull connected to port: " + connection.getPort());
//crete "file descriptor" for i/o
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//read data from server
data = inFromServer.readLine();
System.out.println("["+connection.getLocalPort()+"] Result: " + data + "\n");
connection.close();
}
}
|
92437c555997733b49ce7829de606c8836eea359
| 8,197 |
java
|
Java
|
Courses + Books/Algorithms/Book/Part 1/02 - Sorting/02_2 - Mergesort/Reading Part - Exercises/MergeX.java
|
edaaydinea/365-days-of-coding-challenge
|
baf06a9bef75ff45194e57357e20085b9cde2498
|
[
"MIT"
] | 4 |
2022-01-05T12:14:13.000Z
|
2022-01-08T16:03:32.000Z
|
Courses + Books/Algorithms/Book/Part 1/02 - Sorting/02_2 - Mergesort/Reading Part - Exercises/MergeX.java
|
edaaydinea/365-days-of-coding-challenge
|
baf06a9bef75ff45194e57357e20085b9cde2498
|
[
"MIT"
] | null | null | null |
Courses + Books/Algorithms/Book/Part 1/02 - Sorting/02_2 - Mergesort/Reading Part - Exercises/MergeX.java
|
edaaydinea/365-days-of-coding-challenge
|
baf06a9bef75ff45194e57357e20085b9cde2498
|
[
"MIT"
] | null | null | null | 34.154167 | 107 | 0.501647 | 1,002,670 |
/******************************************************************************
* Compilation: javac MergeX.java
* Execution: java MergeX < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt
* https://algs4.cs.princeton.edu/22mergesort/words3.txt
*
* Sorts a sequence of strings from standard input using an
* optimized version of mergesort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java MergeX < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java MergeX < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import java.util.Comparator;
/**
* The {@code MergeX} class provides static methods for sorting an
* array using an optimized version of mergesort.
* <p>
* In the worst case, this implementation takes
* Θ(<em>n</em> log <em>n</em>) time to sort an array of
* length <em>n</em> (assuming comparisons take constant time).
* <p>
* This sorting algorithm is stable.
* It uses Θ(<em>n</em>) extra memory (not including the input array).
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class MergeX {
private static final int CUTOFF = 7; // cutoff to insertion sort
// This class should not be instantiated.
private MergeX() { }
private static void merge(Comparable[] src, Comparable[] dst, int lo, int mid, int hi) {
// precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays
assert isSorted(src, lo, mid);
assert isSorted(src, mid+1, hi);
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) dst[k] = src[j++];
else if (j > hi) dst[k] = src[i++];
else if (less(src[j], src[i])) dst[k] = src[j++]; // to ensure stability
else dst[k] = src[i++];
}
// postcondition: dst[lo .. hi] is sorted subarray
assert isSorted(dst, lo, hi);
}
private static void sort(Comparable[] src, Comparable[] dst, int lo, int hi) {
// if (hi <= lo) return;
if (hi <= lo + CUTOFF) {
insertionSort(dst, lo, hi);
return;
}
int mid = lo + (hi - lo) / 2;
sort(dst, src, lo, mid);
sort(dst, src, mid+1, hi);
// if (!less(src[mid+1], src[mid])) {
// for (int i = lo; i <= hi; i++) dst[i] = src[i];
// return;
// }
// using System.arraycopy() is a bit faster than the above loop
if (!less(src[mid+1], src[mid])) {
System.arraycopy(src, lo, dst, lo, hi - lo + 1);
return;
}
merge(src, dst, lo, mid, hi);
}
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
Comparable[] aux = a.clone();
sort(aux, a, 0, a.length-1);
assert isSorted(a);
}
// sort from a[lo] to a[hi] using insertion sort
private static void insertionSort(Comparable[] a, int lo, int hi) {
for (int i = lo; i <= hi; i++)
for (int j = i; j > lo && less(a[j], a[j-1]); j--)
exch(a, j, j-1);
}
/*******************************************************************
* Utility methods.
*******************************************************************/
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
// is a[i] < a[j]?
private static boolean less(Comparable a, Comparable b) {
return a.compareTo(b) < 0;
}
// is a[i] < a[j]?
private static boolean less(Object a, Object b, Comparator comparator) {
return comparator.compare(a, b) < 0;
}
/*******************************************************************
* Version that takes Comparator as argument.
*******************************************************************/
/**
* Rearranges the array in ascending order, using the provided order.
*
* @param a the array to be sorted
* @param comparator the comparator that defines the total order
*/
public static void sort(Object[] a, Comparator comparator) {
Object[] aux = a.clone();
sort(aux, a, 0, a.length-1, comparator);
assert isSorted(a, comparator);
}
private static void merge(Object[] src, Object[] dst, int lo, int mid, int hi, Comparator comparator) {
// precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays
assert isSorted(src, lo, mid, comparator);
assert isSorted(src, mid+1, hi, comparator);
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) dst[k] = src[j++];
else if (j > hi) dst[k] = src[i++];
else if (less(src[j], src[i], comparator)) dst[k] = src[j++];
else dst[k] = src[i++];
}
// postcondition: dst[lo .. hi] is sorted subarray
assert isSorted(dst, lo, hi, comparator);
}
private static void sort(Object[] src, Object[] dst, int lo, int hi, Comparator comparator) {
// if (hi <= lo) return;
if (hi <= lo + CUTOFF) {
insertionSort(dst, lo, hi, comparator);
return;
}
int mid = lo + (hi - lo) / 2;
sort(dst, src, lo, mid, comparator);
sort(dst, src, mid+1, hi, comparator);
// using System.arraycopy() is a bit faster than the above loop
if (!less(src[mid+1], src[mid], comparator)) {
System.arraycopy(src, lo, dst, lo, hi - lo + 1);
return;
}
merge(src, dst, lo, mid, hi, comparator);
}
// sort from a[lo] to a[hi] using insertion sort
private static void insertionSort(Object[] a, int lo, int hi, Comparator comparator) {
for (int i = lo; i <= hi; i++)
for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--)
exch(a, j, j-1);
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
}
private static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
private static boolean isSorted(Object[] a, Comparator comparator) {
return isSorted(a, 0, a.length - 1, comparator);
}
private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1], comparator)) return false;
return true;
}
// print array to standard output
private static void show(Object[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; mergesorts them
* (using an optimized version of mergesort);
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
MergeX.sort(a);
show(a);
}
}
|
92437c696a3698c74b0aba068a551a0ff054ca02
| 207 |
java
|
Java
|
StringDigits.java
|
chrisgirl/Strings
|
5265eddb9f47ff0cdbf4d63497a48a78c10fee4e
|
[
"Apache-2.0"
] | null | null | null |
StringDigits.java
|
chrisgirl/Strings
|
5265eddb9f47ff0cdbf4d63497a48a78c10fee4e
|
[
"Apache-2.0"
] | null | null | null |
StringDigits.java
|
chrisgirl/Strings
|
5265eddb9f47ff0cdbf4d63497a48a78c10fee4e
|
[
"Apache-2.0"
] | null | null | null | 14.785714 | 63 | 0.599034 | 1,002,671 |
/*
check if a string contains only digits
*/
public class StringDigits {
String text = "abc";
String number;
if (text.contains("[a-zA-Z]+") == false && text.length() > 2) {
number = text;
}
}
|
92437e7dc3fc0b3b643cf81b9a176861a19cb65f
| 2,034 |
java
|
Java
|
leetcode/src/validNumber/Solution.java
|
mccxj/online-judge-code-example
|
e61c85b1af0613312e149986fb8bd64154d70d95
|
[
"Apache-2.0"
] | 2 |
2018-04-26T09:36:21.000Z
|
2018-04-26T09:36:23.000Z
|
leetcode/src/validNumber/Solution.java
|
mccxj/leetcode
|
e61c85b1af0613312e149986fb8bd64154d70d95
|
[
"Apache-2.0"
] | 4 |
2017-01-09T02:12:29.000Z
|
2017-01-15T01:34:41.000Z
|
leetcode/src/validNumber/Solution.java
|
mccxj/online-judge-code-example
|
e61c85b1af0613312e149986fb8bd64154d70d95
|
[
"Apache-2.0"
] | null | null | null | 27.486486 | 135 | 0.334317 | 1,002,672 |
package validNumber;
/**
* Validate if a given string is numeric.
* <p/>
* Some examples:
* "0" => true
* " 0.1 " => true
* "abc" => false
* "1 a" => false
* "2e10" => true
* Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
*/
public class Solution {
public boolean isNumber(String s) {
int i = 0;
while (i < s.length() && s.charAt(i) == ' ') {
i++;
}
boolean preNum = false;
boolean nextNum = false;
boolean isE = false;
int dot = 1;// at most one(before 'e' or after)
while (i < s.length()) {
char c = s.charAt(i);
if (c == ' ') {
break;
}
if ('-' == c || '+' == c) {
if (i > 0 && (s.charAt(i - 1) != ' ' && s.charAt(i - 1) != 'e')) {
return false;
}
if (i + 1 < s.length()) {
char cc = s.charAt(i + 1);
if (('0' > cc || cc > '9') && '.' != cc) {
return false;
}
}
} else if ('0' <= c && c <= '9') {
if (isE) {
nextNum = true;
} else {
preNum = true;
}
} else if ('.' == c) {
if (isE || dot == 0) {
return false;
}
dot--;
} else if ('e' == c) {
if (isE) {
return false;
}
dot = 1;// reset '.'
isE = true;
} else {
return false;
}
i++;
}
if (!preNum || (isE && !nextNum)) {
return false;
}
while (i < s.length()) {
if (s.charAt(i) != ' ') {
return false;
}
i++;
}
return true;
}
}
|
92437ee920351cafba985309427de515c2c52224
| 1,174 |
java
|
Java
|
src/main/java/project/ridersserver/ridersserverapp/domain/Member/MemberEntity.java
|
CSID-DGU/RidersServerFinal
|
7d66761850dfdd87b82cf6a18c157a476918cab4
|
[
"MIT"
] | 1 |
2020-06-24T05:31:32.000Z
|
2020-06-24T05:31:32.000Z
|
src/main/java/project/ridersserver/ridersserverapp/domain/Member/MemberEntity.java
|
CSID-DGU/RidersServerFinal
|
7d66761850dfdd87b82cf6a18c157a476918cab4
|
[
"MIT"
] | null | null | null |
src/main/java/project/ridersserver/ridersserverapp/domain/Member/MemberEntity.java
|
CSID-DGU/RidersServerFinal
|
7d66761850dfdd87b82cf6a18c157a476918cab4
|
[
"MIT"
] | 2 |
2020-06-24T04:49:47.000Z
|
2020-09-10T13:23:26.000Z
| 28.634146 | 116 | 0.753833 | 1,002,673 |
package project.ridersserver.ridersserverapp.domain.Member;
import javax.persistence.*;
import javafx.scene.NodeBuilder;
import lombok.*;
import org.springframework.util.Assert;
import project.ridersserver.ridersserverapp.domain.Video.VideoEventEntity;
import project.ridersserver.ridersserverapp.domain.Video.VideoViewEntity;
import java.util.HashSet;
import java.util.Set;
@SequenceGenerator(name = "MEMBER_SEQ_GENERATOR", sequenceName = "MEMBER_SEQ", initialValue = 1, allocationSize = 1)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Getter
@Setter
@Entity
@Table(name = "member")
public class MemberEntity {
@Id
@GeneratedValue(strategy= GenerationType.SEQUENCE , generator="MEMBER_SEQ_GENERATOR")
private Long id;
@Column(length = 20, nullable = false , unique = true)
private String email;
@Column(length = 100, nullable = false)
private String password;
@OneToMany(mappedBy = "member", cascade = CascadeType.ALL)
private Set<VideoViewEntity> viewVideos = new HashSet<>();
public void addViewVideo(VideoViewEntity viewVideo){
this.getViewVideos().add(viewVideo);
viewVideo.setMember(this);
}
}
|
92438039c1c045d82528b972a12daf3fe9223a8f
| 656 |
java
|
Java
|
src/main/java/fr/guddy/roombookings/infra/params/RequiredParameter.java
|
RoRoche/RoomBookingsBackEnd
|
bf419635e1d9e69f71e71feecc68e53588b47bd8
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/fr/guddy/roombookings/infra/params/RequiredParameter.java
|
RoRoche/RoomBookingsBackEnd
|
bf419635e1d9e69f71e71feecc68e53588b47bd8
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/fr/guddy/roombookings/infra/params/RequiredParameter.java
|
RoRoche/RoomBookingsBackEnd
|
bf419635e1d9e69f71e71feecc68e53588b47bd8
|
[
"Apache-2.0"
] | 1 |
2018-11-29T16:30:56.000Z
|
2018-11-29T16:30:56.000Z
| 23.428571 | 79 | 0.667683 | 1,002,674 |
package fr.guddy.roombookings.infra.params;
import fr.guddy.roombookings.infra.params.exceptions.MissingParameterException;
import java.util.Optional;
public final class RequiredParameter<T> implements Parameter<T> {
private final Parameter<T> delegate;
public RequiredParameter(final Parameter<T> delegate) {
this.delegate = delegate;
}
@Override
public String name() {
return delegate.name();
}
@Override
public T value() {
final T value = delegate.value();
return Optional.ofNullable(value).orElseThrow(() ->
new MissingParameterException(name())
);
}
}
|
92438176897661220ad473e181496205353b7348
| 521 |
java
|
Java
|
app/src/main/java/com/jm/newvista/mvp/presenter/SettingsPresenter.java
|
johnnymillergh/NewVista-For-Customer
|
3558d7b3d590dbc33527df88c1fd291d45d68dfb
|
[
"MIT"
] | 2 |
2020-02-17T15:54:36.000Z
|
2021-04-11T13:41:47.000Z
|
app/src/main/java/com/jm/newvista/mvp/presenter/SettingsPresenter.java
|
johnnymillergh/NewVista-For-Customer
|
3558d7b3d590dbc33527df88c1fd291d45d68dfb
|
[
"MIT"
] | 1 |
2018-04-21T10:45:47.000Z
|
2018-04-21T11:34:04.000Z
|
app/src/main/java/com/jm/newvista/mvp/presenter/SettingsPresenter.java
|
johnnymillergh/NewVista-For-Customer
|
3558d7b3d590dbc33527df88c1fd291d45d68dfb
|
[
"MIT"
] | 3 |
2018-05-07T09:13:53.000Z
|
2021-02-27T18:52:02.000Z
| 26.05 | 83 | 0.754319 | 1,002,675 |
package com.jm.newvista.mvp.presenter;
import com.jm.newvista.mvp.base.BasePresenter;
import com.jm.newvista.mvp.model.SettingsModel;
import com.jm.newvista.mvp.view.SettingsView;
/**
* Created by Johnny on 3/23/2018.
*/
public class SettingsPresenter extends BasePresenter<SettingsModel, SettingsView> {
private SettingsModel settingsModel;
private SettingsView settingsView;
public SettingsPresenter() {
settingsModel = new SettingsModel();
super.BasePresenter(settingsModel);
}
}
|
924382a75fc5a9108d786c33d95f039e2ec45946
| 840 |
java
|
Java
|
mybatis-in-action/src/main/java/com/photowey/mybatis/in/action/mybatis/dynamic/kernel/repository/Repository.java
|
photowey/the-way-to-java
|
37ec3e12aaebf8f63862837b9d4a506401eb1e38
|
[
"Apache-2.0"
] | null | null | null |
mybatis-in-action/src/main/java/com/photowey/mybatis/in/action/mybatis/dynamic/kernel/repository/Repository.java
|
photowey/the-way-to-java
|
37ec3e12aaebf8f63862837b9d4a506401eb1e38
|
[
"Apache-2.0"
] | 1 |
2022-01-28T04:48:47.000Z
|
2022-02-20T06:20:44.000Z
|
mybatis-in-action/src/main/java/com/photowey/mybatis/in/action/mybatis/dynamic/kernel/repository/Repository.java
|
photowey/the-way-to-java
|
37ec3e12aaebf8f63862837b9d4a506401eb1e38
|
[
"Apache-2.0"
] | null | null | null | 30.035714 | 75 | 0.727705 | 1,002,676 |
/*
* Copyright © 2021 the original author or authors ([email protected])
*
* 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.photowey.mybatis.in.action.mybatis.dynamic.kernel.repository;
/**
* {@code CrudRepository}
*
* @author photowey
* @date 2021/11/08
* @since 1.0.0
*/
public interface Repository<T> {
}
|
924382aa2b956f2c4b095b922aed0db21c876551
| 1,196 |
java
|
Java
|
src/engine/gameRepresentation/evaluatables/evaluators/MovePlayer.java
|
martelagelo/voogaSalad_RTS_gameEditor
|
c582283e598ed589e70b684bcea28fe14a1e12fd
|
[
"MIT"
] | null | null | null |
src/engine/gameRepresentation/evaluatables/evaluators/MovePlayer.java
|
martelagelo/voogaSalad_RTS_gameEditor
|
c582283e598ed589e70b684bcea28fe14a1e12fd
|
[
"MIT"
] | null | null | null |
src/engine/gameRepresentation/evaluatables/evaluators/MovePlayer.java
|
martelagelo/voogaSalad_RTS_gameEditor
|
c582283e598ed589e70b684bcea28fe14a1e12fd
|
[
"MIT"
] | null | null | null | 39.866667 | 97 | 0.737458 | 1,002,677 |
package engine.gameRepresentation.evaluatables.evaluators;
import model.state.gameelement.StateTags;
import engine.gameRepresentation.evaluatables.Evaluatable;
import engine.gameRepresentation.renderedRepresentation.GameElement;
/**
* An Evaluator that moves a player according to their velocity parameters
*
* @author Zach
*/
public class MovePlayer<A, B> extends Evaluator<A, B, Boolean> {
public MovePlayer (Evaluatable<A> parameter1, Evaluatable<B> parameter2) {
super(Boolean.class, "move", parameter1, parameter2);
}
@Override
public Boolean evaluate (GameElement element1, GameElement element2) {
element1.setNumericalAttribute(StateTags.X_POSITION.getValue(), element1
.getNumericalAttribute(StateTags.X_POSITION.getValue()).doubleValue()
+ element1.getNumericalAttribute(StateTags.X_VELOCITY.getValue()).doubleValue());
element1.setNumericalAttribute(StateTags.Y_POSITION.getValue(), element1
.getNumericalAttribute(StateTags.Y_POSITION.getValue()).doubleValue()
+ element1.getNumericalAttribute(StateTags.Y_VELOCITY.getValue()).doubleValue());
return true;
}
}
|
924382d278f0d3b628c615a2e989f4a08f305516
| 1,212 |
java
|
Java
|
tests/src/test/java/com/revolsys/core/test/geometry/test/old/operation/CascadedPolygonUnionFileTest.java
|
pauldaustin/gba-revolsys
|
561c5a2f858b54ab4503e7ae5cffeac11d5d8952
|
[
"Apache-2.0"
] | 5 |
2015-02-23T04:53:44.000Z
|
2021-03-03T17:18:24.000Z
|
tests/src/test/java/com/revolsys/core/test/geometry/test/old/operation/CascadedPolygonUnionFileTest.java
|
pauldaustin/gba-revolsys
|
561c5a2f858b54ab4503e7ae5cffeac11d5d8952
|
[
"Apache-2.0"
] | 5 |
2021-08-13T23:45:14.000Z
|
2022-03-31T19:59:23.000Z
|
tests/src/test/java/com/revolsys/core/test/geometry/test/old/operation/CascadedPolygonUnionFileTest.java
|
pauldaustin/gba-revolsys
|
561c5a2f858b54ab4503e7ae5cffeac11d5d8952
|
[
"Apache-2.0"
] | 8 |
2015-02-23T04:53:45.000Z
|
2022-03-26T22:35:36.000Z
| 29.560976 | 86 | 0.788779 | 1,002,678 |
package com.revolsys.core.test.geometry.test.old.operation;
import java.io.IOException;
import java.util.List;
import com.revolsys.core.test.geometry.test.old.algorithm.InteriorPointTest;
import com.revolsys.geometry.operation.union.CascadedPolygonUnion;
import com.revolsys.geometry.wkb.ParseException;
import junit.framework.TestCase;
/**
* Large-scale tests of {@link CascadedPolygonUnion}
* using data from files.
*
* @author mbdavis
*
*/
public class CascadedPolygonUnionFileTest extends TestCase {
private static CascadedPolygonUnionTester tester = new CascadedPolygonUnionTester();
public CascadedPolygonUnionFileTest(final String name) {
super(name);
}
private void runTestResource(final String file, final double minimumMeasure)
throws IOException, ParseException {
final List geometries = InteriorPointTest.getTestGeometries(file);
assertTrue(tester.test(geometries, minimumMeasure));
}
public void testAfrica2() throws Exception {
runTestResource("africa.wkt", CascadedPolygonUnionTester.MIN_SIMILARITY_MEAURE);
}
public void XtestEurope() throws Exception {
runTestResource("europe.wkt", CascadedPolygonUnionTester.MIN_SIMILARITY_MEAURE);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.