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
9242b15e7faaaee98bcf79c716f0bf708d02023e
23,984
java
Java
app/src/main/java/com/example/weilin/travelapp/MainActivity.java
Edward7Zhang/TravelApp
df5dd95a92d1aecb79750aed9d983ae3310d4632
[ "MIT" ]
null
null
null
app/src/main/java/com/example/weilin/travelapp/MainActivity.java
Edward7Zhang/TravelApp
df5dd95a92d1aecb79750aed9d983ae3310d4632
[ "MIT" ]
null
null
null
app/src/main/java/com/example/weilin/travelapp/MainActivity.java
Edward7Zhang/TravelApp
df5dd95a92d1aecb79750aed9d983ae3310d4632
[ "MIT" ]
null
null
null
34.019858
148
0.584556
1,002,376
package com.example.weilin.travelapp; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.support.v4.app.ActivityCompat; import android.support.v4.view.ViewPager; import android.support.v7.view.menu.MenuBuilder; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationListener; import com.amap.api.maps.AMap; import com.amap.api.maps.CameraUpdate; import com.amap.api.maps.CameraUpdateFactory; import com.amap.api.maps.LocationSource; import com.amap.api.maps.TextureMapView; import com.amap.api.maps.UiSettings; import com.amap.api.maps.model.BitmapDescriptorFactory; import com.amap.api.maps.model.CameraPosition; import com.amap.api.maps.model.LatLng; import com.amap.api.maps.model.Marker; import com.amap.api.maps.model.MarkerOptions; import com.example.weilin.travelapp.bean.Sense; import com.example.weilin.travelapp.tools.MyTextUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.mob.tools.utils.UIHandler; import org.xutils.http.RequestParams; import org.xutils.x; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; import cn.sharesdk.framework.Platform; import cn.sharesdk.framework.PlatformActionListener; import cn.sharesdk.framework.ShareSDK; public class MainActivity extends Activity implements PlatformActionListener, MenuBuilder.Callback, Callback, AMapLocationListener, LocationSource { private String text = "分享旅游信息"; private String imageurl = "http://h.hiphotos.baidu.com/image/pic/item/ac4bd11373f082028dc9b2a749fbfbedaa641bca.jpg"; private String title = "旅游景点"; private String url = "www.baidu.com"; private TextView comment; private TextView reservation; public static String SENSE_KEY = "sense"; /** * viewpager的数据源 */ private List<String> vpUrlList = new ArrayList<>(); private List<String> pictureList; private ImageView shareImage; private SharePopupWindow share; private Button mCallButton; private int price = 120;//价格数据 private ViewPager mImageVp;//viwepager private ViewPagerAdapter mAdapter;//适配器 private TextView priceTv, indexTv;//价格和页脚 private Button colt_bt;//收藏按钮 private boolean flag = false;//收藏按钮的标志 private Timer mTimer;//viewpager定时器 private int currentItem;//viewpager定时器的循环标志 TextureMapView mMapView = null; AMap aMap; LocationSource.OnLocationChangedListener mListener; AMapLocationClient mlocationClient; AMapLocationClientOption mLocationOption; Button bt_route; static double Latitude;//获取纬度 static double Longitude;//获取经度 /** * 将下面两个参数传入注意纬度经度的顺序 ********************************/ static double inLatitude;//传入纬度 /*******/ static double inLongitude;//传入经度 /*******/ /*******************************************************************/ private UiSettings mUiSettings; private CameraUpdate mUpdata; // private TextView doComment_tv; private TextView name_tv; private TextView address_tv; private TextView phnumber_tv; private TextView openTime_tv; private Sense sense; private ImageView centerIMG; private Timer timer; private LinearLayout viewArea; private Button seeAll_bt; private TextView senceIntrudec_tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); getJsonFromNet();//从网络下载数据 ShareSDK.initSDK(this); comment = (TextView) findViewById(R.id.doComment_tv); reservation = (TextView) findViewById(R.id.doShop_tv); reservation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setClass(getBaseContext(), loginActivity.class); startActivity(intent); } }); comment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setClass(getBaseContext(), CommentActivity.class); startActivity(intent); } }); Intent intent = getIntent(); //获取地图控件引用 mMapView = (TextureMapView) findViewById(R.id.map); //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState),创建地图 mMapView.onCreate(savedInstanceState); bt_route = (Button) findViewById(R.id.bt_route); bt_route.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, AMapNavi_View.class); startActivity(intent); } }); initUI(); intitHrs(); } private void intitHrs() { viewArea = (LinearLayout) findViewById(R.id.hrsv); final Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { if (viewArea.getWidth() != 0) { Log.i("LinearLayout", viewArea.getWidth() + ""); Log.i("LinearLayout", viewArea.getHeight() + ""); ViewGroup.LayoutParams para; HorizontalScrollView h = (HorizontalScrollView) findViewById(R.id.hrsv_hs); para = h.getLayoutParams(); para.width = viewArea.getWidth(); h.setLayoutParams(para); ImageView iv = (ImageView) findViewById(R.id.live_iv); para = iv.getLayoutParams(); para.width = viewArea.getWidth() / 4; iv.setLayoutParams(para); iv = (ImageView) findViewById(R.id.play_iv); para = iv.getLayoutParams(); para.width = viewArea.getWidth() / 4; iv.setLayoutParams(para); iv = (ImageView) findViewById(R.id.eat_iv); para = iv.getLayoutParams(); para.width = viewArea.getWidth() / 4; iv.setLayoutParams(para); iv = (ImageView) findViewById(R.id.villager_iv); para = iv.getLayoutParams(); para.width = viewArea.getWidth() / 4; iv.setLayoutParams(para); timer.cancel(); } } } }; timer = new Timer(); TimerTask task = new TimerTask() { public void run() { Message message = new Message(); message.what = 1; myHandler.sendMessage(message); } }; //延迟每次延迟10 毫秒 隔1秒执行一次 timer.schedule(task, 10, 1000); } private void initMap() { //初始化地图控制器对象 if (aMap == null) { aMap = mMapView.getMap(); } mUiSettings = aMap.getUiSettings(); mUiSettings.setZoomControlsEnabled(false); mUpdata = CameraUpdateFactory.newCameraPosition( //15是缩放比例,0是倾斜度,30显示比例 new CameraPosition(new LatLng(inLatitude, inLongitude), 15, 0, 30));//这是地理位置,就是经纬度。 aMap.moveCamera(mUpdata);//定位的方法 drawMarkers(); // 设置定位监听 aMap.setLocationSource(this); // 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false aMap.setMyLocationEnabled(true); // 设置定位的类型为定位模式,有定位、跟随或地图根据面向方向旋转几种 aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE); } public void drawMarkers() { Marker marker = aMap.addMarker(new MarkerOptions() .position(new LatLng(inLatitude, inLongitude)) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)) .draggable(true)); marker.showInfoWindow();// 设置默认显示一个infowinfow } /** * 激活定位 */ @Override public void activate(LocationSource.OnLocationChangedListener listener) { mListener = listener; if (mlocationClient == null) { //初始化定位 mlocationClient = new AMapLocationClient(this); //初始化定位参数 mLocationOption = new AMapLocationClientOption(); //设置定位回调监听 mlocationClient.setLocationListener(this); //设置为高精度定位模式 mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); //设置定位参数 mlocationClient.setLocationOption(mLocationOption); // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗, //设置定位模式为AMapLocationMode.Battery_Saving,低功耗模式。 mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving); // 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求 ///设置定位模式为AMapLocationMode.Device_Sensors,仅设备模式。 mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors); // 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除 mlocationClient.startLocation();//启动定位 //设置是否返回地址信息(默认返回地址信息) mLocationOption.setNeedAddress(true); //获取最近3s内精度最高的一次定位结果: //设置setOnceLocationLatest(boolean b)接口为true,启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true,setOnceLocation(boolean b)接口也会被设置为true,反之不会,默认为false。 mLocationOption.setOnceLocationLatest(true); } } /** * 停止定位 */ @Override public void deactivate() { mListener = null; if (mlocationClient != null) { mlocationClient.stopLocation(); mlocationClient.onDestroy(); } mlocationClient = null; } /** * 定位成功后回调函数 */ @Override public void onLocationChanged(AMapLocation amapLocation) { if (mListener != null && amapLocation != null) { if (amapLocation != null && amapLocation.getErrorCode() == 0) { //mListener.onLocationChanged(amapLocation);// 显示系统小蓝点 amapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见定位类型表 Latitude = amapLocation.getLatitude();//获取纬度 Longitude = amapLocation.getLongitude();//获取经度 amapLocation.getAccuracy();//获取精度信息 amapLocation.getAddress();//地址,如果option中设置isNeedAddress为false,则没有此结果,网络定位结果中会有地址信息,GPS定位不返回地址信息。 amapLocation.getCountry();//国家信息 amapLocation.getProvince();//省信息 amapLocation.getCity();//城市信息 amapLocation.getDistrict();//城区信息 amapLocation.getStreet();//街道信息 amapLocation.getStreetNum();//街道门牌号信息 amapLocation.getCityCode();//城市编码 amapLocation.getAdCode();//地区编码 amapLocation.getAoiName();//获取当前定位点的AOI信息 amapLocation.getBuildingId();//获取当前室内定位的建筑物Id amapLocation.getFloor();//获取当前室内定位的楼层 amapLocation.getGpsAccuracyStatus();//获取GPS的当前状态 //获取定位时间 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(amapLocation.getTime()); df.format(date); } else { String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo(); Log.e("AmapErr", errText); } } } /** * 初始化界面 */ public void initUI() { name_tv = (TextView) findViewById(R.id.name_tv); address_tv = (TextView) findViewById(R.id.address_tv); phnumber_tv = (TextView) findViewById(R.id.phnumber_tv); openTime_tv = (TextView) findViewById(R.id.openTime_tv); centerIMG = (ImageView) findViewById(R.id.oneOfSence_img); /** *分享share的初始化 */ shareImage = (ImageView) findViewById(R.id.share_iv); shareImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { share = new SharePopupWindow(MainActivity.this); share.setPlatformActionListener(MainActivity.this); ShareModel model = new ShareModel(); model.setImageUrl(imageurl); model.setText(text); model.setTitle(title); model.setUrl(url); share.initShareParams(model); share.showShareWindow(); share.showAtLocation(MainActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); } }); mCallButton = (Button) findViewById(R.id.btn_call); mCallButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + sense.getSensePhnumber())); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { return; } startActivity(intent); } }); seeAll_bt = (Button) findViewById(R.id.seeAll_btn); senceIntrudec_tv = (TextView)findViewById(R.id.senseDetail_tv); seeAll_bt.setOnClickListener(mClickListener); } /** * 设置viewpager数据源 * * @param list */ public void setVpUrlList(List<String> list) { vpUrlList = list; } public void initvp() { /** * 控件的实例化viewpager,页脚文本框,价格文半框,收藏按钮 */ mImageVp = (ViewPager) findViewById(R.id.banner_vp); indexTv = (TextView) findViewById(R.id.index_tv); priceTv = (TextView) findViewById(R.id.price_tv); colt_bt = (Button) findViewById(R.id.colt_bt); /** * 生成适配器,绑定到viewpager上 */ mAdapter = new ViewPagerAdapter(this, vpUrlList); mImageVp.setAdapter(mAdapter); /** * viewpager,价格,页脚的初始化设置 */ indexTv.setText(1 + "/" + (vpUrlList.size() - 2)); priceTv.setText("¥" + price); mImageVp.setCurrentItem(1); /** * 设置收藏按钮的监听 */ colt_bt.setOnClickListener(mClickListener); /** * 设置ViewPager的监听器 */ mImageVp.addOnPageChangeListener(mPageChangeListener); //初始化定时器 initTimer(); } /** * viewpager定时器初始化 */ public void initTimer() { mTimer = new Timer(); mTimer.schedule(mTask, 5 * 1000, 5 * 1000); } /** * 定时器向线程发送消息 */ private TimerTask mTask = new TimerTask() { @Override public void run() { Message message = new Message(); message.arg1 = 0; mHandler.sendMessage(message); } }; /** * 开启线程更换图片 */ private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.arg1 == 0) { currentItem++; if (currentItem > (vpUrlList.size() - 2)) { currentItem = 1; mImageVp.setCurrentItem(currentItem, false); } else mImageVp.setCurrentItem(currentItem); } else if (msg.arg1 == 1) { sense = pullJason((String) msg.obj); inLatitude = Double.valueOf(sense.getSenseLatitude()); inLongitude = Double.valueOf(sense.getSenseLongitude()); initMap(); //设置viewpager的数据源 setVpUrlList(sense.getSensePictures()); //绑定viewpager的相关的操作 initvp(); x.image().bind(centerIMG, sense.getSensePictures().get(1)); mAdapter.notifyDataSetChanged(); name_tv.setText(sense.getSenseName()); phnumber_tv.setText("电话:" + sense.getSensePhnumber()); address_tv.setText("地址:" + sense.getSenseAddress()); openTime_tv.setText("开放时间:" + sense.getSenseOpenTime() + "~" + sense.getSenseCloseTime()); } } }; private Sense pullJason(String jsondata) { Gson gson = new Gson(); List<Sense> senseList = gson.fromJson(jsondata, new TypeToken<List<Sense>>() { }.getType()); System.out.println(senseList.get(0)); return senseList.get(0); } /** * 收藏按钮的监听 */ private View.OnClickListener mClickListener = new View.OnClickListener() { @Override public void onClick(View view) { if(view.getId() == R.id.colt_bt) { if (flag) { //设置收藏按钮的背景图片高亮 colt_bt.setBackgroundResource(R.drawable.favorite2); flag = false; } else { //设置收藏按钮的背景图 colt_bt.setBackgroundResource(R.drawable.favorite); flag = true; } } if(view.getId() == R.id.seeAll_btn) { if(flag){ flag = false; senceIntrudec_tv.setEllipsize(null); // 展开 senceIntrudec_tv.setSingleLine(flag); seeAll_bt.setText("收起"); }else{ flag = true; senceIntrudec_tv.setEllipsize(TextUtils.TruncateAt.valueOf("END")); // 收缩 senceIntrudec_tv.setLines(5); seeAll_bt.setText("查看所有"); } } } }; /** * 对viewpager的监听 */ private ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } /** * viewpager的循环和页脚的文本设置 * @param position */ @Override public void onPageSelected(int position) { if (position < 1) { //首位之前,跳转到末尾(N) position = vpUrlList.size() - 2; indexTv.setText(position + 1 + "/" + (vpUrlList.size() - 2)); mImageVp.setCurrentItem(position, false); } else if (position > (vpUrlList.size() - 2)) { //末位之后,跳转到首位(1) mImageVp.setCurrentItem(1, false); //false:不显示跳转过程的动画 position = 1; indexTv.setText(position + "/" + (vpUrlList.size() - 2)); } indexTv.setText(position + "/" + (vpUrlList.size() - 2)); } @Override public void onPageScrollStateChanged(int state) { } }; @Override protected void onResume() { super.onResume(); if (share != null) { share.dismiss(); } //在activity执行onResume时执行mMapView.onResume (),重新绘制加载地图 mMapView.onResume(); } @Override protected void onDestroy() { super.onDestroy(); ShareSDK.stopSDK(this); mMapView.onDestroy(); if (null != mlocationClient) { mlocationClient.onDestroy(); } if (mTimer != null) { mTimer.cancel(); mTimer = null; } } @Override protected void onPause() { super.onPause(); //在activity执行onPause时执行mMapView.onPause (),暂停地图的绘制 mMapView.onPause(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),保存地图当前的状态 mMapView.onSaveInstanceState(outState); } @Override public void onCancel(Platform arg0, int arg1) { Message msg = new Message(); msg.what = 0; UIHandler.sendMessage(msg, this); } @Override public void onComplete(Platform plat, int action, HashMap<String, Object> res) { Message msg = new Message(); msg.arg1 = 1; msg.arg2 = action; msg.obj = plat; UIHandler.sendMessage(msg, this); } @Override public void onError(Platform arg0, int arg1, Throwable arg2) { Message msg = new Message(); msg.what = 1; UIHandler.sendMessage(msg, this); } @Override public boolean handleMessage(Message msg) { int what = msg.what; if (what == 1) { Toast.makeText(this, "您没有注册", Toast.LENGTH_SHORT).show(); } if (share != null) { share.dismiss(); } return false; } @Override public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { return false; } @Override public void onMenuModeChange(MenuBuilder menu) { } /** * 从网络中下载json数据 */ public void getJsonFromNet() { RequestParams params = new RequestParams("http://115.159.150.136:8080/travel/Eservlet"); params.setHeader("Content-Type", "text/html;charset=utf-8"); params.addParameter("SenseCode", "1235"); x.http().get(params, new org.xutils.common.Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { Message message = new Message(); message.arg1 = 1; message.obj = result; System.out.println(result); mHandler.sendMessage(message); } @Override public void onError(Throwable ex, boolean isOnCallback) { System.out.println("下载失败......"); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { System.out.println("下载程序完成........"); } }); } /** * 查看更多评论,跳转 * * @param view */ public void seeAllComment(View view) { Intent seeall = new Intent(MainActivity.this, AllComment.class); Bundle bundle = new Bundle(); bundle.putSerializable(SENSE_KEY, sense); seeall.putExtras(bundle); System.out.println("comment数据为:" + sense.getSenseComments()); startActivity(seeall); } /** * 查看所有详情的介绍 * * @param v */ public void seeAlldetails(View v) { TextView senseDetail_tv = (TextView) findViewById(R.id.senseDetail_tv); String text = (String) senseDetail_tv.getText(); String s = MyTextUtils.toDBC(text); senseDetail_tv.setText(s); } }
9242b1b7cfb0cb0d8192dcb59b2477699d8c725a
1,574
java
Java
ejb3/docs/examples/xpetstore/xpetstore-servlet/java/xpetstore/util/MailUtil.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
ejb3/docs/examples/xpetstore/xpetstore-servlet/java/xpetstore/util/MailUtil.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
ejb3/docs/examples/xpetstore/xpetstore-servlet/java/xpetstore/util/MailUtil.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
29.277778
101
0.600886
1,002,377
/* * Created on 27-Feb-2003 */ package xpetstore.util; import java.util.Date; import javax.activation.DataHandler; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.naming.InitialContext; import javax.naming.NamingException; /** * @author <a href="mailto:[email protected]">Herve Tchepannou</a> */ public class MailUtil { //~ Static fields/initializers --------------------------------------------- public static final String MAIL_SESSION = "java:comp/env/mail/xpetstore/MailSession"; //~ Methods ---------------------------------------------------------------- public static void send( String to, String subject, String body ) throws NamingException, AddressException, MessagingException { InitialContext ic = new InitialContext( ); Session session = ( Session ) ic.lookup( MAIL_SESSION ); javax.mail.Message msg = new MimeMessage( session ); msg.setFrom( ); msg.setRecipients( javax.mail.Message.RecipientType.TO, InternetAddress.parse( to, false ) ); msg.setSubject( subject ); msg.setDataHandler( new DataHandler( body, "text/plain" ) ); msg.setHeader( "X-Mailer", "JavaMailer" ); msg.setSentDate( new Date( ) ); Transport.send( msg ); } }
9242b3c6807fa77eb73778ac6ff5957a02de0bbd
17,760
java
Java
extras/rya.geoindexing/geo.geowave/src/main/java/org/apache/rya/indexing/geoExamples/GeowaveDirectExample.java
iruka2019/rya
9ed219e7376880794b0566cd5ceff0e23ade6f4b
[ "Apache-2.0" ]
80
2015-11-11T22:28:17.000Z
2019-10-03T09:25:10.000Z
extras/rya.geoindexing/geo.geowave/src/main/java/org/apache/rya/indexing/geoExamples/GeowaveDirectExample.java
iruka2019/rya
9ed219e7376880794b0566cd5ceff0e23ade6f4b
[ "Apache-2.0" ]
262
2015-12-02T17:20:38.000Z
2019-06-25T13:00:01.000Z
extras/rya.geoindexing/geo.geowave/src/main/java/org/apache/rya/indexing/geoExamples/GeowaveDirectExample.java
Varulv1997/rya
baf3fe2f2357db7fc86e38df5f4b994b44bd4307
[ "Apache-2.0" ]
87
2015-11-10T14:12:32.000Z
2019-09-13T08:44:31.000Z
39.820628
118
0.651745
1,002,378
package org.apache.rya.indexing.geoExamples; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import org.apache.commons.lang.Validate; import org.apache.hadoop.conf.Configuration; import org.apache.log4j.Logger; import org.apache.rya.indexing.GeoIndexerType; import org.apache.rya.indexing.GeoRyaSailFactory; import org.apache.rya.indexing.accumulo.AccumuloIndexingConfiguration; import org.apache.rya.indexing.accumulo.ConfigUtils; import org.apache.rya.indexing.accumulo.geo.OptionalConfigUtils; import org.apache.rya.indexing.external.PrecomputedJoinIndexerConfig; import org.apache.rya.indexing.external.PrecomputedJoinIndexerConfig.PrecomputedJoinStorageType; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.MalformedQueryException; import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.QueryResultHandlerException; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResultHandler; import org.eclipse.rdf4j.query.TupleQueryResultHandlerException; import org.eclipse.rdf4j.query.Update; import org.eclipse.rdf4j.query.UpdateExecutionException; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection; import org.eclipse.rdf4j.sail.Sail; public class GeowaveDirectExample { private static final Logger log = Logger.getLogger(GeowaveDirectExample.class); // // Connection configuration parameters // private static final boolean USE_MOCK_INSTANCE = true; private static final boolean PRINT_QUERIES = true; private static final String INSTANCE = "instance"; private static final String RYA_TABLE_PREFIX = "x_test_triplestore_"; private static final String AUTHS = "U"; public static void main(final String[] args) throws Exception { final Configuration conf = getConf(); conf.set(PrecomputedJoinIndexerConfig.PCJ_STORAGE_TYPE, PrecomputedJoinStorageType.ACCUMULO.name()); conf.setBoolean(ConfigUtils.DISPLAY_QUERY_PLAN, PRINT_QUERIES); conf.setBoolean(OptionalConfigUtils.USE_GEO, true); conf.setEnum(OptionalConfigUtils.GEO_INDEXER_TYPE, GeoIndexerType.GEO_WAVE); log.info("Creating the tables as root."); SailRepository repository = null; SailRepositoryConnection conn = null; try { log.info("Connecting to Geo Sail Repository."); final Sail extSail = GeoRyaSailFactory.getInstance(conf); repository = new SailRepository(extSail); conn = repository.getConnection(); final long start = System.currentTimeMillis(); log.info("Running SPARQL Example: Add Point and Geo Search with PCJ"); testAddPointAndWithinSearchWithPCJ(conn); log.info("Running SPARQL Example: Temporal, Freetext, and Geo Search"); testTemporalFreeGeoSearch(conn); log.info("Running SPARQL Example: Geo, Freetext, and PCJ Search"); testGeoFreetextWithPCJSearch(conn); log.info("Running SPARQL Example: Delete Geo Data"); testDeleteGeoData(conn); log.info("TIME: " + (System.currentTimeMillis() - start) / 1000.); } finally { log.info("Shutting down"); closeQuietly(conn); closeQuietly(repository); } } private static void closeQuietly(final SailRepository repository) { if (repository != null) { try { repository.shutDown(); } catch (final RepositoryException e) { // quietly absorb this exception } } } private static void closeQuietly(final SailRepositoryConnection conn) { if (conn != null) { try { conn.close(); } catch (final RepositoryException e) { // quietly absorb this exception } } } private static Configuration getConf() { return AccumuloIndexingConfiguration.builder() .setUseMockAccumulo(USE_MOCK_INSTANCE) .setAuths(AUTHS) .setAccumuloUser("root") .setAccumuloPassword("") .setAccumuloInstance(INSTANCE) .setRyaPrefix(RYA_TABLE_PREFIX) .setUsePcj(true) .setUseAccumuloFreetextIndex(true) .setUseAccumuloTemporalIndex(true) .build(); } private static void testAddPointAndWithinSearchWithPCJ( final SailRepositoryConnection conn) throws Exception { final String update = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "INSERT DATA { " // + " <urn:feature> a geo:Feature ; " // + " geo:hasGeometry [ " // + " a geo:Point ; " // + " geo:asWKT \"Point(-77.03524 38.889468)\"^^geo:wktLiteral "// + " ] . " // + "}"; final Update u = conn.prepareUpdate(QueryLanguage.SPARQL, update); u.execute(); String queryString; TupleQuery tupleQuery; CountingResultHandler tupleHandler; // point outside search ring queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "SELECT ?feature ?point ?wkt " // + "{" // + " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + " FILTER(geof:sfWithin(?wkt, \"POLYGON((-77 39, -76 39, -76 38, -77 38, -77 39))\"^^geo:wktLiteral)) " // + "}";// tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); tupleHandler = new CountingResultHandler(); tupleQuery.evaluate(tupleHandler); log.info("point outside search ring, Result count : " + tupleHandler.getCount()); Validate.isTrue(tupleHandler.getCount() == 0); // point inside search ring queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "SELECT ?feature ?point ?wkt " // ?e ?l ?o" // + "{" // // + " ?feature a ?e . "// // + " ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "// // + " ?e <uri:talksTo> ?o . "// + " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + " FILTER(geof:sfWithin(?wkt, \"POLYGON((-78 39, -77 39, -77 38, -78 38, -78 39))\"^^geo:wktLiteral)) " // + "}";// tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); tupleHandler = new CountingResultHandler(); tupleQuery.evaluate(tupleHandler); log.info("point inside search ring, Result count : " + tupleHandler.getCount()); Validate.isTrue(tupleHandler.getCount() == 1); // point inside search ring with Pre-Computed Join queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "SELECT ?feature ?point ?wkt "//?e ?l ?o" // + "{" // // + " ?feature a ?e . "// // + " ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "// // + " ?e <uri:talksTo> ?o . "// + " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + " FILTER(geof:sfWithin(?wkt, \"POLYGON((-78 39, -77 39, -77 38, -78 38, -78 39))\"^^geo:wktLiteral)) " // + "}";// tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); tupleHandler = new CountingResultHandler(); tupleQuery.evaluate(tupleHandler); log.info("point inside search ring with Pre-Computed Join, Result count : " + tupleHandler.getCount()); Validate.isTrue(tupleHandler.getCount() >= 1); // may see points from // during previous runs // point outside search ring with PCJ queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "SELECT ?feature ?point ?wkt "//?e ?l ?o " // + "{" // // + " ?feature a ?e . "// // + " ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "// // + " ?e <uri:talksTo> ?o . "// + " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + " FILTER(geof:sfWithin(?wkt, \"POLYGON((-77 39, -76 39, -76 38, -77 38, -77 39))\"^^geo:wktLiteral)) " // + "}";// tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); tupleHandler = new CountingResultHandler(); tupleQuery.evaluate(tupleHandler); log.info("point outside search ring with PCJ, Result count : " + tupleHandler.getCount()); Validate.isTrue(tupleHandler.getCount() == 0); // point inside search ring with different Pre-Computed Join queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "SELECT ?feature ?point "//?wkt ?e ?c ?l ?o " // + "{" // // + " ?e a ?c . "// // + " ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "// //+ " ?e <uri:talksTo> ?o . "// //+ " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + " FILTER(geof:sfWithin(?wkt, \"POLYGON((-78 39, -77 39, -77 38, -78 38, -78 39))\"^^geo:wktLiteral)) " // + "}";// tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); tupleHandler = new CountingResultHandler(); tupleQuery.evaluate(tupleHandler); log.info("point inside search ring with different Pre-Computed Join, Result count : " + tupleHandler.getCount()); Validate.isTrue(tupleHandler.getCount() == 1); } private static void testTemporalFreeGeoSearch( final SailRepositoryConnection conn) throws MalformedQueryException, RepositoryException, UpdateExecutionException, TupleQueryResultHandlerException, QueryEvaluationException { // Once upon a time, a meeting happened, in a place and time, attended by 5 paladins and another. final String update = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "PREFIX time: <http://www.w3.org/2006/time#> "// + "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> "// + "PREFIX fts: <http://rdf.useekm.com/fts#> "// + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "// + "PREFIX ex: <http://example.com/#> "// + "INSERT DATA { " // + " ex:feature719 a geo:Feature ; " // + " geo:hasGeometry [ " // + " a geo:Point ; " // + " geo:asWKT \"Point(-77.03524 38.889468)\"^^geo:wktLiteral "// + " ] . "// + " ex:event719 a time:Instant ;" // + " time:inXSDDateTime '2001-01-01T01:01:04-08:00' ;" // 4 seconds + " ex:locatedAt ex:feature719 ;" // + " ex:attendee ex:person01;" // + " ex:attendee ex:person02;" // + " ex:attendee ex:person03;" // + " ex:attendee [a ex:Person ; rdfs:label 'Paladin Ogier the Dane' ] ;" // Use a blank node instead of person04 + " ex:attendee ex:person05;" // + " ex:attendee ex:person06." // + " ex:person01 a ex:Person ;" // + " rdfs:label \"Paladin Fossil\"." // + " ex:person02 a ex:Person ;" // + " rdfs:label \"Paladin Paul Denning\"." // + " ex:person03 a ex:Person ;" // + " rdfs:label 'Paladin Will Travel'." // + " ex:person05 a ex:Person ;" // + " rdfs:label 'Paladin dimethyl disulfide'." // + " ex:person06 a ex:Person ;" // + " rdfs:label 'Ignore me'." // + "" // + "}"; final Update u = conn.prepareUpdate(QueryLanguage.SPARQL, update); u.execute(); String queryString; TupleQuery tupleQuery; CountingResultHandler tupleHandler; // Find all events after a time, located in a polygon square, whose attendees have label names beginning with "Pal" queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "PREFIX time: <http://www.w3.org/2006/time#> "// + "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> "// + "PREFIX fts: <http://rdf.useekm.com/fts#> "// + "PREFIX ex: <http://example.com/#> "// + "SELECT ?feature ?point ?wkt ?event ?time ?person ?match" // + "{" // + " ?event a time:Instant ; \n"// + " time:inXSDDateTime ?time ; \n"// + " ex:locatedAt ?feature ;" // + " ex:attendee ?person." // + " FILTER(tempo:after(?time, '2001-01-01T01:01:03-08:00') ) \n"// after 3 seconds + " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + " FILTER(geof:sfWithin(?wkt, \"POLYGON((-78 39, -77 39, -77 38, -78 38, -78 39))\"^^geo:wktLiteral)). " // + " ?person a ex:Person . "// + " ?person <http://www.w3.org/2000/01/rdf-schema#label> ?match . "// + " FILTER(fts:text(?match, \"Pal*\")) " // + "}";// tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); tupleHandler = new CountingResultHandler(); tupleQuery.evaluate(tupleHandler); log.info("Result count : " + tupleHandler.getCount()); Validate.isTrue(tupleHandler.getCount() == 5 ); } private static void testGeoFreetextWithPCJSearch( final SailRepositoryConnection conn) throws MalformedQueryException, RepositoryException, TupleQueryResultHandlerException, QueryEvaluationException { // ring outside point final String queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX fts: <http://rdf.useekm.com/fts#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "SELECT ?feature ?point ?wkt ?e ?c ?l ?o ?person ?match " // + "{" // + " ?person a <http://example.org/ontology/Person> . "// + " ?person <http://www.w3.org/2000/01/rdf-schema#label> ?match . "// + " FILTER(fts:text(?match, \"!alice & hose\")) " // + " ?e a ?c . "// + " ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "// + " ?e <uri:talksTo> ?o . "// + " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + " FILTER(geof:sfWithin(?wkt, \"POLYGON((-78 39, -77 39, -77 38, -78 38, -78 39))\"^^geo:wktLiteral)) " // + "}";// final TupleQuery tupleQuery = conn.prepareTupleQuery( QueryLanguage.SPARQL, queryString); final CountingResultHandler tupleHandler = new CountingResultHandler(); tupleQuery.evaluate(tupleHandler); log.info("Result count : " + tupleHandler.getCount()); Validate.isTrue(tupleHandler.getCount() == 0);// TODO ==1 some data is missing for this query! } private static void testDeleteGeoData(final SailRepositoryConnection conn) throws Exception { // Delete all stored points final String sparqlDelete = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "DELETE {\n" // + " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + "}\n" + "WHERE { \n" + " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + "}";// final Update deleteUpdate = conn.prepareUpdate(QueryLanguage.SPARQL, sparqlDelete); deleteUpdate.execute(); String queryString; TupleQuery tupleQuery; CountingResultHandler tupleHandler; // Find all stored points queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#> "// + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "// + "SELECT ?feature ?point ?wkt " // + "{" // + " ?feature a geo:Feature . "// + " ?feature geo:hasGeometry ?point . "// + " ?point a geo:Point . "// + " ?point geo:asWKT ?wkt . "// + "}";// tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); tupleHandler = new CountingResultHandler(); tupleQuery.evaluate(tupleHandler); log.info("Result count : " + tupleHandler.getCount()); Validate.isTrue(tupleHandler.getCount() == 0); } private static class CountingResultHandler implements TupleQueryResultHandler { private int count = 0; public int getCount() { return count; } public void resetCount() { count = 0; } @Override public void startQueryResult(final List<String> arg0) throws TupleQueryResultHandlerException { } @Override public void handleSolution(final BindingSet arg0) throws TupleQueryResultHandlerException { count++; System.out.println(arg0); } @Override public void endQueryResult() throws TupleQueryResultHandlerException { } @Override public void handleBoolean(final boolean arg0) throws QueryResultHandlerException { } @Override public void handleLinks(final List<String> arg0) throws QueryResultHandlerException { } } }
9242b3d0bdf600a30434256cf71e4a6752be17d7
2,169
java
Java
RPCClient/src/main/java/com/springmvc/ClientHandler.java
theosunny/studyEveryDay
0563cf28b1c238c5d3036f1b44c9e82223382e29
[ "Apache-2.0" ]
null
null
null
RPCClient/src/main/java/com/springmvc/ClientHandler.java
theosunny/studyEveryDay
0563cf28b1c238c5d3036f1b44c9e82223382e29
[ "Apache-2.0" ]
4
2021-01-20T21:47:48.000Z
2022-03-31T18:37:31.000Z
RPCClient/src/main/java/com/springmvc/ClientHandler.java
theosunny/studyEveryDay
0563cf28b1c238c5d3036f1b44c9e82223382e29
[ "Apache-2.0" ]
null
null
null
32.863636
80
0.527432
1,002,379
package com.springmvc; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.net.Socket; import java.util.Arrays; public class ClientHandler implements InvocationHandler { String host; int port; public ClientHandler(String host, int port) { this.host = host; this.port = port; } // invoke方法本意是对目标方法的增强,在这里用于发送RPC请求和接收响应 @Override public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable { // 创建Socket客户端,并与服务端建立链接 Socket socket = new Socket(host, port); try { /* 客户端像服务端进行请求,并将请求参数写入流中*/ // 将对象写入到对象输出流,并将其发送到Socket流中去 ObjectOutputStream output = new ObjectOutputStream( socket.getOutputStream()); try { // 发送请求 System.out.println("\nClient发送请求 : "); output.writeUTF(method.getName()); System.out.println("methodName : " + method.getName()); output.writeObject(method.getParameterTypes()); System.out.println("parameterTypes : " + Arrays.toString(method .getParameterTypes())); output.writeObject(arguments); System.out.println("arguments : " + Arrays.toString(arguments)); /* 客户端读取并返回服务端的响应*/ ObjectInputStream input = new ObjectInputStream( socket.getInputStream()); try { Object result = input.readObject(); if (result instanceof Throwable) { throw (Throwable) result; } System.out.println("\nClient收到响应 : "); System.out.println("result : " + result); return result; } finally { input.close(); } } finally { output.close(); } } finally { socket.close(); } } }
9242b45691f329f85c17019576966f15a46c6f64
16,556
java
Java
aeron-system-tests/src/test/java/io/aeron/archive/ManageRecordingHistoryTest.java
jrsala-auguration/aeron
613cae03d73e615af43b8f2a253f0a4c0929ab5e
[ "Apache-2.0" ]
3,400
2017-07-01T14:25:59.000Z
2022-03-31T00:45:02.000Z
aeron-system-tests/src/test/java/io/aeron/archive/ManageRecordingHistoryTest.java
jrsala-auguration/aeron
613cae03d73e615af43b8f2a253f0a4c0929ab5e
[ "Apache-2.0" ]
566
2017-07-01T13:47:37.000Z
2022-03-22T20:17:40.000Z
aeron-system-tests/src/test/java/io/aeron/archive/ManageRecordingHistoryTest.java
jrsala-auguration/aeron
613cae03d73e615af43b8f2a253f0a4c0929ab5e
[ "Apache-2.0" ]
542
2017-07-04T15:29:49.000Z
2022-03-24T18:36:01.000Z
43.915119
115
0.693767
1,002,380
/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.aeron.archive; import io.aeron.Aeron; import io.aeron.ChannelUriStringBuilder; import io.aeron.Publication; import io.aeron.archive.client.AeronArchive; import io.aeron.archive.client.RecordingSignalAdapter; import io.aeron.archive.client.RecordingSignalConsumer; import io.aeron.archive.codecs.RecordingSignal; import io.aeron.archive.status.RecordingPos; import io.aeron.driver.MediaDriver; import io.aeron.driver.ThreadingMode; import io.aeron.logbuffer.LogBufferDescriptor; import io.aeron.test.InterruptAfter; import io.aeron.test.InterruptingTestCallback; import io.aeron.test.SystemTestWatcher; import io.aeron.test.driver.TestMediaDriver; import org.agrona.CloseHelper; import org.agrona.SystemUtil; import org.agrona.collections.MutableReference; import org.agrona.concurrent.status.CountersReader; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import java.io.File; import static io.aeron.archive.ArchiveSystemTests.*; import static io.aeron.logbuffer.FrameDescriptor.FRAME_ALIGNMENT; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(InterruptingTestCallback.class) public class ManageRecordingHistoryTest { private static final int TERM_LENGTH = LogBufferDescriptor.TERM_MIN_LENGTH; private static final int SEGMENT_LENGTH = TERM_LENGTH * 2; private static final int STREAM_ID = 1033; private static final int MTU_LENGTH = 1024; private final ChannelUriStringBuilder uriBuilder = new ChannelUriStringBuilder() .media("udp") .endpoint("localhost:3333") .mtu(MTU_LENGTH) .termLength(TERM_LENGTH); private TestMediaDriver driver; private Archive archive; private Aeron aeron; private AeronArchive aeronArchive; @RegisterExtension public final SystemTestWatcher systemTestWatcher = new SystemTestWatcher(); @BeforeEach public void before() { final MediaDriver.Context driverCtx = new MediaDriver.Context() .publicationTermBufferLength(TERM_LENGTH) .termBufferSparseFile(true) .threadingMode(ThreadingMode.SHARED) .spiesSimulateConnection(true) .dirDeleteOnStart(true); final Archive.Context archiveCtx = new Archive.Context() .catalogCapacity(CATALOG_CAPACITY) .segmentFileLength(SEGMENT_LENGTH) .deleteArchiveOnStart(true) .archiveDir(new File(SystemUtil.tmpDirName(), "archive")) .fileSyncLevel(0) .threadingMode(ArchiveThreadingMode.SHARED); try { driver = TestMediaDriver.launch(driverCtx, systemTestWatcher); archive = Archive.launch(archiveCtx); } finally { systemTestWatcher.dataCollector().add(driverCtx.aeronDirectory()); systemTestWatcher.dataCollector().add(archiveCtx.archiveDir()); } aeron = Aeron.connect(); aeronArchive = AeronArchive.connect( new AeronArchive.Context() .aeron(aeron)); } @AfterEach public void after() { CloseHelper.closeAll(aeronArchive, aeron, archive, driver); } @Test @InterruptAfter(10) public void shouldPurgeForStreamJoinedAtTheBeginning() { final String messagePrefix = "Message-Prefix-"; final long targetPosition = (SEGMENT_LENGTH * 3L) + 1; try (Publication publication = aeronArchive.addRecordedPublication(uriBuilder.build(), STREAM_ID)) { final CountersReader counters = aeron.countersReader(); final int counterId = awaitRecordingCounterId(counters, publication.sessionId()); final long recordingId = RecordingPos.getRecordingId(counters, counterId); offerToPosition(publication, messagePrefix, targetPosition); awaitPosition(counters, counterId, publication.position()); final long startPosition = 0L; final long segmentFileBasePosition = AeronArchive.segmentFileBasePosition( startPosition, SEGMENT_LENGTH * 2L, TERM_LENGTH, SEGMENT_LENGTH); final long count = aeronArchive.purgeSegments(recordingId, segmentFileBasePosition); assertEquals(2L, count); assertEquals(segmentFileBasePosition, aeronArchive.getStartPosition(recordingId)); aeronArchive.stopRecording(publication); } } @Test @InterruptAfter(10) public void shouldPurgeForLateJoinedStream() { final String messagePrefix = "Message-Prefix-"; final int initialTermId = 7; final long targetPosition = (SEGMENT_LENGTH * 3L) + 1; final long startPosition = (TERM_LENGTH * 2L) + (FRAME_ALIGNMENT * 2L); uriBuilder.initialPosition(startPosition, initialTermId, TERM_LENGTH); try (Publication publication = aeronArchive.addRecordedExclusivePublication(uriBuilder.build(), STREAM_ID)) { assertEquals(startPosition, publication.position()); final CountersReader counters = aeron.countersReader(); final int counterId = awaitRecordingCounterId(counters, publication.sessionId()); final long recordingId = RecordingPos.getRecordingId(counters, counterId); offerToPosition(publication, messagePrefix, targetPosition); awaitPosition(counters, counterId, publication.position()); final long segmentFileBasePosition = AeronArchive.segmentFileBasePosition( startPosition, startPosition + (SEGMENT_LENGTH * 2L), TERM_LENGTH, SEGMENT_LENGTH); final long purgeSegments = aeronArchive.purgeSegments(recordingId, segmentFileBasePosition); assertEquals(2L, purgeSegments); assertEquals(segmentFileBasePosition, aeronArchive.getStartPosition(recordingId)); aeronArchive.stopRecording(publication); } } @Test @InterruptAfter(10) public void shouldDetachThenAttachFullSegments() { final String messagePrefix = "Message-Prefix-"; final long targetPosition = (SEGMENT_LENGTH * 3L) + 1; try (Publication publication = aeronArchive.addRecordedPublication(uriBuilder.build(), STREAM_ID)) { final CountersReader counters = aeron.countersReader(); final int counterId = awaitRecordingCounterId(counters, publication.sessionId()); final long recordingId = RecordingPos.getRecordingId(counters, counterId); offerToPosition(publication, messagePrefix, targetPosition); awaitPosition(counters, counterId, publication.position()); aeronArchive.stopRecording(publication); final long startPosition = 0L; final long segmentFileBasePosition = AeronArchive.segmentFileBasePosition( startPosition, SEGMENT_LENGTH * 2L, TERM_LENGTH, SEGMENT_LENGTH); aeronArchive.detachSegments(recordingId, segmentFileBasePosition); assertEquals(segmentFileBasePosition, aeronArchive.getStartPosition(recordingId)); final long attachSegments = aeronArchive.attachSegments(recordingId); assertEquals(2L, attachSegments); assertEquals(startPosition, aeronArchive.getStartPosition(recordingId)); } } @Test @InterruptAfter(10) public void shouldDetachThenAttachWhenStartNotSegmentAligned() { final String messagePrefix = "Message-Prefix-"; final int initialTermId = 7; final long targetPosition = (SEGMENT_LENGTH * 3L) + 1; final long startPosition = (TERM_LENGTH * 2L) + (FRAME_ALIGNMENT * 2L); uriBuilder.initialPosition(startPosition, initialTermId, TERM_LENGTH); try (Publication publication = aeronArchive.addRecordedExclusivePublication(uriBuilder.build(), STREAM_ID)) { assertEquals(startPosition, publication.position()); final CountersReader counters = aeron.countersReader(); final int counterId = awaitRecordingCounterId(counters, publication.sessionId()); final long recordingId = RecordingPos.getRecordingId(counters, counterId); offerToPosition(publication, messagePrefix, targetPosition); awaitPosition(counters, counterId, publication.position()); aeronArchive.stopRecording(publication); final long segmentFileBasePosition = AeronArchive.segmentFileBasePosition( startPosition, startPosition + (SEGMENT_LENGTH * 2L), TERM_LENGTH, SEGMENT_LENGTH); aeronArchive.detachSegments(recordingId, segmentFileBasePosition); assertEquals(segmentFileBasePosition, aeronArchive.getStartPosition(recordingId)); final long attachSegments = aeronArchive.attachSegments(recordingId); assertEquals(2L, attachSegments); assertEquals(startPosition, aeronArchive.getStartPosition(recordingId)); } } @Test @InterruptAfter(10) public void shouldMigrateSegmentsForStreamJoinedAtTheBeginning() { final String messagePrefix = "Message-Prefix-"; final long targetPosition = (SEGMENT_LENGTH * 3L) + 1; try (Publication publication = aeronArchive.addRecordedPublication(uriBuilder.build(), STREAM_ID)) { final CountersReader counters = aeron.countersReader(); final int dstCounterId = awaitRecordingCounterId(counters, publication.sessionId()); final long dstRecordingId = RecordingPos.getRecordingId(counters, dstCounterId); offerToPosition(publication, messagePrefix, targetPosition); awaitPosition(counters, dstCounterId, publication.position()); aeronArchive.stopRecording(publication); final long startPosition = 0L; final long segmentFileBasePosition = AeronArchive.segmentFileBasePosition( startPosition, SEGMENT_LENGTH * 2L, TERM_LENGTH, SEGMENT_LENGTH); final long count = aeronArchive.purgeSegments(dstRecordingId, segmentFileBasePosition); assertEquals(2L, count); assertEquals(segmentFileBasePosition, aeronArchive.getStartPosition(dstRecordingId)); final long srcRecordingId; final String migrateChannel = uriBuilder .initialPosition(startPosition, publication.initialTermId(), TERM_LENGTH) .endpoint("localhost:4444") .build(); try (Publication migratePub = aeronArchive.addRecordedExclusivePublication(migrateChannel, STREAM_ID)) { final int srcCounterId = awaitRecordingCounterId(counters, migratePub.sessionId()); srcRecordingId = RecordingPos.getRecordingId(counters, srcCounterId); offerToPosition(migratePub, messagePrefix, segmentFileBasePosition); awaitPosition(counters, srcCounterId, migratePub.position()); aeronArchive.stopRecording(migratePub); } aeronArchive.truncateRecording(srcRecordingId, segmentFileBasePosition); final long migratedSegments = aeronArchive.migrateSegments(srcRecordingId, dstRecordingId); assertEquals(2L, migratedSegments); assertEquals(startPosition, aeronArchive.getStartPosition(dstRecordingId)); } } @Test @InterruptAfter(10) public void shouldMigrateSegmentsForStreamNotSegmentAligned() { final String messagePrefix = "Message-Prefix-"; final int initialTermId = 7; final long targetPosition = (SEGMENT_LENGTH * 3L) + 1; final long startPosition = (TERM_LENGTH * 2L) + (FRAME_ALIGNMENT * 2L); uriBuilder.initialPosition(startPosition, initialTermId, TERM_LENGTH); try (Publication publication = aeronArchive.addRecordedExclusivePublication(uriBuilder.build(), STREAM_ID)) { final CountersReader counters = aeron.countersReader(); final int dstCounterId = awaitRecordingCounterId(counters, publication.sessionId()); final long dstRecordingId = RecordingPos.getRecordingId(counters, dstCounterId); offerToPosition(publication, messagePrefix, targetPosition); awaitPosition(counters, dstCounterId, publication.position()); aeronArchive.stopRecording(publication); final long segmentFileBasePosition = AeronArchive.segmentFileBasePosition( startPosition, startPosition + (SEGMENT_LENGTH * 2L), TERM_LENGTH, SEGMENT_LENGTH); final long purgedSegments = aeronArchive.purgeSegments(dstRecordingId, segmentFileBasePosition); assertEquals(2L, purgedSegments); assertEquals(segmentFileBasePosition, aeronArchive.getStartPosition(dstRecordingId)); final long srcRecordingId; final String migrateChannel = uriBuilder .initialPosition(startPosition, initialTermId, TERM_LENGTH) .endpoint("localhost:4444") .build(); try (Publication migratePub = aeronArchive.addRecordedExclusivePublication(migrateChannel, STREAM_ID)) { final int srcCounterId = awaitRecordingCounterId(counters, migratePub.sessionId()); srcRecordingId = RecordingPos.getRecordingId(counters, srcCounterId); offerToPosition(migratePub, messagePrefix, segmentFileBasePosition); awaitPosition(counters, srcCounterId, migratePub.position()); aeronArchive.stopRecording(migratePub); } aeronArchive.truncateRecording(srcRecordingId, segmentFileBasePosition); final long migratedSegments = aeronArchive.migrateSegments(srcRecordingId, dstRecordingId); assertEquals(2L, migratedSegments); assertEquals(startPosition, aeronArchive.getStartPosition(dstRecordingId)); assertEquals(startPosition, aeronArchive.getStopPosition(srcRecordingId)); } } @Test @InterruptAfter(10) public void shouldPurgeRecording() { final String messagePrefix = "Message-Prefix-"; final long targetPosition = (SEGMENT_LENGTH * 3L) + 1; try (Publication publication = aeronArchive.addRecordedPublication(uriBuilder.build(), STREAM_ID)) { final CountersReader counters = aeron.countersReader(); final int counterId = awaitRecordingCounterId(counters, publication.sessionId()); final long newRecordingId = RecordingPos.getRecordingId(counters, counterId); offerToPosition(publication, messagePrefix, targetPosition); awaitPosition(counters, counterId, publication.position()); final MutableReference<RecordingSignal> signalRef = new MutableReference<>(); final RecordingSignalConsumer consumer = (controlSessionId, correlationId, recordingId, subscriptionId, position, transitionType) -> { if (newRecordingId == recordingId) { signalRef.set(transitionType); } }; final RecordingSignalAdapter adapter = new RecordingSignalAdapter( aeronArchive.controlSessionId(), ERROR_CONTROL_LISTENER, consumer, aeronArchive.controlResponsePoller().subscription(), FRAGMENT_LIMIT); aeronArchive.stopRecording(publication); assertEquals(RecordingSignal.STOP, awaitSignal(signalRef, adapter)); aeronArchive.purgeRecording(newRecordingId); assertEquals(RecordingSignal.DELETE, awaitSignal(signalRef, adapter)); } } }
9242b46fa5958398d401f719010c1dd376bb0633
668
java
Java
app/src/main/java/zsf/com/android/coolweather/model/Province.java
jackshi007/coolweather
3310d7a0af7d2c781190975391126b92a5cb7929
[ "Apache-2.0" ]
2
2016-10-12T07:42:40.000Z
2016-10-12T07:42:41.000Z
app/src/main/java/zsf/com/android/coolweather/model/Province.java
jackshi007/coolweather
3310d7a0af7d2c781190975391126b92a5cb7929
[ "Apache-2.0" ]
null
null
null
app/src/main/java/zsf/com/android/coolweather/model/Province.java
jackshi007/coolweather
3310d7a0af7d2c781190975391126b92a5cb7929
[ "Apache-2.0" ]
null
null
null
18.555556
54
0.633234
1,002,381
package zsf.com.android.coolweather.model; /** * Created by zhangsf on 16-10-12. */ public class Province { private int id; private String provinceName; private String provinceCode; public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getProvinceCode() { return provinceCode; } public void setProvinceCode(String provinceCode) { this.provinceCode = provinceCode; } }
9242b513b351f65c51ffa6f4b70ecd6bbbce3e19
1,001
java
Java
src/main/gen/com/bich/idl/psi/impl/IdlDeclaratorsImpl.java
chris060986/intellij-idl-support
9fc40ff5aef00a3b4cf25893aad54971ebc9e78b
[ "Apache-2.0" ]
null
null
null
src/main/gen/com/bich/idl/psi/impl/IdlDeclaratorsImpl.java
chris060986/intellij-idl-support
9fc40ff5aef00a3b4cf25893aad54971ebc9e78b
[ "Apache-2.0" ]
null
null
null
src/main/gen/com/bich/idl/psi/impl/IdlDeclaratorsImpl.java
chris060986/intellij-idl-support
9fc40ff5aef00a3b4cf25893aad54971ebc9e78b
[ "Apache-2.0" ]
null
null
null
27.805556
88
0.774226
1,002,382
// This is a generated file. Not intended for manual editing. package com.bich.idl.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.bich.idl.psi.IdlTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.bich.idl.psi.*; public class IdlDeclaratorsImpl extends ASTWrapperPsiElement implements IdlDeclarators { public IdlDeclaratorsImpl(ASTNode node) { super(node); } public void accept(@NotNull IdlVisitor visitor) { visitor.visitDeclarators(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof IdlVisitor) accept((IdlVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List<IdlDeclarator> getDeclaratorList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, IdlDeclarator.class); } }
9242b7d96a467154bb6b11c8c30c85d7a54ee956
1,767
java
Java
core/src/main/java/com/github/nicholasren/monitoring/prometheus/collector/TransactionLatencyCollector.java
nicholasren/prometheus-springboot-support
003a7f04b0329813edc5d5b158d793413be78cf1
[ "MIT" ]
null
null
null
core/src/main/java/com/github/nicholasren/monitoring/prometheus/collector/TransactionLatencyCollector.java
nicholasren/prometheus-springboot-support
003a7f04b0329813edc5d5b158d793413be78cf1
[ "MIT" ]
null
null
null
core/src/main/java/com/github/nicholasren/monitoring/prometheus/collector/TransactionLatencyCollector.java
nicholasren/prometheus-springboot-support
003a7f04b0329813edc5d5b158d793413be78cf1
[ "MIT" ]
null
null
null
33.980769
103
0.693831
1,002,383
package com.github.nicholasren.monitoring.prometheus.collector; import static com.github.nicholasren.monitoring.prometheus.support.Aspects.targetClassOf; import static com.github.nicholasren.monitoring.prometheus.support.Aspects.targetMethodOf; import java.util.Optional; import com.github.nicholasren.monitoring.prometheus.support.CheckedSupplier; import io.prometheus.client.Histogram; import org.aspectj.lang.ProceedingJoinPoint; public final class TransactionLatencyCollector { private final Histogram metric; private final TransactionNameResolver resolver; public static TransactionLatencyCollector create() { return new TransactionLatencyCollector(metric(), TransactionNameResolver.create()); } public Object measure(ProceedingJoinPoint pjp) throws Throwable { Optional<String> name = resolver.nameOf(targetClassOf(pjp), targetMethodOf(pjp)); if (name.isPresent()) { return measure(name.get(), pjp::proceed); } else { return pjp.proceed(); } } private Object measure(String transactionName, CheckedSupplier<Object> supplier) throws Throwable { Histogram.Timer timer = metric.labels(transactionName).startTimer(); try { return supplier.get(); } finally { timer.observeDuration(); } } TransactionLatencyCollector(Histogram metric, TransactionNameResolver resolver) { this.metric = metric; this.resolver = resolver; } private static Histogram metric() { return Histogram.build() .name("controller_latency_seconds") .labelNames("transaction") .help("Controller latency in seconds") .register(); } }
9242b89e4b352a095bb0dc28fff23d1d309ae3bf
12,050
java
Java
sbi-service/src/main/java/no/norstore/storebioinfo/handlers/DataSetTypeRequestHandler.java
elixir-no-nels/nels-core
b7988f3b85456c7c55064a20ca7d832083a3c51d
[ "Apache-2.0" ]
3
2018-05-16T10:44:38.000Z
2020-12-24T10:53:41.000Z
sbi-service/src/main/java/no/norstore/storebioinfo/handlers/DataSetTypeRequestHandler.java
elixir-no-nels/nels-core
b7988f3b85456c7c55064a20ca7d832083a3c51d
[ "Apache-2.0" ]
13
2021-12-10T00:51:17.000Z
2022-02-16T00:55:20.000Z
sbi-service/src/main/java/no/norstore/storebioinfo/handlers/DataSetTypeRequestHandler.java
elixir-no-nels/nels-core
b7988f3b85456c7c55064a20ca7d832083a3c51d
[ "Apache-2.0" ]
null
null
null
59.359606
318
0.536266
1,002,384
package no.norstore.storebioinfo.handlers; import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.Future; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; import no.norstore.storebioinfo.Route; import no.norstore.storebioinfo.constants.JsonKey; import no.norstore.storebioinfo.constants.UrlParam; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import java.util.*; public final class DataSetTypeRequestHandler implements HttpRequestHandler { public void deleteDataSetType(RoutingContext routingContext) { validateRequest(routingContext, () -> { Map<String, Long> map = validateNumericParamOfUrlPath(routingContext, UrlParam.DATASET_TYPE_ID); JsonArray params = new JsonArray(); params.add(map.get(UrlParam.DATASET_TYPE_ID)); Route.vertxDBHelper.count("SELECT count(*) FROM data_set WHERE type IN (SELECT name FROM data_set_type WHERE id=?)", params, countResult -> { if (countResult.succeeded()) { int count = countResult.result(); if (count > 0) { logger.debug("Can't delete this data set type"); routingContext.response().setStatusCode(HttpResponseStatus.PRECONDITION_FAILED.code()) .end(new JsonObject().put(JsonKey.DESCRIPTION, "You can't delete this type, because there are data sets referring to this type.").encodePrettily()); } else { Route.vertxDBHelper.updateMultipleSqlInTransaction(finalResult -> { if (finalResult.succeeded()) { routingContext.response().setStatusCode(HttpResponseStatus.NO_CONTENT.code()).end(); } else { logger.error("Creating data set type failed", finalResult.cause()); routingContext.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()) .end(new JsonObject().put(JsonKey.DESCRIPTION, finalResult.cause().getMessage()).encodePrettily()); } }, (connection, asyncResultHandler) -> connection.updateWithParams("DELETE FROM data_set_type_subtypes WHERE datasettype_id=?", params, deleteDataSetTypeSubtypesResult -> { if (deleteDataSetTypeSubtypesResult.succeeded()) { connection.updateWithParams("DELETE FROM data_set_type WHERE id=?", params, deleteDataSetTypeResult -> { if (deleteDataSetTypeResult.succeeded()) { asyncResultHandler.handle(Future.succeededFuture()); } else { asyncResultHandler.handle(Future.failedFuture(deleteDataSetTypeResult.cause())); } }); } else { asyncResultHandler.handle(Future.failedFuture(deleteDataSetTypeSubtypesResult.cause())); } }) ); } } else { logger.error("Creating data set type failed", countResult.cause()); routingContext.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end(); } }); }); } public void getDataSetTypes(RoutingContext routingContext) { validateRequest(routingContext, () -> { String federatedId = routingContext.request().getHeader(JsonKey.FEDERATED_ID_IN_HEADER); Pair<Optional<String>, Optional<String>> pair = validateUrlParamForReturnPartialResult(routingContext); Optional<String> sort = validateUrlParamForSorting(routingContext, JsonKey.NAME, JsonKey.CREATOR); String sql = "SELECT data_set_type.id, data_set_type.adder, data_set_type.description, data_set_type.name, array_to_string(array(SELECT data_set_type_subtypes.element FROM data_set_type_subtypes WHERE data_set_type.id=data_set_type_subtypes.datasettype_id), ',') AS elements FROM data_set_type"; if (sort.isPresent()) { switch (sort.get()) { case "-name": sql = sql + " order by name desc"; break; case "name": sql = sql + " order by name asc"; break; case "-creator": sql = sql + " order by adder desc"; break; case "creator": sql = sql + " order by adder asc"; break; } } if (pair.getRight().isPresent()) { sql = sql + " offset " + pair.getRight().get(); } if (StringUtils.isEmpty(federatedId)) { sql = sql + " limit " + pair.getLeft().get(); } Route.vertxDBHelper.select(sql, result -> returnResponseWithCount(routingContext, HttpResponseStatus.OK, result, "SELECT count(*) FROM data_set_type")); }); } public void getDataSetType(RoutingContext routingContext) { validateRequest(routingContext, () -> { Map<String, Long> map = validateNumericParamOfUrlPath(routingContext, UrlParam.DATASET_TYPE_ID); String sql = "SELECT data_set_type.id, data_set_type.adder, data_set_type.description, data_set_type.name, array_to_string(array(SELECT data_set_type_subtypes.element FROM data_set_type_subtypes WHERE data_set_type.id=data_set_type_subtypes.datasettype_id), ',') AS elements FROM data_set_type WHERE id=?"; Route.vertxDBHelper.getOne(sql, new JsonArray().add(map.get(UrlParam.DATASET_TYPE_ID)), result -> returnResponse(routingContext, HttpResponseStatus.OK, result)); }); } public void createDataSetType(RoutingContext routingContext) { validateRequest(routingContext, () -> { JsonObject body = validateRequestBody(routingContext, JsonKey.NAME, JsonKey.DESCRIPTION, JsonKey.SUBTYPE, JsonKey.CREATOR); String name = body.getString(JsonKey.NAME); String description = body.getString(JsonKey.DESCRIPTION); JsonArray subtype = body.getJsonArray(JsonKey.SUBTYPE); String creator = body.getString(JsonKey.CREATOR); String typeId = UUID.randomUUID().toString(); Route.vertxDBHelper.updateMultipleSqlInTransaction(finalResult -> { if (finalResult.succeeded()) { routingContext.response().setStatusCode(HttpResponseStatus.CREATED.code()).end(); } else { logger.error("Creating data set type failed", finalResult.cause()); routingContext.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()) .end(new JsonObject().put(JsonKey.DESCRIPTION, finalResult.cause().getMessage()).encodePrettily()); } }, (connection, asyncResultHandler) -> connection.updateWithParams( "INSERT INTO data_set_type (adder, description, name, type_id) VALUES (?, ?, ?, ?)", new JsonArray().add(creator).add(description).add(name).add(typeId), insertDataSetTypeResult -> { if (insertDataSetTypeResult.succeeded()) { long dataSetTypeId = insertDataSetTypeResult.result().getKeys().getLong(0); List<String> params = new ArrayList<>(subtype.size()); subtype.stream().map(String.class::cast).forEach(element -> params.add("(" + dataSetTypeId + ",'" + element + "')")); connection.update( "INSERT INTO data_set_type_subtypes (datasettype_id, element) VALUES " + StringUtils.join(params, ","), insertDataSetTypeSubtypesResult -> { if (insertDataSetTypeSubtypesResult.succeeded()) { asyncResultHandler.handle(Future.succeededFuture()); } else { asyncResultHandler.handle(Future.failedFuture(insertDataSetTypeSubtypesResult.cause())); } }); } else { asyncResultHandler.handle(Future.failedFuture(insertDataSetTypeResult.cause())); } }) ); }); } public void searchDataSetTypes(RoutingContext routingContext) { validateRequest(routingContext, () -> { Pair<Optional<String>, Optional<String>> pair = validateUrlParamForReturnPartialResult(routingContext); Optional<String> sort = validateUrlParamForSorting(routingContext, JsonKey.NAME, JsonKey.CREATOR); JsonObject body = validateRequestBody(routingContext, JsonKey.QUERY); String query = body.getString(JsonKey.QUERY); StringBuilder builder = new StringBuilder(); builder.append("SELECT data_set_type.id, data_set_type.adder, data_set_type.description, data_set_type.name, array_to_string(array(SELECT data_set_type_subtypes.element FROM data_set_type_subtypes WHERE data_set_type.id=data_set_type_subtypes.datasettype_id), ',') AS elements FROM data_set_type "); builder.append("WHERE LOWER(data_set_type.name) LIKE LOWER('%" + query + "%') OR LOWER(data_set_type.adder) LIKE LOWER('%" + query + "%') "); if (sort.isPresent()) { switch (sort.get()) { case "-name": builder.append("order by name desc"); break; case "name": builder.append("order by name asc"); break; case "-creator": builder.append("order by adder desc"); break; case "creator": builder.append("order by adder asc"); break; default: builder.append("order by name"); } } else { builder.append("ORDER BY name"); } if (pair.getRight().isPresent()) { builder.append(" offset ").append(pair.getRight().get()); } builder.append(" limit ").append(pair.getLeft().get()); String countSql = "SELECT count(*) FROM data_set_type WHERE LOWER(name) LIKE LOWER('%" + query + "%') OR LOWER(adder) LIKE LOWER('%" + query + "%')"; Route.vertxDBHelper.select(builder.toString(), result -> returnResponseWithCount(routingContext, HttpResponseStatus.OK, result, countSql)); }); } }
9242b8d5aa9dbad53cfb1c442aa22844ba82a68f
1,689
java
Java
common/src/main/java/qiangyt/springboot_example/common/bean/BeanCopyer.java
qiangyt/springboot-example-monothilic
ac76f2ab257e2f660853e66a8074f05d036dc94b
[ "Apache-2.0" ]
null
null
null
common/src/main/java/qiangyt/springboot_example/common/bean/BeanCopyer.java
qiangyt/springboot-example-monothilic
ac76f2ab257e2f660853e66a8074f05d036dc94b
[ "Apache-2.0" ]
null
null
null
common/src/main/java/qiangyt/springboot_example/common/bean/BeanCopyer.java
qiangyt/springboot-example-monothilic
ac76f2ab257e2f660853e66a8074f05d036dc94b
[ "Apache-2.0" ]
null
null
null
24.838235
74
0.629366
1,002,385
package qiangyt.springboot_example.common.bean; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; import org.springframework.cglib.beans.BeanCopier; // import org.springframework.cglib.core.Converter; import lombok.Getter; /** * */ @Getter public class BeanCopyer<SOURCE,TARGET> { private final BeanCopier copier; private final Supplier<TARGET> targetSupplier; private Function<Integer, TARGET[]> targetArraySupplier; // private final Converter converter; public BeanCopyer( Class<SOURCE> sourceClass, Class<TARGET> targetClass, Supplier<TARGET> targetSupplier, Function<Integer, TARGET[]> targetArraySupplier) { this.targetSupplier = targetSupplier; this.targetArraySupplier = targetArraySupplier; this.copier = BeanCopier.create(sourceClass, targetClass, false); } public TARGET newTarget() { return getTargetSupplier().get(); } public TARGET[] newTargetArray(int length) { return getTargetArraySupplier().apply(length); } public TARGET copy(SOURCE source) { if (source == null) { return null; } TARGET r = newTarget(); getCopier().copy(source, r, null); return r; } public TARGET[] copy(Iterable<SOURCE> sources) { if (sources == null) { return null; } List<TARGET> r = new ArrayList<>(); for (SOURCE src: sources) { r.add(copy(src)); } return r.toArray(getTargetArraySupplier().apply(r.size())); } }
9242b964d6d6575e8386cab3ee4652192d6c6120
145
java
Java
dex_src/com/xunlei/tdlive/protocol/XLLiveFollowRequest$FollowInfo.java
megahertz0/android_thunder
3304c95a751ac228362bc53b47ed92e292510155
[ "MIT" ]
11
2018-08-05T16:00:47.000Z
2021-11-18T02:55:40.000Z
dex_src/com/xunlei/tdlive/protocol/XLLiveFollowRequest$FollowInfo.java
megahertz0/android_thunder
3304c95a751ac228362bc53b47ed92e292510155
[ "MIT" ]
null
null
null
dex_src/com/xunlei/tdlive/protocol/XLLiveFollowRequest$FollowInfo.java
megahertz0/android_thunder
3304c95a751ac228362bc53b47ed92e292510155
[ "MIT" ]
9
2017-02-05T16:24:32.000Z
2021-11-18T02:55:42.000Z
20.714286
51
0.77931
1,002,387
package com.xunlei.tdlive.protocol; public final class XLLiveFollowRequest$FollowInfo { public int is_follow; public String playerid; }
9242b9ac2bb7526b21259da923d809fbe0263d2d
7,218
java
Java
main/src/cgeo/geocaching/ui/Formatter.java
mirsch/cgeo
5c6bf40981223e4e8cdc3de0da8e273fc2d11b50
[ "Apache-2.0" ]
2
2016-09-03T00:08:53.000Z
2017-02-21T06:47:14.000Z
main/src/cgeo/geocaching/ui/Formatter.java
mirsch/cgeo
5c6bf40981223e4e8cdc3de0da8e273fc2d11b50
[ "Apache-2.0" ]
null
null
null
main/src/cgeo/geocaching/ui/Formatter.java
mirsch/cgeo
5c6bf40981223e4e8cdc3de0da8e273fc2d11b50
[ "Apache-2.0" ]
null
null
null
37.59375
142
0.650319
1,002,388
package cgeo.geocaching.ui; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.Geocache; import cgeo.geocaching.R; import cgeo.geocaching.Waypoint; import cgeo.geocaching.enumerations.CacheListType; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.WaypointType; import org.apache.commons.lang3.StringUtils; import android.content.Context; import android.text.format.DateUtils; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public abstract class Formatter { /** Text separator used for formatting texts */ public static final String SEPARATOR = " · "; private static final Context context = CgeoApplication.getInstance().getBaseContext(); /** * Generate a time string according to system-wide settings (locale, 12/24 hour) * such as "13:24". * * @param date * milliseconds since the epoch * @return the formatted string */ public static String formatTime(long date) { return DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_TIME); } /** * Generate a date string according to system-wide settings (locale, date format) * such as "20 December" or "20 December 2010". The year will only be included when necessary. * * @param date * milliseconds since the epoch * @return the formatted string */ public static String formatDate(long date) { return DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_DATE); } /** * Generate a date string according to system-wide settings (locale, date format) * such as "20 December 2010". The year will always be included, making it suitable * to generate long-lived log entries. * * @param date * milliseconds since the epoch * @return the formatted string */ public static String formatFullDate(long date) { return DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR); } /** * Generate a numeric date string according to system-wide settings (locale, date format) * such as "10/20/2010". * * @param date * milliseconds since the epoch * @return the formatted string */ public static String formatShortDate(long date) { DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); return dateFormat.format(date); } /** * Generate a numeric date string according to system-wide settings (locale, date format) * such as "10/20/2010". Today and yesterday will be presented as strings "today" and "yesterday". * * @param date * milliseconds since the epoch * @return the formatted string */ public static String formatShortDateVerbally(long date) { int diff = cgeo.geocaching.utils.DateUtils.daysSince(date); switch (diff) { case 0: return CgeoApplication.getInstance().getString(R.string.log_today); case 1: return CgeoApplication.getInstance().getString(R.string.log_yesterday); default: return formatShortDate(date); } } /** * Generate a numeric date and time string according to system-wide settings (locale, * date format) such as "7 sept. at 12:35". * * @param date * milliseconds since the epoch * @return the formatted string */ public static String formatShortDateTime(long date) { return DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL); } /** * Generate a numeric date and time string according to system-wide settings (locale, * date format) such as "7 september at 12:35". * * @param date * milliseconds since the epoch * @return the formatted string */ public static String formatDateTime(long date) { return DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME); } public static String formatCacheInfoLong(Geocache cache, CacheListType cacheListType) { final ArrayList<String> infos = new ArrayList<String>(); if (StringUtils.isNotBlank(cache.getGeocode())) { infos.add(cache.getGeocode()); } addShortInfos(cache, infos); if (cache.isPremiumMembersOnly()) { infos.add(CgeoApplication.getInstance().getString(R.string.cache_premium)); } if (cacheListType != CacheListType.OFFLINE && cacheListType != CacheListType.HISTORY && cache.getListId() > 0) { infos.add(CgeoApplication.getInstance().getString(R.string.cache_offline)); } return StringUtils.join(infos, Formatter.SEPARATOR); } public static String formatCacheInfoShort(Geocache cache) { final ArrayList<String> infos = new ArrayList<String>(); addShortInfos(cache, infos); return StringUtils.join(infos, Formatter.SEPARATOR); } private static void addShortInfos(Geocache cache, final ArrayList<String> infos) { if (cache.hasDifficulty()) { infos.add("D " + String.format("%.1f", cache.getDifficulty())); } if (cache.hasTerrain()) { infos.add("T " + String.format("%.1f", cache.getTerrain())); } // don't show "not chosen" for events and virtuals, that should be the normal case if (cache.getSize() != CacheSize.UNKNOWN && cache.showSize()) { infos.add(cache.getSize().getL10n()); } else if (cache.isEventCache()) { final Date hiddenDate = cache.getHiddenDate(); if (hiddenDate != null) { infos.add(Formatter.formatShortDate(hiddenDate.getTime())); } } } public static String formatCacheInfoHistory(Geocache cache) { final ArrayList<String> infos = new ArrayList<String>(3); infos.add(StringUtils.upperCase(cache.getGeocode())); infos.add(Formatter.formatDate(cache.getVisitedDate())); infos.add(Formatter.formatTime(cache.getVisitedDate())); return StringUtils.join(infos, Formatter.SEPARATOR); } public static String formatWaypointInfo(Waypoint waypoint) { final List<String> infos = new ArrayList<String>(3); WaypointType waypointType = waypoint.getWaypointType(); if (waypointType != WaypointType.OWN && waypointType != null) { infos.add(waypointType.getL10n()); } if (Waypoint.PREFIX_OWN.equalsIgnoreCase(waypoint.getPrefix())) { infos.add(CgeoApplication.getInstance().getString(R.string.waypoint_custom)); } else { if (StringUtils.isNotBlank(waypoint.getPrefix())) { infos.add(waypoint.getPrefix()); } if (StringUtils.isNotBlank(waypoint.getLookup())) { infos.add(waypoint.getLookup()); } } return StringUtils.join(infos, Formatter.SEPARATOR); } }
9242baae80035c1248b9ac2c6cad17406c456ad4
1,595
java
Java
turms-server-common/src/main/java/im/turms/server/common/property/env/common/UserStatusProperties.java
MyAllures/turms
1c1d30b02ef0469eca8d6f0fa5b5d80d6f275af1
[ "Apache-2.0" ]
1,008
2019-06-12T23:58:03.000Z
2022-03-28T01:38:39.000Z
turms-server-common/src/main/java/im/turms/server/common/property/env/common/UserStatusProperties.java
MyAllures/turms
1c1d30b02ef0469eca8d6f0fa5b5d80d6f275af1
[ "Apache-2.0" ]
940
2019-09-28T00:04:10.000Z
2022-03-30T04:20:28.000Z
turms-server-common/src/main/java/im/turms/server/common/property/env/common/UserStatusProperties.java
MyAllures/turms
1c1d30b02ef0469eca8d6f0fa5b5d80d6f275af1
[ "Apache-2.0" ]
144
2019-06-13T06:00:30.000Z
2022-03-26T16:21:41.000Z
31.9
116
0.749216
1,002,389
/* * Copyright (C) 2019 The Turms Project * https://github.com/turms-im/turms * * 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 im.turms.server.common.property.env.common; import im.turms.server.common.property.metadata.annotation.Description; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.Min; /** * @author James Chen */ @AllArgsConstructor @Builder(toBuilder = true) @Data @NoArgsConstructor public class UserStatusProperties { @Description("Whether to cache the user sessions status") private boolean cacheUserSessionsStatus = true; @Description("The maximum size of the cache of users' sessions status") @Min(-1) private int userSessionsStatusCacheMaxSize = -1; @Description("The life duration of each remote user's sessions status in the cache. " + "Note that the cache will make the presentation of users' sessions status inconsistent during the time") @Min(1) private int userSessionsStatusExpireAfter = 60; }
9242bae734381c56e4bf9274bc3915551c10c8f2
3,794
java
Java
src/main/java/org/clothocad/model/BasicModule.java
CIDARLAB/Clotho3DataModel
8cbea099b2f0d8fb43de2e8451d077617f01bd3a
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/clothocad/model/BasicModule.java
CIDARLAB/Clotho3DataModel
8cbea099b2f0d8fb43de2e8451d077617f01bd3a
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/clothocad/model/BasicModule.java
CIDARLAB/Clotho3DataModel
8cbea099b2f0d8fb43de2e8451d077617f01bd3a
[ "BSD-3-Clause" ]
null
null
null
28.961832
112
0.529257
1,002,390
/* * 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 org.clothocad.model; import java.util.HashMap; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.json.simple.JSONObject; /** * * @author Nicholas Roehner * @author mardian */ @NoArgsConstructor public class BasicModule extends Module { @NotNull @Size(min=1) @Getter @Setter //@ReferenceCollection protected Set<Feature> features; public BasicModule(String name, ModuleRole role, Set<Feature> features, Person author) { super(name, role, author); this.features = features; } public BasicModule(String name, String description, ModuleRole role, Set<Feature> features, Person author) { super(name, description, role, author); this.features = features; } public void addFeature(Feature feature) { if (features == null) { features = new HashSet<Feature>(); } features.add(feature); } public Map getMap(){ Map map = new HashMap(); map.put("name", this.getName()); map.put("author", this.getAuthor().getName()); map.put("description", this.getDescription()); if (features!=null) { int i = 0; for (Feature feature : features) { map.put("feature" + i, feature.getName()); i++; } } map.put("role", this.role.toString()); if (influences!=null) { int j = 0; for (Influence influence : influences) { map.put("influence" + j, influence.getName()); j++; } } if (parentModule!=null) { map.put("name", this.parentModule.getName()); } return map; } public JSONObject getJSON(){ JSONObject obj = new JSONObject(); obj.put("name", this.getName()); obj.put("author", this.getAuthor().getName()); obj.put("description", this.getDescription()); if (features!=null) { int i = 0; for (Feature feature : features) { obj.put("feature" + i, feature.getName()); i++; } } obj.put("role", this.role.toString()); if (influences!=null) { int j = 0; for (Influence influence : influences) { obj.put("influence" + j, influence.getName()); j++; } } if (parentModule!=null) { obj.put("name", this.parentModule.getName()); } return obj; } public String toString(){ String str = ""; str += "Name : " + this.getName() + "\n"; str += "Author : " + this.getAuthor().getName() + "\n"; str += "Description : " + this.getDescription() + "\n"; if (features!=null) { int i = 0; for (Feature feature : features) { str += "Feature " + i + " : " + feature.getName() + "\n"; i++; } } str += "Module Role : " + this.role.toString(); if (influences!=null) { int j = 0; for (Influence influence : influences) { str += "\nInfluence " + j + " : " + influence.getName(); j++; } } if (parentModule!=null) { str += "\nParent Module : " + this.parentModule.getName(); } return str; } }
9242bb303272585c778d3b99c91ad2e3c39d9aeb
195
java
Java
agileway-vfs/src/main/java/com/jn/agileway/vfs/filter/IsFileFilter.java
fangjinuo/avoid996
dd80e537ce27f2697ee39d242c47d552e4ce336b
[ "Apache-2.0" ]
null
null
null
agileway-vfs/src/main/java/com/jn/agileway/vfs/filter/IsFileFilter.java
fangjinuo/avoid996
dd80e537ce27f2697ee39d242c47d552e4ce336b
[ "Apache-2.0" ]
null
null
null
agileway-vfs/src/main/java/com/jn/agileway/vfs/filter/IsFileFilter.java
fangjinuo/avoid996
dd80e537ce27f2697ee39d242c47d552e4ce336b
[ "Apache-2.0" ]
null
null
null
19.5
49
0.728205
1,002,391
package com.jn.agileway.vfs.filter; import org.apache.commons.vfs2.FileType; public class IsFileFilter extends FileTypeFilter{ public IsFileFilter() { super(FileType.FILE); } }
9242bb5dd49e7bde29d633e6b7530176539a8ead
4,144
java
Java
src/main/java/ru/betterend/world/structures/piece/NBTPiece.java
rjuven2401/BetterEnd
634927b2eba82751d7c004a457576fefc1b3487b
[ "MIT" ]
null
null
null
src/main/java/ru/betterend/world/structures/piece/NBTPiece.java
rjuven2401/BetterEnd
634927b2eba82751d7c004a457576fefc1b3487b
[ "MIT" ]
null
null
null
src/main/java/ru/betterend/world/structures/piece/NBTPiece.java
rjuven2401/BetterEnd
634927b2eba82751d7c004a457576fefc1b3487b
[ "MIT" ]
null
null
null
41.44
183
0.756274
1,002,392
package ru.betterend.world.structures.piece; import net.minecraft.core.BlockPos; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.StructureFeatureManager; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import ru.bclib.util.MHelper; import ru.bclib.util.StructureHelper; import ru.betterend.registry.EndStructures; import ru.betterend.util.StructureErode; import ru.betterend.world.biome.EndBiome; import java.util.Random; public class NBTPiece extends BasePiece { private ResourceLocation structureID; private Rotation rotation; private Mirror mirror; private StructureTemplate structure; private BlockPos pos; private int erosion; private boolean cover; public NBTPiece(ResourceLocation structureID, StructureTemplate structure, BlockPos pos, int erosion, boolean cover, Random random) { super(EndStructures.NBT_PIECE, random.nextInt(), null); this.structureID = structureID; this.structure = structure; this.rotation = Rotation.getRandom(random); this.mirror = Mirror.values()[random.nextInt(3)]; this.pos = StructureHelper.offsetPos(pos, structure, rotation, mirror); this.erosion = erosion; this.cover = cover; makeBoundingBox(); } public NBTPiece(StructurePieceSerializationContext type, CompoundTag tag) { super(EndStructures.NBT_PIECE, tag); makeBoundingBox(); } @Override protected void addAdditionalSaveData(CompoundTag tag) { super.addAdditionalSaveData(tag); tag.putString("structureID", structureID.toString()); tag.putInt("rotation", rotation.ordinal()); tag.putInt("mirror", mirror.ordinal()); tag.putInt("erosion", erosion); tag.put("pos", NbtUtils.writeBlockPos(pos)); tag.putBoolean("cover", cover); } @Override protected void fromNbt(CompoundTag tag) { structureID = new ResourceLocation(tag.getString("structureID")); rotation = Rotation.values()[tag.getInt("rotation")]; mirror = Mirror.values()[tag.getInt("mirror")]; erosion = tag.getInt("erosion"); pos = NbtUtils.readBlockPos(tag.getCompound("pos")); cover = tag.getBoolean("cover"); structure = StructureHelper.readStructure(structureID); } @Override public void postProcess(WorldGenLevel world, StructureFeatureManager arg, ChunkGenerator chunkGenerator, Random random, BoundingBox blockBox, ChunkPos chunkPos, BlockPos blockPos) { BoundingBox bounds = BoundingBox.fromCorners(new Vec3i( blockBox.minX(), this.boundingBox.minY(), blockBox.minZ() ), new Vec3i(blockBox.maxX(), this.boundingBox.maxX(), blockBox.maxZ())); StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror).setBoundingBox(bounds); structure.placeInWorld(world, pos, pos, placementData, random, 2); if (erosion > 0) { int x1 = MHelper.min(bounds.maxX(), boundingBox.maxX()); int x0 = MHelper.max(bounds.minX(), boundingBox.minX()); int z1 = MHelper.min(bounds.maxZ(), boundingBox.maxZ()); int z0 = MHelper.max(bounds.minZ(), boundingBox.minZ()); bounds = BoundingBox.fromCorners(new Vec3i(x0, bounds.minY(), z0), new Vec3i(x1, bounds.maxY(), z1)); StructureErode.erode(world, bounds, erosion, random); } if (cover) { StructureErode.cover(world, bounds, random, EndBiome.Config.DEFAULT_MATERIAL.getTopMaterial()); } } private void makeBoundingBox() { this.boundingBox = StructureHelper.getStructureBounds(pos, structure, rotation, mirror); } }
9242bbf0071c94227d4007c33dad35db76165512
259
java
Java
lib/src/main/java/com/github/tianma8023/formatter/SunriseSunsetLabelFormatter.java
ansh2166/SunriseSunsetView
a0edb20dab861e575b21bf2f1506ed5fd455dbf4
[ "Apache-2.0" ]
26
2018-02-05T05:49:34.000Z
2022-02-02T11:58:28.000Z
lib/src/main/java/com/github/tianma8023/formatter/SunriseSunsetLabelFormatter.java
ansh2166/SunriseSunsetView
a0edb20dab861e575b21bf2f1506ed5fd455dbf4
[ "Apache-2.0" ]
null
null
null
lib/src/main/java/com/github/tianma8023/formatter/SunriseSunsetLabelFormatter.java
ansh2166/SunriseSunsetView
a0edb20dab861e575b21bf2f1506ed5fd455dbf4
[ "Apache-2.0" ]
5
2018-08-05T07:07:41.000Z
2021-12-12T00:49:08.000Z
17.266667
47
0.725869
1,002,393
package com.github.tianma8023.formatter; import com.github.tianma8023.model.Time; /** * 日出日落标签格式化 */ public interface SunriseSunsetLabelFormatter { String formatSunriseLabel(Time sunrise); String formatSunsetLabel(Time sunset); }
9242bc60225408c2ff8a1a56c14347f6e95087c5
4,603
java
Java
test/controllers/ApplicationTest.java
AgileDropZone/trombi
6ba5e324f1c04f9688b9ae03816242590f515a71
[ "BSD-2-Clause" ]
null
null
null
test/controllers/ApplicationTest.java
AgileDropZone/trombi
6ba5e324f1c04f9688b9ae03816242590f515a71
[ "BSD-2-Clause" ]
null
null
null
test/controllers/ApplicationTest.java
AgileDropZone/trombi
6ba5e324f1c04f9688b9ae03816242590f515a71
[ "BSD-2-Clause" ]
null
null
null
34.350746
74
0.716272
1,002,394
package controllers; import org.junit.Test; import play.mvc.Http.Response; import play.test.FunctionalTest; public class ApplicationTest extends FunctionalTest { @Test public void testThatIndexPageWorks() { Response response = GET("/"); assertIsOk(response); assertContentType("text/html", response); assertCharset(play.Play.defaultWebEncoding, response); } @Test public void leTitreDuSiteDoitEtrePresentSurLaPageAccueil() { Response response = GET("/"); assertIsOk(response); assertContentType("text/html", response); assertContentMatch("Bienvenue sur le trombinoscope", response); } @Test public void laPageAccueilDoitContenirRobertDupond() { Response response = GET("/"); assertIsOk(response); assertContentType("text/html", response); assertContentMatch("Robert DUPOND", response); } @Test public void laRechercheDoitRemonterRobertDupond() { Response response = GET("/recherche/dupo"); assertIsOk(response); assertContentType("text/html", response); assertContentMatch("Robert DUPOND", response); String strReponse = getContent(response); assertTrue("Henry MARTIN ne devrait pas apparaitre sur cette page", strReponse.indexOf("Henry MARTIN") == -1); } @Test public void laPageAccueilNeDoitAfficherQue15Profils() { Response response = GET("/"); assertIsOk(response); assertContentType("text/html", response); // Vis-à-vis du jeu de données de test, nous devons avoir // sur la première page de Céline Ampère à Carine Lavoisier // Les profils de Henry MARTIN à Naomie WATT doivent // apparaitre en page 2 assertContentMatch("C&eacute;line AMP&Egrave;RE", response); assertContentMatch("Carine LAVOISIER", response); String strReponse = getContent(response); assertTrue("Henry MARTIN ne devrait pas apparaitre sur cette page", strReponse.indexOf("Henry MARTIN") == -1); assertTrue("Naomie WATT ne devrait pas apparaitre sur cette page", strReponse.indexOf("Naomie WATT") == -1); } @Test public void laSecondePageDoitAfficherLesProfilsDe16a30() { Response response = GET("/page2"); assertIsOk(response); assertContentType("text/html", response); // Vis-à-vis du jeu de données de test, nous devons avoir // sur la seconde page de Henry MARTIN à Naomie WATT // Les profils de Céline Ampère à Carine Lavoisier doivent // apparaitre en page 1 assertContentMatch("Henry MARTIN", response); assertContentMatch("Naomie WATT", response); String strReponse = getContent(response); assertTrue("Céline AMPÈRE ne devrait pas apparaitre sur cette page", strReponse.indexOf("C&eacute;line AMP&Egrave;RE") == -1); assertTrue("Carine LAVOISIER ne devrait pas apparaitre sur cette page", strReponse.indexOf("Carine LAVOISIER") == -1); } @Test public void laRechercheNeDoitAfficherQue15Profils() { Response response = GET("/page1/a"); assertIsOk(response); assertContentType("text/html", response); // Vis-à-vis du jeu de données de test, nous devons avoir // sur la première page de Céline Ampère à Henry MARTIN // -> Robert DUPOND ne doit pas remonter car il ne répond // pas aux critères de recherche // Les profils de Anaïs MENDELEÏEV à Naomie WATT doivent // apparaitre en page 2 assertContentMatch("C&eacute;line AMP&Egrave;RE", response); assertContentMatch("Henry MARTIN", response); String strReponse = getContent(response); assertTrue("Robert DUPOND ne répond pas aux critères de recherche", strReponse.indexOf("Robert DUPOND") == -1); assertTrue("Anaïs MENDELEÏEV ne devrait pas apparaitre sur cette page", strReponse.indexOf("Ana&iuml;s MENDELE&Iuml;EV") == -1); } @Test public void laSecondepageDeRechercheDoitAfficherDesProfilsFiltrés() { Response response = GET("/page2/a"); assertIsOk(response); assertContentType("text/html", response); // Vis-à-vis du jeu de données de test et du critère recherché, // nous devons avoir sur la seconde page de Anaïs MENDELEÏEV à // Naomie WATT // Les profils de Céline Ampère à Henry MARTIN doivent // apparaitre en page 1 assertContentMatch("Ana&iuml;s MENDELE&Iuml;EV", response); assertContentMatch("Naomie WATT", response); String strReponse = getContent(response); assertTrue("Céline AMPÈRE ne devrait pas apparaitre sur cette page", strReponse.indexOf("C&eacute;line AMP&Egrave;RE") == -1); assertTrue("Henry MARTIN ne devrait pas apparaitre sur cette page", strReponse.indexOf("Henry MARTIN") == -1); } }
9242bc8b334f1eb38f1799db8c4ad7c4c050de68
26,953
java
Java
Android/HairApp2/app/src/main/java/com/example/neha/hairapp/HairAppCode.java
NehaNishikant/git
61a7e63c9419940561fc6787269da6e6bc130747
[ "MIT" ]
null
null
null
Android/HairApp2/app/src/main/java/com/example/neha/hairapp/HairAppCode.java
NehaNishikant/git
61a7e63c9419940561fc6787269da6e6bc130747
[ "MIT" ]
null
null
null
Android/HairApp2/app/src/main/java/com/example/neha/hairapp/HairAppCode.java
NehaNishikant/git
61a7e63c9419940561fc6787269da6e6bc130747
[ "MIT" ]
null
null
null
47.789007
152
0.544503
1,002,395
package com.example.neha.hairapp; import android.content.Context; import android.graphics.Color; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; public class HairAppCode extends AppCompatActivity { LinearLayout fragmentContainer; FragmentManager fragmentManager; FragmentTransaction transaction; Button quizTab; Button listTab; Button favsTab; Button submit; Button save; TextView currentFrag; RelativeLayout rel; public static ArrayList<HairStyle> styles=new ArrayList<HairStyle>(); public static ArrayList<HairStyle> favstyles=new ArrayList<HairStyle>(); public static String[]answers=new String[10]; public static Fragment[]frags=new Fragment[2]; public static int currentQuestion; public static QuizFragment qfrag; public static MCQuestionFragment mcfrag; public static TFQuestionFragment tffrag; public static QuizEndFragment quizendfrag; public static ListFragment listfrag; public static FavoritesFragment favfrag; public static TutorialFFragment tutffrag; public static TutorialLFragment tutlfrag; public static String currentTab; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hair_app_code); qfrag= new QuizFragment(); mcfrag= new MCQuestionFragment(); tffrag= new TFQuestionFragment(); styles=new ArrayList<HairStyle>(); favstyles=new ArrayList<HairStyle>(); HairStyle frenchbraid=new HairStyle("FRENCH BRAID", R.drawable.frenchbraid, 1); //yeah you need better styles HairStyle threebuns=new HairStyle("THREE BUNS", R.drawable.threebuns, 2); //fix all drawables HairStyle fishtail=new HairStyle("FISHTAIL BRAID", R.drawable.fishtailbraid, 3); HairStyle frenchbun=new HairStyle("FRENCH BUN", R.drawable.frenchbun, 4); HairStyle sidebraid=new HairStyle("SIDE BRAID", R.drawable.sidebraid, 5); HairStyle messybun=new HairStyle("MESSY BUN", R.drawable.messybun, 6); HairStyle waterfallbraid=new HairStyle("WATERFALL BRAID", R.drawable.waterfallbraid, 7); HairStyle ballerinabun=new HairStyle("BALLERINA BUN", R.drawable.ballerinabun, 8); styles.add(frenchbraid); styles.add(threebuns); styles.add(fishtail); styles.add(frenchbun); styles.add(sidebraid); styles.add(messybun); styles.add(waterfallbraid); styles.add(ballerinabun); try{ BufferedReader reader= new BufferedReader (new InputStreamReader(openFileInput("datafile.json"))); String s=(reader.readLine()); //Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show(); JSONObject obj=new JSONObject(s); currentQuestion=obj.getInt("currentQuestion"); currentTab=obj.getString("currentTab"); if (currentQuestion>0){ if (currentQuestion<=5){ mcfrag.setAnswer(obj.getString("answer")); } else if (currentQuestion<=10){ tffrag.setAnswer(obj.getString("answer")); } } int sizeFav = obj.getJSONObject("favorites").length(); Toast.makeText(getApplicationContext(), sizeFav+" ", Toast.LENGTH_SHORT).show(); for(int i=0; i<sizeFav;i++) { favstyles.add(getStyle(obj.getJSONObject("favorites").getInt(i+" "))); if (!getStyle(obj.getJSONObject("favorites").getInt(i+" ")).isFavorite()){ getStyle(obj.getJSONObject("favorites").getInt(i+" ")).changeFavorite(); } Toast.makeText(getApplicationContext(), obj.getJSONObject("favorites").getString(i+" "), Toast.LENGTH_SHORT).show(); } JSONObject obj2=obj.getJSONObject("answerList"); for (int i=0; i<10; i++){ answers[i]=obj2.getString(i+" "); } //int i=0; //while (obj.getJSONObject("favorites").getString(i+" ")!=null){ // favstyles.add(getStyle(obj.getJSONObject("favorites").getString(i+" "))); // i++; //} //quiz result } catch (IOException e){ e.printStackTrace(); } catch (JSONException e){ e.printStackTrace(); }; quizendfrag= new QuizEndFragment(); listfrag=new ListFragment(); favfrag=new FavoritesFragment(); tutffrag=new TutorialFFragment(); tutlfrag=new TutorialLFragment(); fragmentContainer=(LinearLayout)findViewById(R.id.fragment_id); quizTab=(Button)findViewById(R.id.quizTab_id); listTab=(Button)findViewById(R.id.listTab_id); favsTab=(Button)findViewById(R.id.favsTab_id); submit=(Button)findViewById(R.id.submit_id); currentFrag=(TextView)findViewById(R.id.currentFrag_id); save=(Button)findViewById(R.id.saveAll_id); rel=(RelativeLayout)findViewById(R.id.relLay_id); rel.setBackgroundColor(Color.CYAN); fragmentManager=getSupportFragmentManager(); transaction=fragmentManager.beginTransaction(); if (currentTab==null) { currentQuestion = 0; submit.setVisibility(View.GONE); /*if (qfrag.isAdded()){ transaction = fragmentManager.beginTransaction(); transaction.remove(qfrag); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.fragment_id, qfrag); transaction.commit(); fragmentManager.executePendingTransactions(); quizTab.setTextColor(Color.LTGRAY); currentTab = "quiz"; currentFrag.setText("Current Tab: Quiz"); } else if (currentTab.equals("quiz")){ if(currentQuestion==11){ QuizEndFragment quizendfrag=new QuizEndFragment(); submit.setVisibility(View.GONE); /*if (quizendfrag.isAdded()){ transaction = fragmentManager.beginTransaction(); transaction.remove(quizendfrag); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.fragment_id, quizendfrag); transaction.commit(); fragmentManager.executePendingTransactions(); quizTab.setTextColor(Color.LTGRAY); currentTab = "quiz"; currentFrag.setText("Current Tab: Quiz"); } if (currentQuestion==0){ submit.setVisibility(View.GONE); /*if (qfrag.isAdded()){ transaction = fragmentManager.beginTransaction(); transaction.remove(qfrag); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.fragment_id, qfrag); transaction.commit(); fragmentManager.executePendingTransactions(); quizTab.setTextColor(Color.LTGRAY); currentTab = "quiz"; currentFrag.setText("Current Tab: Quiz"); } else if (currentQuestion<=5){ submit.setVisibility(View.VISIBLE); transaction = fragmentManager.beginTransaction(); /*if (mcfrag.isAdded()){ transaction = fragmentManager.beginTransaction(); transaction.remove(mcfrag); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ transaction.replace(R.id.fragment_id, mcfrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); quizTab.setTextColor(Color.LTGRAY); currentTab = "quiz"; currentFrag.setText("Current Tab: Quiz"); if (currentQuestion==1){ mcfrag.setChoices("1. How long do you want your style to last?", "I don't care", "A few hours", "For school", "Over night"); } else if (currentQuestion==2){ mcfrag.setChoices("2. How much time do you have?", "1 minute", "5 minutes", "10 minutes", "15+ minutes"); } else if (currentQuestion==3){ mcfrag.setChoices("3. Which type of hair do you have?", "Straight", "Wavy", "Curly", "Kinky"); } else if (currentQuestion==4){ mcfrag.setChoices("4. Choose a style: ", "Casual", "Fun", "Formal", "Messy"); } else { mcfrag.setChoices("5. How long is your hair", "Short", "Medium", "Long", "Rapunzel"); } } else if (currentQuestion<=10){ submit.setVisibility(View.VISIBLE); transaction = fragmentManager.beginTransaction(); /*if (tffrag.isAdded()){ transaction = fragmentManager.beginTransaction(); transaction.remove(tffrag); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ transaction.replace(R.id.fragment_id, tffrag); transaction.commit(); fragmentManager.executePendingTransactions(); quizTab.setTextColor(Color.LTGRAY); currentTab = "quiz"; currentFrag.setText("Current Tab: Quiz"); if (currentQuestion==6){ tffrag.setChoices("6. Asymmetry is awesome"); } else if (currentQuestion==7){ tffrag.setChoices("7. A good hairstyle is never messy"); } else if (currentQuestion==8){ tffrag.setChoices("8. I love braids"); } else if (currentQuestion==9){ tffrag.setChoices("9. Always try to stand out"); } else { tffrag.setChoices("10. I am comfortable with difficult styles"); } } } else if (currentTab.equals("list")){ submit.setVisibility(View.GONE); transaction = fragmentManager.beginTransaction(); /*if (listfrag.isAdded()){ transaction = fragmentManager.beginTransaction(); transaction.remove(listfrag); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ transaction.replace(R.id.fragment_id, listfrag); transaction.commit(); fragmentManager.executePendingTransactions(); listTab.setTextColor(Color.LTGRAY); currentTab = "list"; currentFrag.setText("Current Tab: List"); } else if (currentTab.equals("favs")){ submit.setVisibility(View.GONE); transaction = fragmentManager.beginTransaction(); /*if (favfrag.isAdded()){ transaction = fragmentManager.beginTransaction(); transaction.remove(favfrag); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ transaction.replace(R.id.fragment_id, favfrag); transaction.commit(); fragmentManager.executePendingTransactions(); favsTab.setTextColor(Color.LTGRAY); currentTab = "favs"; currentFrag.setText("Current Tab: Favorites"); } save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveInformation(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(openFileInput("datafile.json"))); String s = (reader.readLine()); //Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show(); } catch (IOException e){}; } }); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentQuestion<=5) { answers[currentQuestion - 1] = mcfrag.getAnswer(); } else if (currentQuestion<=10) { answers[currentQuestion - 1] = tffrag.getAnswer(); } if (answers[currentQuestion-1].equals(" ")) { Toast.makeText(getApplicationContext(), "Please choose an answer", Toast.LENGTH_SHORT).show(); } else { currentQuestion++; if (currentQuestion == 6) { /*if (tffrag.isAdded()) { transaction=fragmentManager.beginTransaction(); transaction.remove(tffrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ submit.setVisibility(View.VISIBLE); transaction = fragmentManager.beginTransaction(); transaction.remove(mcfrag); transaction.replace(R.id.fragment_id, tffrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); } else if (currentQuestion == 11) { /*if (quizendfrag.isAdded()) { transaction = fragmentManager.beginTransaction(); transaction.remove(quizendfrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ submit.setVisibility(View.VISIBLE); QuizEndFragment quizendfrag = new QuizEndFragment(); transaction = fragmentManager.beginTransaction(); transaction.remove(tffrag); transaction.replace(R.id.fragment_id, quizendfrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); } if (currentQuestion<=5){ mcfrag.setAnswer(" "); if (currentQuestion==1){ mcfrag.setChoices("1. How long do you want your style to last?", "I don't care", "A few hours", "For school", "Over night"); } else if (currentQuestion==2){ mcfrag.setChoices("2. How much time do you have?", "1 minute", "5 minutes", "10 minutes", "15+ minutes"); } else if (currentQuestion==3){ mcfrag.setChoices("3. Which type of hair do you have?", "Straight", "Wavy", "Curly", "Kinky"); } else if (currentQuestion==4){ mcfrag.setChoices("4. Choose a style: ", "Casual", "Fun", "Formal", "Messy"); } else { mcfrag.setChoices("5. How long is your hair", "Short", "Medium", "Long", "Rapunzel"); } } else if (currentQuestion <= 10) { tffrag.resetAnswer(); if (currentQuestion==6){ tffrag.setChoices("6. Asymmetry is awesome"); } else if (currentQuestion==7){ tffrag.setChoices("7. A good hairstyle is never messy"); } else if (currentQuestion==8){ tffrag.setChoices("8. I love braids"); } else if (currentQuestion==9){ tffrag.setChoices("9. Always try to stand out"); } else { tffrag.setChoices("10. I am comfortable with difficult styles"); } } } } }); quizTab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentTab="quiz"; if (currentQuestion==0) { /*if (qfrag.isAdded()) { transaction = fragmentManager.beginTransaction(); transaction.remove(qfrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); submit.setVisibility(View.VISIBLE); }*/ submit.setVisibility(View.GONE); for(Fragment fragment:getSupportFragmentManager().getFragments()){ transaction = fragmentManager.beginTransaction(); transaction.remove(fragment).commit(); } transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.fragment_id, qfrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); } else if (currentQuestion<=5) { /*if (mcfrag.isAdded()) { transaction = fragmentManager.beginTransaction(); transaction.remove(mcfrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ submit.setVisibility(View.VISIBLE); for(Fragment fragment:getSupportFragmentManager().getFragments()){ transaction = fragmentManager.beginTransaction(); transaction.remove(fragment).commit(); } transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.fragment_id, mcfrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); if (currentQuestion == 1){ mcfrag.setChoices("1. How long do you want your style to last?", "I don't care", "A few hours", "For school", "Over night"); } else if (currentQuestion==2){ mcfrag.setChoices("2. How much time do you have?", "1 minute", "5 minutes", "10 minutes", "15+ minutes"); } else if (currentQuestion==3){ mcfrag.setChoices("3. Which type of hair do you have?", "Straight", "Wavy", "Curly", "Kinky"); } else if (currentQuestion==4){ mcfrag.setChoices("4. Choose a style: ", "Casual", "Fun", "Formal", "Messy"); } else { mcfrag.setChoices("5. How long is your hair", "Short", "Medium", "Long", "Rapunzel"); } } else if (currentQuestion<=10){ submit.setVisibility(View.VISIBLE); /*if (tffrag.isAdded()){ transaction=fragmentManager.beginTransaction(); transaction.remove(tffrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); }*/ for(Fragment fragment:getSupportFragmentManager().getFragments()){ transaction = fragmentManager.beginTransaction(); transaction.remove(fragment).commit(); } transaction=fragmentManager.beginTransaction(); transaction.replace(R.id.fragment_id, tffrag); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); if (currentQuestion==6){ tffrag.setChoices("6. Asymmetry is awesome"); } else if (currentQuestion==7){ tffrag.setChoices("7. A good hairstyle is never messy"); } else if (currentQuestion==8){ tffrag.setChoices("8. I love braids"); } else if (currentQuestion==9){ tffrag.setChoices("9. Always try to stand out"); } else { tffrag.setChoices("10. I am comfortable with difficult styles"); } } else { //code to find out quiz results for(Fragment fragment:getSupportFragmentManager().getFragments()){ transaction = fragmentManager.beginTransaction(); transaction.remove(fragment).commit(); } transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.fragment_id, new QuizEndFragment()); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); submit.setVisibility(View.GONE); } currentFrag.setText("Current Tab: Quiz"); quizTab.setTextColor(Color.LTGRAY); listTab.setTextColor(Color.BLACK); favsTab.setTextColor(Color.BLACK); } }); listTab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { submit.setVisibility(View.GONE); currentTab="list"; for(Fragment fragment:getSupportFragmentManager().getFragments()){ transaction = fragmentManager.beginTransaction(); transaction.remove(fragment).commit(); } transaction=fragmentManager.beginTransaction(); transaction.replace(R.id.fragment_id, new ListFragment()); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); currentFrag.setText("Current Tab: Recommendations"); quizTab.setTextColor(Color.BLACK); listTab.setTextColor(Color.LTGRAY); favsTab.setTextColor(Color.BLACK); } }); favsTab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { submit.setVisibility(View.GONE); currentTab="favs"; for(Fragment fragment:getSupportFragmentManager().getFragments()){ transaction = fragmentManager.beginTransaction(); transaction.remove(fragment).commit(); } transaction=fragmentManager.beginTransaction(); transaction.replace(R.id.fragment_id, new FavoritesFragment()); transaction.addToBackStack(null); transaction.commit(); fragmentManager.executePendingTransactions(); currentFrag.setText("Current Tab: Favorites"); quizTab.setTextColor(Color.BLACK); listTab.setTextColor(Color.BLACK); favsTab.setTextColor(Color.LTGRAY); } }); } public HairStyle getStyle(int tag){ for (int i=0; i<styles.size(); i++){ if (tag==styles.get(i).getTag()) return styles.get(i); } return new HairStyle("fake", R.drawable.frenchbraid, 0); } public void saveInformation(){ String filename="datafile.json"; JSONObject obj=new JSONObject(); try { obj.put("currentTab", currentTab); obj.put("currentQuestion", currentQuestion); if ((currentQuestion<=5)&&(currentQuestion>0)) { obj.put("answer", mcfrag.getAnswer()); } else if ((currentQuestion<=10)&&(currentQuestion>0)) { obj.put("answer", tffrag.getAnswer()); } else obj.put("answer", " "); //cQ=0 or 11 if (currentQuestion==11) { obj.put("quizResult", quizendfrag.getResult()); //change to quiz result } else obj.put("quizResult", " "); JSONObject obj2=new JSONObject(); for (int i=0; i<10; i++){ obj2.put(i+" ", answers[i]); } obj.put("answerList", obj2); JSONObject obj3=new JSONObject(); for (int i=0; i<favstyles.size(); i++){ obj3.put(i+" ", favstyles.get(i).getTag()); } obj.put("favorites", obj3); } catch (JSONException e){}; try{ OutputStreamWriter writer=new OutputStreamWriter(openFileOutput(filename, Context.MODE_WORLD_WRITEABLE)); writer.write(obj.toString()); writer.close(); }catch (FileNotFoundException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } } }
9242bcda219c3d387bb24fb99e56e01010dfd371
1,533
java
Java
java/classes/com/facebook/common/internal/Closeables.java
gaoht/house
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
[ "Apache-2.0" ]
1
2020-05-08T05:35:32.000Z
2020-05-08T05:35:32.000Z
java/classes/com/facebook/common/internal/Closeables.java
gaoht/house
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
[ "Apache-2.0" ]
null
null
null
java/classes/com/facebook/common/internal/Closeables.java
gaoht/house
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
[ "Apache-2.0" ]
3
2018-09-07T08:15:08.000Z
2020-05-22T03:59:12.000Z
22.217391
121
0.667319
1,002,396
package com.facebook.common.internal; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; public final class Closeables { @VisibleForTesting static final Logger logger = Logger.getLogger(Closeables.class.getName()); public static void close(@Nullable Closeable paramCloseable, boolean paramBoolean) throws IOException { if (paramCloseable == null) { return; } try { paramCloseable.close(); return; } catch (IOException paramCloseable) { if (paramBoolean) { logger.log(Level.WARNING, "IOException thrown while closing Closeable.", paramCloseable); return; } throw paramCloseable; } } public static void closeQuietly(@Nullable InputStream paramInputStream) { try { close(paramInputStream, true); return; } catch (IOException paramInputStream) { throw new AssertionError(paramInputStream); } } public static void closeQuietly(@Nullable Reader paramReader) { try { close(paramReader, true); return; } catch (IOException paramReader) { throw new AssertionError(paramReader); } } } /* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/facebook/common/internal/Closeables.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
9242bcfd7fc4c2127445cc18820d1287f0b2c5ff
41,931
java
Java
ode4j/src/org/ode4j/ode/internal/DxBody.java
YvesBoyadjian/Koin3D
b49547f938886261dc9feae3c2f63f19680a2cfa
[ "BSD-3-Clause" ]
14
2018-06-29T21:55:55.000Z
2021-12-30T12:18:21.000Z
ode4j/src/org/ode4j/ode/internal/DxBody.java
YvesBoyadjian/Koin3D
b49547f938886261dc9feae3c2f63f19680a2cfa
[ "BSD-3-Clause" ]
null
null
null
ode4j/src/org/ode4j/ode/internal/DxBody.java
YvesBoyadjian/Koin3D
b49547f938886261dc9feae3c2f63f19680a2cfa
[ "BSD-3-Clause" ]
4
2018-11-15T02:00:18.000Z
2021-12-12T05:42:31.000Z
27.203764
114
0.677322
1,002,397
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: [email protected] Web: www.q12.org * * Open Dynamics Engine 4J, Copyright (C) 2009-2014 Tilmann Zaeschke * * All rights reserved. Email: [email protected] Web: www.ode4j.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file ODE-LICENSE-BSD.TXT and ODE4J-LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT, ODE-LICENSE-BSD.TXT and ODE4J-LICENSE-BSD.TXT for more * * details. * * * *************************************************************************/ package org.ode4j.ode.internal; import static org.ode4j.ode.OdeMath.dAddVectorCross3; import static org.ode4j.ode.OdeMath.dCalcVectorDot3; import static org.ode4j.ode.OdeMath.dMultiply0_331; import static org.ode4j.ode.OdeMath.dMultiply1_331; import static org.ode4j.ode.OdeMath.dNormalize3; import static org.ode4j.ode.OdeMath.dNormalize4; import static org.ode4j.ode.OdeMath.dOrthogonalizeR; import static org.ode4j.ode.internal.Common.DBL_EPSILON; import static org.ode4j.ode.internal.Common.dAASSERT; import static org.ode4j.ode.internal.Common.dCos; import static org.ode4j.ode.internal.Common.dDEBUGMSG; import static org.ode4j.ode.internal.Common.dFabs; import static org.ode4j.ode.internal.Common.dIASSERT; import static org.ode4j.ode.internal.Common.dRecip; import static org.ode4j.ode.internal.Common.dSin; import static org.ode4j.ode.internal.Common.dSqrt; import static org.ode4j.ode.internal.Common.dUASSERT; import static org.ode4j.ode.internal.Matrix.dInvertPDMatrix; import static org.ode4j.ode.internal.Rotation.dDQfromW; import static org.ode4j.ode.internal.Rotation.dQMultiply0; import static org.ode4j.ode.internal.Rotation.dQfromR; import static org.ode4j.ode.internal.Rotation.dRfromQ; import org.ode4j.math.DMatrix3; import org.ode4j.math.DMatrix3C; import org.ode4j.math.DQuaternion; import org.ode4j.math.DQuaternionC; import org.ode4j.math.DVector3; import org.ode4j.math.DVector3C; import org.ode4j.ode.DBody; import org.ode4j.ode.DGeom; import org.ode4j.ode.DJoint; import org.ode4j.ode.DMass; import org.ode4j.ode.DMassC; import org.ode4j.ode.internal.Objects_H.DxPosR; import org.ode4j.ode.internal.Objects_H.DxPosRC; import org.ode4j.ode.internal.Objects_H.dxAutoDisable; import org.ode4j.ode.internal.Objects_H.dxDampingParameters; import org.ode4j.ode.internal.cpp4j.java.Ref; import org.ode4j.ode.internal.joints.DxJoint; import org.ode4j.ode.internal.joints.DxJointNode; import org.ode4j.ode.internal.joints.OdeJointsFactoryImpl; import org.ode4j.ode.internal.processmem.DxWorldProcessContext; /** * rigid body (dynamics object). */ public class DxBody extends DObject implements DBody, Cloneable { // some body flags // enum Body { // dxBodyFlagFiniteRotation (1), // use finite rotations // dxBodyFlagFiniteRotationAxis (2), // use finite rotations only along axis // dxBodyDisabled (4), // body is disabled // dxBodyNoGravity (8), // body is not influenced by gravity // dxBodyAutoDisable (16), // enable auto-disable on body // dxBodyLinearDamping (32), // using linear damping // dxBodyAngularDamping (64), // using angular damping // dxBodyMaxAngularSpeed (128); // using maximum angular speed // private final int _i; // Body(int i) { // _i = i; // } // }; private static final int dxBodyFlagFiniteRotation = 1; // use finite rotations private static final int dxBodyFlagFiniteRotationAxis= 2; // use finite rotations only along axis static final int dxBodyDisabled = 4; // body is disabled static final int dxBodyNoGravity =8; // body is not influenced by gravity static final int dxBodyAutoDisable =16; // enable auto-disable on body static final int dxBodyLinearDamping =32; // using linear damping static final int dxBodyAngularDamping =64; // use angular damping static final int dxBodyMaxAngularSpeed =128; // use maximum angular speed private static final int dxBodyGyroscopic =256; // use gyroscopic term // public dxJointNode firstjoint; // list of attached joints //TODO public final Ref<DxJointNode> firstjoint = new Ref<DxJointNode>(); // list of attached joints //unsigned int flags; // some dxBodyFlagXXX flags // public dGeom geom; // first collision geom associated with body public DxGeom geom; // first collision geom associated with body DxMass mass; // mass parameters about POR DMatrix3 invI; // inverse of mass.I public double invMass; // 1 / mass.mass public DxPosR _posr; // position and orientation of point of reference public DQuaternion _q; // orientation quaternion public DVector3 lvel; // linear and angular velocity of POR public DVector3 avel; DVector3 facc,tacc; // force and torque accumulators DVector3 finite_rot_axis; // finite rotation axis, unit length or 0=none // auto-disable information dxAutoDisable adis; // auto-disable parameters double adis_timeleft; // time left to be idle int adis_stepsleft; // steps left to be idle // dVector3* average_lvel_buffer; // buffer for the linear average velocity calculation // dVector3* average_avel_buffer; // buffer for the angular average velocity calculation // unsigned int average_counter; // counter/index to fill the average-buffers DVector3[] average_lvel_buffer; // buffer for the linear average velocity calculation DVector3[] average_avel_buffer; // buffer for the angular average velocity calculation //unsigned int average_counter; // counter/index to fill the average-buffers int average_ready; // indicates ( with = 1 ), if the Body's buffers are ready for average-calculations BodyMoveCallBack moved_callback; // let the user know the body moved private dxDampingParameters dampingp; // damping parameters, depends on flags double max_angular_speed; // limit the angular velocity to this magnitude protected DxBody(DxWorld w) { super(w); } DxWorld dBodyGetWorld () { return world; } public static DxBody dBodyCreate (DxWorld w) { dAASSERT (w); DxBody b = new DxBody(w); b.firstjoint.set(null); b.flags = 0; b.geom = null; b.average_lvel_buffer = null; b.average_avel_buffer = null; //TZ b.mass = new DxMass(); b.mass.dMassSetParameters (1, 0,0,0,1,1,1,0,0,0); b.invI = new DMatrix3(); //MAT.dSetZero (b.invI.v,4*3); b.invI.set00( 1 ); b.invI.set11( 1 ); b.invI.set22( 1 ); b.invMass = 1; b._posr = new DxPosR(); //MAT.dSetZero (b.posr.pos.v,4); b._q = new DQuaternion(); //MAT.dSetZero (b._q.v,4); b._q.set( 0, 1 ); b._posr.Rw().setIdentity(); b.lvel = new DVector3(); //MAT.dSetZero (b.lvel.v,4); b.avel = new DVector3(); //MAT.dSetZero (b.avel.v,4); b.facc = new DVector3(); //MAT.dSetZero (b.facc.v,4); b.tacc = new DVector3(); //MAT.dSetZero (b.tacc.v,4); b.finite_rot_axis = new DVector3(); //MAT.dSetZero (b.finite_rot_axis.v,4); //addObjectToList (b,(dObject **) &w.firstbody); addObjectToList(b, w.firstbody); w.nb++; // set auto-disable parameters b.average_avel_buffer = b.average_lvel_buffer = null; // no buffer at beginning b.dBodySetAutoDisableDefaults (); // must do this after adding to world b.adis_stepsleft = b.adis.idle_steps; b.adis_timeleft = b.adis.idle_time; b.average_counter = 0; b.average_ready = 0; // average buffer not filled on the beginning b.dBodySetAutoDisableAverageSamplesCount(b.adis.average_samples); b.moved_callback = null; b.dBodySetDampingDefaults(); // must do this after adding to world b.flags |= w.body_flags & dxBodyMaxAngularSpeed; b.max_angular_speed = w.max_angular_speed; b.flags |= dxBodyGyroscopic; return b; } // public void dBodyDestroy (dxBody b) public void dBodyDestroy () { //dAASSERT (b); // all geoms that link to this body must be notified that the body is about // to disappear. note that the call to dGeomSetBody(geom,0) will result in // dGeomGetBodyNext() returning 0 for the body, so we must get the next body // before setting the body to 0. DxGeom next_geom = null; for (DxGeom geom2 = geom; geom2 != null; geom2 = next_geom) { next_geom = geom2.dGeomGetBodyNext (); geom2.dGeomSetBody (null); } // detach all neighbouring joints, then delete this body. DxJointNode n = firstjoint.get(); while (n != null) { // sneaky trick to speed up removal of joint references (black magic) //TODO use equals? n.joint.node[(n == n.joint.node[0])?1:0].body = null; DxJointNode next = n.next; n.next = null; n.joint.removeJointReferencesFromAttachedBodies (); n = next; } removeObjectFromList (); world.nb--; // delete the average buffers //TZ nothing to do // if(average_lvel_buffer!= null) // { // delete[] (average_lvel_buffer); // average_lvel_buffer = null; // } // if(average_avel_buffer!= null) // { // delete[] (average_avel_buffer); // average_avel_buffer = null; // } // // delete b; DESTRUCTOR(); } //public void dBodySetData (dxBody b, Object data) public void dBodySetData (Object data) { userdata = data; } public Object dBodyGetData () { return userdata; } public void dBodySetPosition (double x, double y, double z) { _posr.pos.set(x, y, z); // notify all attached geoms that this body has moved for (DxGeom geom2 = geom; geom2 != null; geom2 = geom2.dGeomGetBodyNext ()) geom2.dGeomMoved (); } //TZ public void dBodySetPosition (DVector3C xyz) { _posr.pos.set(xyz); // notify all attached geoms that this body has moved for (DxGeom geom2 = geom; geom2 != null; geom2 = geom2.dGeomGetBodyNext ()) geom2.dGeomMoved (); } // public void dBodySetRotation (dxBody b, final dMatrix3 R) public void dBodySetRotation (DMatrix3C R) { //memcpy(b->posr.R, R, sizeof(dMatrix3)); _posr.Rw().set(R); dOrthogonalizeR(_posr.Rw()); dQfromR (_q, R); dNormalize4 (_q); // notify all attached geoms that this body has moved for (DxGeom geom2 = geom; geom2 != null; geom2 = geom2.dGeomGetBodyNext ()) { geom2.dGeomMoved (); } } // void dBodySetQuaternion (dxBody b, final dQuaternion q) public void dBodySetQuaternion (DQuaternionC q) { //dAASSERT (q); // _q.v[0] = q.v[0]; // _q.v[1] = q.v[1]; // _q.v[2] = q.v[2]; // _q.v[3] = q.v[3]; _q.set(q); dNormalize4 (_q); //dQtoR (b.q, b.posr.R); dRfromQ(_posr.Rw(), _q); // notify all attached geoms that this body has moved for (DxGeom geom2 = geom; geom2 != null; geom2 = geom2.dGeomGetBodyNext ()) geom2.dGeomMoved (); } public void dBodySetLinearVel (double x, double y, double z) { lvel.set(x, y, z); } public void dBodySetLinearVel (DVector3C xyz) { lvel.set(xyz); } public void dBodySetAngularVel (double x, double y, double z) { avel.set(x, y, z); } public void dBodySetAngularVel (DVector3C xyz) { avel.set(xyz); } // public final double[] dBodyGetPosition (dxBody b) public DVector3C dBodyGetPosition () { return _posr.pos(); } void dBodyCopyPosition (DxBody b, DVector3 pos) { // dAASSERT (b); //double[] src = b.posr.pos.v; // pos.v[0] = src[0]; // pos.v[1] = src[1]; // pos.v[2] = src[2]; pos.set(b._posr.pos()); } // public final double[] dBodyGetRotation (dxBody b) public DMatrix3C dBodyGetRotation () { return _posr.R(); } void dBodyCopyRotation (DxBody b, DMatrix3 R) { // dAASSERT (b); // final double[] src = b.posr.R.v; // R.v[0] = src[0]; // R.v[1] = src[1]; // R.v[2] = src[2]; // R.v[3] = src[3]; // R.v[4] = src[4]; // R.v[5] = src[5]; // R.v[6] = src[6]; // R.v[7] = src[7]; // R.v[8] = src[8]; // R.v[9] = src[9]; // R.v[10] = src[10]; // R.v[11] = src[11]; //TODO clean up commented code and other TODO below (add(f), e.t.c) R.set(b._posr.R()); } // final double[] dBodyGetQuaternion (dxBody b) public DQuaternionC dBodyGetQuaternion () { return _q; } void dBodyCopyQuaternion (DxBody b, DQuaternion quat) { quat.set(b._q); } // final double[] dBodyGetLinearVel (dxBody b) public DVector3C dBodyGetLinearVel () { return lvel; } // final double[] dBodyGetAngularVel (dxBody b) public DVector3C dBodyGetAngularVel () { return avel; } //void dBodySetMass (dxBody b, final dMass mass) public void dBodySetMass (DMassC mass2) { //dAASSERT (mass2 ); dIASSERT(mass2.check()); // The centre of mass must be at the origin. // Use dMassTranslate( mass, -mass->c[0], -mass->c[1], -mass->c[2] ) // to correct it. DVector3C mass2c = mass2.getC(); dUASSERT( Math.abs( mass2c.get0() ) <= DBL_EPSILON && Math.abs( mass2c.get1() ) <= DBL_EPSILON && Math.abs( mass2c.get2() ) <= DBL_EPSILON, "The centre of mass must be at the origin." ); //memcpy (b.mass,mass,sizeof(dMass)); mass.set(mass2); if (!dInvertPDMatrix (mass._I, invI)) { dDEBUGMSG ("inertia must be positive definite!"); invI.setIdentity(); } invMass = dRecip(mass._mass); } public void dBodyGetMass (DxMass mass2) //void dBodyGetMass (dxBody b, dMass *mass) { mass2.set(mass); //memcpy (mass,b.mass,sizeof(dMass)); } // public void dBodyAddForce (dxBody b, double fx, double fy, double fz) public void dBodyAddForce (double fx, double fy, double fz) { facc.add(fx, fy, fz); } public void dBodyAddForce (DVector3C f) { facc.add(f); } // public void dBodyAddTorque (dxBody b, double fx, double fy, double fz) public void dBodyAddTorque (double fx, double fy, double fz) { tacc.add(fx, fy, fz); } public void dBodyAddTorque (DVector3C f) { tacc.add(f); } void dBodyAddRelForce (DVector3C f) { DVector3 t2 = new DVector3(); dMultiply0_331 (t2,_posr.R(),f); facc.add(t2); } // void dBodyAddRelTorque (dxBody b, double fx, double fy, double fz) public void dBodyAddRelTorque (DVector3C f) { DVector3 t2 = new DVector3(); dMultiply0_331 (t2,_posr.R(),f); tacc.add(t2); } void dBodyAddForceAtPos (DVector3C f, DVector3C p) { facc.add(f); DVector3 q = p.reSub(_posr.pos()); dAddVectorCross3 (tacc,q,f); } void dBodyAddForceAtRelPos (DVector3C f, DVector3C prel) { DVector3 p = new DVector3(); dMultiply0_331 (p,_posr.R(),prel); facc.add(f); dAddVectorCross3 (tacc,p,f); } void dBodyAddRelForceAtPos (DVector3C frel, DVector3C p) { DVector3 f = new DVector3(); dMultiply0_331 (f,_posr.R(),frel); facc.add(f); DVector3 q = p.reSub(_posr.pos()); dAddVectorCross3 (tacc,q,f); } // void dBodyAddRelForceAtRelPos (dxBody b, double fx, double fy, double fz, // double px, double py, double pz) void dBodyAddRelForceAtRelPos (DVector3C fRel, DVector3C pRel) { // dVector3 frel = new dVector3(fx, fy, fz); // dVector3 prel = new dVector3(px, py, pz); DVector3 f = new DVector3(); DVector3 p = new DVector3(); // frel.v[0] = fx; // frel.v[1] = fy; // frel.v[2] = fz; // frel.v[3] = 0; // prel.v[0] = px; // prel.v[1] = py; // prel.v[2] = pz; // prel.v[3] = 0; dMultiply0_331 (f,_posr.R(),fRel); dMultiply0_331 (p,_posr.R(),pRel); // b.facc.v[0] += f.v[0]; // b.facc.v[1] += f.v[1]; // b.facc.v[2] += f.v[2]; facc.add(f); dAddVectorCross3 (tacc,p,f); } DVector3C dBodyGetForce () { //dAASSERT (b); return facc; } DVector3C dBodyGetTorque () { return tacc; } void dBodySetForce (double x, double y, double z) { facc.set(x, y, z); } void dBodySetForce (DVector3C xyz) { facc.set(xyz); } void dBodySetTorque (double x, double y, double z) { tacc.set(x, y, z); } void dBodySetTorque (DVector3C t) { tacc.set(t); } // void dBodyGetRelPointPos (dxBody b, double px, double py, double pz, // dVector3 result) void dBodyGetRelPointPos (DVector3C prel, DVector3 result) { //dVector3 prel = new dVector3(px, py, pz); // dVector3 p = new dVector3(); // prel.v[0] = px; // prel.v[1] = py; // prel.v[2] = pz; // prel.v[3] = 0; // dMULTIPLY0_331 (p,b._posr.R,prel); // result.v[0] = p.v[0] + b._posr.pos.v[0]; // result.v[1] = p.v[1] + b._posr.pos.v[1]; // result.v[2] = p.v[2] + b._posr.pos.v[2]; // result.sum(p, b._posr.pos); dMultiply0_331 (result,_posr.R(),prel); result.add( _posr.pos() ); } // public void dBodyGetRelPointVel (double px, double py, double pz, // dVector3 result) public void dBodyGetRelPointVel (DVector3C prel, DVector3 result) { //dVector3 prel = new dVector3(px, py, pz); DVector3 p = new DVector3(); dMultiply0_331 (p,_posr.R(),prel); result.set(lvel); dAddVectorCross3 (result,avel,p); } // void dBodyGetPointVel (dxBody b, double px, double py, double pz, // dVector3 result) void dBodyGetPointVel (DVector3C prel, DVector3 result) { DVector3 p = new DVector3(prel).sub(_posr.pos()); result.set(lvel); dAddVectorCross3 (result,avel,p); } // void dBodyGetPosRelPoint (dxBody b, double px, double py, double pz, // dVector3 result) void dBodyGetPosRelPoint (DVector3C p, DVector3 result) { DVector3 prel = p.reSub(_posr.pos()); dMultiply1_331 (result,_posr.R(),prel); } // void dBodyVectorToWorld (dxBody b, double px, double py, double pz, // dVector3 result) void dBodyVectorToWorld (DVector3C p, DVector3 result) { dMultiply0_331 (result,_posr.R(),p); } // void dBodyVectorFromWorld (dxBody b, double px, double py, double pz, // dVector3 result) void dBodyVectorFromWorld (DVector3C p, DVector3 result) { dMultiply1_331 (result,_posr.R(),p); } // void dBodySetFiniteRotationMode (dxBody b, int mode) void dBodySetFiniteRotationMode (boolean mode) { flags &= ~(dxBodyFlagFiniteRotation | dxBodyFlagFiniteRotationAxis); if (mode) { flags |= dxBodyFlagFiniteRotation; if (finite_rot_axis.get0() != 0 || finite_rot_axis.get1() != 0 || finite_rot_axis.get2() != 0) { flags |= dxBodyFlagFiniteRotationAxis; } } } // void dBodySetFiniteRotationAxis (dxBody b, double x, double y, double z) void dBodySetFiniteRotationAxis (DVector3C xyz) { finite_rot_axis.set(xyz); if (xyz.get0() != 0 || xyz.get1() != 0 || xyz.get2() != 0) { dNormalize3 (finite_rot_axis); flags |= dxBodyFlagFiniteRotationAxis; } else { flags &= ~dxBodyFlagFiniteRotationAxis; } } boolean dBodyGetFiniteRotationMode () { return (flags & dxBodyFlagFiniteRotation) != 0; } void dBodyGetFiniteRotationAxis (DVector3 result) { result.set(finite_rot_axis); } int dBodyGetNumJoints () { int count=0; //TODO return array size for (DxJointNode n=firstjoint.get(); n != null; n=n.next, count++); return count; } DxJoint dBodyGetJoint (int index) { int i=0; //TODO return array size for (DxJointNode n=firstjoint.get(); n != null; n=n.next, i++) { if (i == index) return n.joint; } return null; } void dBodySetDynamic () { dBodySetMass(mass); } void dBodySetKinematic () { //dSetZero (b->invI,4*3); invI.setZero(); invMass = 0; } boolean dBodyIsKinematic () { return invMass == 0; } // void dBodyEnable (dxBody b) public void dBodyEnable () { flags &= ~dxBodyDisabled; adis_stepsleft = adis.idle_steps; adis_timeleft = adis.idle_time; // no code for average-processing needed here } /** * flags &amp;= ~dxBodyDisabled. */ //(TZ) public void dBodyEnable_noAdis () { flags &= ~dxBodyDisabled; } // void dBodyDisable (dxBody b) public void dBodyDisable () { flags |= dxBodyDisabled; } /** * @return (flags &amp; dxBodyDisabled) == 0 */ // public boolean dBodyIsEnabled (dxBody b) public boolean dBodyIsEnabled () { return ((flags & dxBodyDisabled) == 0); } // void dBodySetGravityMode (dxBody b, int mode) void dBodySetGravityMode (boolean mode) { if (mode) flags &= ~dxBodyNoGravity; else flags |= dxBodyNoGravity; } /** * @return (flags & dxBodyNoGravity) == 0 */ boolean dBodyGetGravityMode () { return (flags & dxBodyNoGravity) == 0; } // body auto-disable functions double dBodyGetAutoDisableLinearThreshold () { return dSqrt (adis.linear_average_threshold); } void dBodySetAutoDisableLinearThreshold (double linear_average_threshold) { adis.linear_average_threshold = linear_average_threshold * linear_average_threshold; } double dBodyGetAutoDisableAngularThreshold () { return dSqrt (adis.angular_average_threshold); } void dBodySetAutoDisableAngularThreshold (double angular_average_threshold) { adis.angular_average_threshold = angular_average_threshold * angular_average_threshold; } int dBodyGetAutoDisableAverageSamplesCount () { return adis.average_samples; } // void dBodySetAutoDisableAverageSamplesCount (dxBody b, unsigned int average_samples_count) void dBodySetAutoDisableAverageSamplesCount (int average_samples_count) { adis.average_samples = average_samples_count; // update the average buffers if(average_lvel_buffer != null) { //TZ delete[] b.average_lvel_buffer; average_lvel_buffer = null; } if(average_avel_buffer != null) { //TZ delete[] b.average_avel_buffer; average_avel_buffer = null; } if(adis.average_samples > 0) { average_lvel_buffer = DVector3.newArray(adis.average_samples); average_avel_buffer = DVector3.newArray(adis.average_samples); } else { average_lvel_buffer = null; average_avel_buffer = null; } // new buffer is empty average_counter = 0; average_ready = 0; } int dBodyGetAutoDisableSteps () { return adis.idle_steps; } void dBodySetAutoDisableSteps (int steps) { adis.idle_steps = steps; } double dBodyGetAutoDisableTime () { return adis.idle_time; } void dBodySetAutoDisableTime (double time) { adis.idle_time = time; } boolean dBodyGetAutoDisableFlag () { return ((flags & dxBodyAutoDisable) != 0); } // void dBodySetAutoDisableFlag (dxBody b, int do_auto_disable) void dBodySetAutoDisableFlag (boolean do_auto_disable) { if (!do_auto_disable) { flags &= ~dxBodyAutoDisable; // (mg) we should also reset the IsDisabled state to correspond to the DoDisabling flag flags &= ~dxBodyDisabled; adis.idle_steps = world.getAutoDisableSteps(); adis.idle_time = world.getAutoDisableTime(); // resetting the average calculations too dBodySetAutoDisableAverageSamplesCount( world.getAutoDisableAverageSamplesCount() ); } else { flags |= dxBodyAutoDisable; } } void dBodySetAutoDisableDefaults () { DxWorld w = world; adis = w.adis.clone(); dBodySetAutoDisableFlag ( (w.body_flags & dxBodyAutoDisable)!=0); } // body damping functions double dBodyGetLinearDamping() { return dampingp.linear_scale; } void dBodySetLinearDamping(double scale) { if (scale != 0) flags |= dxBodyLinearDamping; else flags &= ~dxBodyLinearDamping; dampingp.linear_scale = scale; } double dBodyGetAngularDamping() { return dampingp.angular_scale; } void dBodySetAngularDamping(double scale) { if (scale != 0) flags |= dxBodyAngularDamping; else flags &= ~dxBodyAngularDamping; dampingp.angular_scale = scale; } void dBodySetDamping(double linear_scale, double angular_scale) { dBodySetLinearDamping(linear_scale); dBodySetAngularDamping(angular_scale); } double dBodyGetLinearDampingThreshold() { return dSqrt(dampingp.linear_threshold); } void dBodySetLinearDampingThreshold(double threshold) { dampingp.linear_threshold = threshold*threshold; } double dBodyGetAngularDampingThreshold() { return dSqrt(dampingp.angular_threshold); } void dBodySetAngularDampingThreshold(double threshold) { dampingp.angular_threshold = threshold*threshold; } void dBodySetDampingDefaults() { DxWorld w = world; dampingp = w.dampingp.clone(); //unsigned final int mask = dxBodyLinearDamping | dxBodyAngularDamping; flags &= ~mask; // zero them flags |= w.body_flags & mask; } double dBodyGetMaxAngularSpeed() { return max_angular_speed; } void dBodySetMaxAngularSpeed(double max_speed) { if (max_speed < Double.MAX_VALUE) flags |= dxBodyMaxAngularSpeed; else flags &= ~dxBodyMaxAngularSpeed; max_angular_speed = max_speed; } // void dBodySetMovedCallback(dxBody b, void (*callback)(dxBody)) public void dBodySetMovedCallback(BodyMoveCallBack callback) { moved_callback = callback; } // dxGeom dBodyGetFirstGeom(dxBody b) DxGeom dBodyGetFirstGeom() { // dAASSERT(b); return geom; } //TODO check calls for invalid geom (not of this body) DxGeom dBodyGetNextGeom(DxGeom geom) { //dAASSERT(geom); return geom.dGeomGetBodyNext(); } boolean dBodyGetGyroscopicMode() { return (flags & dxBodyGyroscopic) != 0; } void dBodySetGyroscopicMode(boolean enabled) { if (enabled) flags |= dxBodyGyroscopic; else flags &= ~dxBodyGyroscopic; } //**************************************************************************** // body rotation // return sin(x)/x. this has a singularity at 0 so special handling is needed // for small arguments. private static double sinc (double x) { // if |x| < 1e-4 then use a taylor series expansion. this two term expansion // is actually accurate to one LS bit within this range if double precision // is being used - so don't worry! if (dFabs(x) < 1.0e-4) return 1.0 - x*x*0.166666666666666666667; else return dSin(x)/x; } // given a body b, apply its linear and angular rotation over the time // interval h, thereby adjusting its position and orientation. void dxStepBody (double h) { // cap the angular velocity if ((flags & dxBodyMaxAngularSpeed) != 0) { final double max_ang_speed = max_angular_speed; final double aspeed = dCalcVectorDot3( avel, avel ); if (aspeed > max_ang_speed*max_ang_speed) { final double coef = max_ang_speed/dSqrt(aspeed); avel.scale(coef);//dOPEC(avel.v, OP.MUL_EQ /* *= */, coef); } } // end of angular velocity cap // handle linear velocity //for (j=0; j<3; j++) _posr.pos.v[j] += h * lvel.v[j]; _posr.pos.eqSum(_posr.pos(), lvel, h); if ((flags & dxBodyFlagFiniteRotation) != 0) { DVector3 irv = new DVector3(); // infitesimal rotation vector DQuaternion q = new DQuaternion(); // quaternion for finite rotation if ((flags & dxBodyFlagFiniteRotationAxis) != 0) { // split the angular velocity vector into a component along the finite // rotation axis, and a component orthogonal to it. DVector3 frv = new DVector3(); // finite rotation vector double k = dCalcVectorDot3 (finite_rot_axis,avel); // frv.v[0] = finite_rot_axis.v[0] * k; // frv.v[1] = finite_rot_axis.v[1] * k; // frv.v[2] = finite_rot_axis.v[2] * k; frv.set( finite_rot_axis ).scale( k ); // irv.v[0] = avel.v[0] - frv.v[0]; // irv.v[1] = avel.v[1] - frv.v[1]; // irv.v[2] = avel.v[2] - frv.v[2]; irv.eqDiff(avel, frv); // make a rotation quaternion q that corresponds to frv * h. // compare this with the full-finite-rotation case below. h *= 0.5; double theta = k * h; double s = sinc(theta) * h; // q.v[0] = dCos(theta); // q.v[1] = frv.v[0] * s; // q.v[2] = frv.v[1] * s; // q.v[3] = frv.v[2] * s; q.set( dCos(theta), frv.get0()*s, frv.get1()*s, frv.get2()*s); } else { // make a rotation quaternion q that corresponds to w * h double wlen = avel.length();//dSqrt (avel.v[0]*avel.v[0] + avel.v[1]*avel.v[1] + //avel.v[2]*avel.v[2]); h *= 0.5; double theta = wlen * h; double s = sinc(theta) * h; // q.v[0] = dCos(theta); // q.v[1] = avel.v[0] * s; // q.v[2] = avel.v[1] * s; // q.v[3] = avel.v[2] * s; q.set( dCos(theta), avel.get0()*s, avel.get1()*s, avel.get2()*s); } // do the finite rotation DQuaternion q2 = new DQuaternion(); dQMultiply0 (q2,q,_q); //for (j=0; j<4; j++) _q.v[j] = q2.v[j]; _q.set(q2); // do the infitesimal rotation if required if ((flags & dxBodyFlagFiniteRotationAxis) != 0) { DQuaternion dq = new DQuaternion(); dDQfromW (dq,irv,_q); //for (j=0; j<4; j++) _q.v[j] += h * dq[j]; _q.sum( _q, dq, h); } } else { // the normal way - do an infitesimal rotation DQuaternion dq = new DQuaternion(); dDQfromW (dq,avel,_q); //for (j=0; j<4; j++) _q.v[j] += h * dq[j]; _q.sum( _q, dq, h); } // normalize the quaternion and convert it to a rotation matrix dNormalize4 (_q); dRfromQ (_posr.Rw(),_q); // notify all attached geoms that this body has moved DxWorldProcessContext world_process_context = world.UnsafeGetWorldProcessingContext(); for (DxGeom geom2 = geom; geom2 != null; geom2 = geom2.dGeomGetBodyNext ()) { world_process_context.LockForStepbodySerialization(); geom2.dGeomMoved (); world_process_context.UnlockForStepbodySerialization(); } // notify the user if (moved_callback != null) moved_callback.run(this); // damping if ((flags & dxBodyLinearDamping)!=0) { final double lin_threshold = dampingp.linear_threshold; final double lin_speed = dCalcVectorDot3( lvel, lvel ); if ( lin_speed > lin_threshold) { final double k = 1 - dampingp.linear_scale; lvel.scale(k);//dOPEC(lvel.v, OP.MUL_EQ, k); } } if ((flags & dxBodyAngularDamping)!=0) { final double ang_threshold = dampingp.angular_threshold; final double ang_speed = dCalcVectorDot3( avel, avel ); if ( ang_speed > ang_threshold) { final double k = 1 - dampingp.angular_scale; avel.scale(k);//dOPEC(avel.v, OP.MUL_EQ, k); } } } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } @Override public String toString() { return super.toString(); } public DxPosRC posr() { return _posr; } // ****************************************************** // dBody API // ****************************************************** //~dBody() @Override // public void DESTRUCTOR() // { dBodyDestroy (); super.DESTRUCTOR(); } public void DESTRUCTOR() { super.DESTRUCTOR(); }; //void setData (void *data) @Override public void setData (Object data) { dBodySetData (data); } //void *getData() @Override public Object getData() { return dBodyGetData (); } @Override public void setPosition (double x, double y, double z) { dBodySetPosition (x,y,z); } @Override public void setPosition (DVector3C p) { dBodySetPosition(p); } @Override public void setRotation (DMatrix3C R) { dBodySetRotation (R); } @Override public void setQuaternion (DQuaternionC q) { dBodySetQuaternion (q); } @Override public void setLinearVel (double x, double y, double z) { dBodySetLinearVel (x,y,z); } @Override public void setLinearVel (DVector3C v) { dBodySetLinearVel(v); } @Override public void setAngularVel (double x, double y, double z) { dBodySetAngularVel (x,y,z); } @Override public void setAngularVel (DVector3C v) { dBodySetAngularVel (v); } @Override public DVector3C getPosition() { return dBodyGetPosition (); } @Override public DMatrix3C getRotation() //const { return dBodyGetRotation (); } @Override public DQuaternionC getQuaternion() //const { return dBodyGetQuaternion (); } @Override public DVector3C getLinearVel() //const { return dBodyGetLinearVel (); } @Override public DVector3C getAngularVel() //const { return dBodyGetAngularVel (); } // void setMass (final dMass *mass) // { dBodySetMass (_id,mass); } //void setMass (final dMass &mass) // { setMass (&mass); } @Override public void setMass (DMassC mass) { dBodySetMass (mass); } @Override public DMass getMass () //const { DMass mass = new DxMass(); dBodyGetMass ((DxMass) mass); return mass; } @Override public void addForce (double fx, double fy, double fz) { dBodyAddForce (fx, fy, fz); } @Override public void addForce (DVector3C f) { dBodyAddForce (f); } @Override public void addTorque (double fx, double fy, double fz) { dBodyAddTorque (fx, fy, fz); } @Override public void addTorque (DVector3C t) { dBodyAddTorque(t); } @Override public void addRelForce (double fx, double fy, double fz) { dBodyAddRelForce ( new DVector3(fx, fy, fz)); } @Override public void addRelForce (DVector3C f) { dBodyAddRelForce (f); } @Override public void addRelTorque (double fx, double fy, double fz) { dBodyAddRelTorque (new DVector3(fx, fy, fz)); } @Override public void addRelTorque (DVector3C t) { dBodyAddRelTorque (t); } @Override public void addForceAtPos (double fx, double fy, double fz, double px, double py, double pz) { dBodyAddForceAtPos (new DVector3(fx, fy, fz), new DVector3(px, py, pz)); } @Override public void addForceAtPos (DVector3C f, DVector3C p) { dBodyAddForceAtPos (f,p); } @Override public void addForceAtRelPos (double fx, double fy, double fz, double px, double py, double pz) { dBodyAddForceAtRelPos (new DVector3(fx, fy, fz), new DVector3(px, py, pz)); } @Override public void addForceAtRelPos (DVector3C f, DVector3C p) { dBodyAddForceAtRelPos (f, p); } @Override public void addRelForceAtPos (double fx, double fy, double fz, double px, double py, double pz) { dBodyAddRelForceAtPos (new DVector3(fx, fy, fz), new DVector3(px, py, pz)); } @Override public void addRelForceAtPos (DVector3C f, DVector3C p) { dBodyAddRelForceAtPos (f, p); } @Override public void addRelForceAtRelPos (double fx, double fy, double fz, double px, double py, double pz) { dBodyAddRelForceAtRelPos (new DVector3(fx, fy, fz), new DVector3(px, py, pz)); } @Override public void addRelForceAtRelPos (DVector3C f, DVector3C p) { dBodyAddRelForceAtRelPos (f, p); } @Override public DVector3C getForce() //const { return dBodyGetForce(); } @Override public DVector3C getTorque() //const { return dBodyGetTorque(); } @Override public void setForce (double x, double y, double z) { dBodySetForce (x,y,z); } @Override public void setForce (DVector3C f) { dBodySetForce (f); } @Override public void setTorque (double x, double y, double z) { dBodySetTorque (x,y,z); } @Override public void setTorque (DVector3C t) { dBodySetTorque (t); } @Override public void setDynamic() { dBodySetDynamic (); } @Override public void setKinematic() { dBodySetKinematic (); } @Override public boolean isKinematic() { return dBodyIsKinematic (); } @Override public void enable() { dBodyEnable (); } @Override public void disable() { dBodyDisable (); } @Override public boolean isEnabled() //const { return dBodyIsEnabled (); } //TZ public boolean isFlagsGyroscopic() { return (flags & dxBodyGyroscopic) != 0; } @Override public void getRelPointPos (double px, double py, double pz, DVector3 result) //const { dBodyGetRelPointPos (new DVector3(px, py, pz), result); } @Override public void getRelPointPos (DVector3C p, DVector3 result) //const { dBodyGetRelPointPos (p, result); } @Override public void getRelPointVel (double px, double py, double pz, DVector3 result) //const { dBodyGetRelPointVel (new DVector3(px, py, pz), result); } @Override public void getRelPointVel (DVector3C p, DVector3 result) //const { dBodyGetRelPointVel (p, result); } @Override public void getPointVel (double px, double py, double pz, DVector3 result) //const { dBodyGetPointVel ( new DVector3(px, py, pz), result); } @Override public void getPointVel (DVector3C p, DVector3 result) //const { dBodyGetPointVel (p, result); } @Override public void getPosRelPoint (double px, double py, double pz, DVector3 result) //const { dBodyGetPosRelPoint ( new DVector3(px, py, pz), result); } @Override public void getPosRelPoint (DVector3C p, DVector3 result) //const { dBodyGetPosRelPoint (p, result); } @Override public void vectorToWorld (double px, double py, double pz, DVector3 result) //const { dBodyVectorToWorld ( new DVector3(px, py, pz), result); } @Override public void vectorToWorld (DVector3C p, DVector3 result) //const { dBodyVectorToWorld (p, result); } @Override public void vectorFromWorld (double px, double py, double pz, DVector3 result) //const { dBodyVectorFromWorld (new DVector3(px,py,pz),result); } @Override public void vectorFromWorld (DVector3C p, DVector3 result) //const { dBodyVectorFromWorld (p, result); } @Override public void setFiniteRotationMode (boolean mode) { dBodySetFiniteRotationMode (mode); } @Override public void setFiniteRotationAxis (double x, double y, double z) { dBodySetFiniteRotationAxis( new DVector3(x, y, z)); } @Override public void setFiniteRotationAxis (DVector3C a) { dBodySetFiniteRotationAxis (a); } @Override public boolean getFiniteRotationMode() //const { return dBodyGetFiniteRotationMode (); } @Override public void getFiniteRotationAxis (DVector3 result) //const { dBodyGetFiniteRotationAxis ( result); } @Override public int getNumJoints() //const { return dBodyGetNumJoints (); } @Override public DJoint getJoint (int index) //const { return dBodyGetJoint ( index); } @Override public void setGravityMode (boolean mode) { dBodySetGravityMode (mode); } /** @see DxBody#dBodyGetGravityMode() */ @Override public boolean getGravityMode() { return dBodyGetGravityMode (); } @Override public void setGyroscopicMode (boolean mode) { dBodySetGyroscopicMode(mode); } @Override public boolean getGyroscopicMode() { return dBodyGetGyroscopicMode (); } @Override public boolean isConnectedTo (DBody body) //const { return OdeJointsFactoryImpl.areConnected (this, body); } @Override public void setAutoDisableLinearThreshold (double threshold) { dBodySetAutoDisableLinearThreshold (threshold); } @Override public double getAutoDisableLinearThreshold() //const { return dBodyGetAutoDisableLinearThreshold (); } @Override public void setAutoDisableAngularThreshold (double threshold) { dBodySetAutoDisableAngularThreshold (threshold); } @Override public double getAutoDisableAngularThreshold() //const { return dBodyGetAutoDisableAngularThreshold (); } @Override public void setAutoDisableSteps (int steps) { dBodySetAutoDisableSteps (steps); } @Override public int getAutoDisableSteps() { return dBodyGetAutoDisableSteps (); } @Override public void setAutoDisableTime (double time) { dBodySetAutoDisableTime (time); } @Override public double getAutoDisableTime() { return dBodyGetAutoDisableTime (); } @Override public void setAutoDisableFlag (boolean do_auto_disable) { dBodySetAutoDisableFlag ( do_auto_disable); } @Override public boolean getAutoDisableFlag() { return dBodyGetAutoDisableFlag (); } @Override public double getLinearDamping() { return dBodyGetLinearDamping(); } @Override public void setLinearDamping(double scale) { dBodySetLinearDamping(scale); } @Override public double getAngularDamping() { return dBodyGetAngularDamping(); } @Override public void setAngularDamping(double scale) { dBodySetAngularDamping( scale); } @Override public void setDamping(double linear_scale, double angular_scale) { dBodySetDamping(linear_scale, angular_scale); } @Override public double getLinearDampingThreshold() { return dBodyGetLinearDampingThreshold(); } @Override public void setLinearDampingThreshold(double threshold) { dBodySetLinearDampingThreshold(threshold); } @Override public double getAngularDampingThreshold() { return dBodyGetAngularDampingThreshold(); } @Override public void setAngularDampingThreshold(double threshold) { dBodySetAngularDampingThreshold(threshold); } @Override public void setDampingDefaults() { dBodySetDampingDefaults(); } @Override public double getMaxAngularSpeed() { return dBodyGetMaxAngularSpeed(); } @Override public void setMaxAngularSpeed(double max_speed) { dBodySetMaxAngularSpeed(max_speed); } @Override public void destroy() { dBodyDestroy(); } @Override public int getAutoDisableAverageSamplesCount() { return dBodyGetAutoDisableAverageSamplesCount(); } @Override public void setAutoDisableAverageSamplesCount(int average_samples_count) { dBodySetAutoDisableAverageSamplesCount(average_samples_count); } @Override public void setAutoDisableDefaults() { dBodySetAutoDisableDefaults(); } /** @deprecated */ @Deprecated @Override public DGeom getFirstGeom() { return dBodyGetFirstGeom(); } /** @deprecated */ @Deprecated @Override public DGeom getNextGeom(DGeom geom) { return dBodyGetNextGeom((DxGeom) geom); } @Override public void setMovedCallback(BodyMoveCallBack callback) { dBodySetMovedCallback(callback); } }
9242be14f1486c582890ef5e998f94ac5354717c
1,234
java
Java
site/src/main/java/nl/hsleiden/components/catalog/RelatedNews.java
HogeschoolLeiden/website
c468cc69f6b6aca1012afa577cf26338816055a4
[ "CC0-1.0" ]
null
null
null
site/src/main/java/nl/hsleiden/components/catalog/RelatedNews.java
HogeschoolLeiden/website
c468cc69f6b6aca1012afa577cf26338816055a4
[ "CC0-1.0" ]
null
null
null
site/src/main/java/nl/hsleiden/components/catalog/RelatedNews.java
HogeschoolLeiden/website
c468cc69f6b6aca1012afa577cf26338816055a4
[ "CC0-1.0" ]
null
null
null
38.5625
111
0.76175
1,002,398
package nl.hsleiden.components.catalog; import hslbeans.NewsPage; import nl.hsleiden.componentsinfo.RelatedItemsInfo; import nl.hsleiden.componentsinfo.RelatedNewsInfo; import nl.hsleiden.utils.Constants.WidgetConstants; import org.hippoecm.hst.content.beans.query.HstQuery; import org.hippoecm.hst.content.beans.query.exceptions.QueryException; import org.hippoecm.hst.content.beans.standard.HippoBean; import org.hippoecm.hst.core.component.HstRequest; import org.hippoecm.hst.core.parameters.ParametersInfo; import com.tdclighthouse.prototype.utils.BeanUtils; @ParametersInfo(type = RelatedNewsInfo.class) public class RelatedNews extends RelatedItems { @Override protected HstQuery createQuery(HstRequest request, RelatedItemsInfo parametersInfo) throws QueryException { HstQuery result = null; HippoBean scope = BeanUtils.getBeanViaAbsolutePath(parametersInfo.getContentBeanPath()); if(scope!=null){ result = request.getRequestContext().getQueryManager().createQuery(scope, NewsPage.JCR_TYPE); }else{ request.setAttribute(WidgetConstants.WEB_MASTER_MESSAGE, "webmaster.nofolder.message"); } return result; } }
9242be214d51856fb69375315b5e1c8d7dbe8807
3,350
java
Java
src/test/java/com/fdmgroup/legendwealth/dal/GenericDaoTest.java
KabirRajput/PortfolioManagementSystem
d74327f8154059466756a1de76b1009dae2f81af
[ "Apache-2.0" ]
null
null
null
src/test/java/com/fdmgroup/legendwealth/dal/GenericDaoTest.java
KabirRajput/PortfolioManagementSystem
d74327f8154059466756a1de76b1009dae2f81af
[ "Apache-2.0" ]
null
null
null
src/test/java/com/fdmgroup/legendwealth/dal/GenericDaoTest.java
KabirRajput/PortfolioManagementSystem
d74327f8154059466756a1de76b1009dae2f81af
[ "Apache-2.0" ]
null
null
null
31.018519
104
0.768657
1,002,399
package com.fdmgroup.legendwealth.dal; import static org.mockito.Mockito.*; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.TypedQuery; import org.junit.Test; import org.mockito.*; import com.fdmgroup.legendwealth.entity.Trade; public class GenericDaoTest { @Test public void given_Instance_when_addingInstanceToDataBase_then_InstanceIsPersistedAndResourcesClosed() { Trade mockTrade = mock(Trade.class); EntityManagerFactory mockEmf = mock(EntityManagerFactory.class); EntityManager mockEm = mock(EntityManager.class); EntityTransaction mockEt = mock(EntityTransaction.class); when(mockEmf.createEntityManager()).thenReturn(mockEm); when(mockEm.getTransaction()).thenReturn(mockEt); TradeDao tradeDao = new TradeDao(mockEmf); tradeDao.add(mockTrade); InOrder order = inOrder(mockEmf, mockEm, mockEt); order.verify(mockEmf).createEntityManager(); order.verify(mockEm).getTransaction(); order.verify(mockEt).begin(); order.verify(mockEm).persist(mockTrade); order.verify(mockEt).commit(); order.verify(mockEm).close(); } @Test public void given_existingId_when_findingById_then_returnsFromDataBase() { long id = 1; EntityManagerFactory mockEmf = mock(EntityManagerFactory.class); EntityManager mockEm = mock(EntityManager.class); when(mockEmf.createEntityManager()).thenReturn(mockEm); TradeDao tradeDao = new TradeDao(mockEmf); tradeDao.getById(id); InOrder order = inOrder(mockEmf, mockEm); order.verify(mockEmf).createEntityManager(); order.verify(mockEm).find(Trade.class, id); order.verify(mockEm).close(); } @Test public void query_list_then_returnsFromDataBase() { EntityManagerFactory mockEmf = mock(EntityManagerFactory.class); EntityManager mockEm = mock(EntityManager.class); EntityTransaction mockEt = mock(EntityTransaction.class); TypedQuery<Trade> mockQ = mock(TypedQuery.class); when(mockEmf.createEntityManager()).thenReturn(mockEm); when(mockEm.getTransaction()).thenReturn(mockEt); when(mockEm.createQuery("SELECT e FROM Trade e")).thenReturn(mockQ); TradeDao tradeDao = new TradeDao(mockEmf); tradeDao.getList(); InOrder order = inOrder(mockEmf, mockEm, mockEt, mockQ); order.verify(mockEmf).createEntityManager(); order.verify(mockEm).getTransaction(); order.verify(mockEt).begin(); order.verify(mockQ).getResultList(); order.verify(mockEt).commit(); order.verify(mockEm).close(); } @Test public void given_Instance_when_mergingInstanceToDataBase_then_InstanceIsMergedAndResourcesClosed() { Trade mockTrade = mock(Trade.class); EntityManagerFactory mockEmf = mock(EntityManagerFactory.class); EntityManager mockEm = mock(EntityManager.class); EntityTransaction mockEt = mock(EntityTransaction.class); when(mockEmf.createEntityManager()).thenReturn(mockEm); when(mockEm.getTransaction()).thenReturn(mockEt); TradeDao tradeDao = new TradeDao(mockEmf); tradeDao.merge(mockTrade); InOrder order = inOrder(mockEmf, mockEm, mockEt); order.verify(mockEmf).createEntityManager(); order.verify(mockEm).getTransaction(); order.verify(mockEt).begin(); order.verify(mockEm).merge(mockTrade); order.verify(mockEt).commit(); order.verify(mockEm).close(); } }
9242bfd5c7bff94a6c3e54c74774e2281094251b
3,011
java
Java
ThirdPartyAdapters/DuAdPlatform/du-ad-platform/src/main/java/com/google/ads/mediation/dap/forwarder/DapRewardedVideoEventForwarder.java
imobile-maio/googleads-mobile-android-mediation
64ef862c1d8a1dccfe65969842ba8a0798b5dbcb
[ "Apache-2.0" ]
null
null
null
ThirdPartyAdapters/DuAdPlatform/du-ad-platform/src/main/java/com/google/ads/mediation/dap/forwarder/DapRewardedVideoEventForwarder.java
imobile-maio/googleads-mobile-android-mediation
64ef862c1d8a1dccfe65969842ba8a0798b5dbcb
[ "Apache-2.0" ]
1
2018-04-15T17:09:20.000Z
2018-04-17T19:29:01.000Z
ThirdPartyAdapters/DuAdPlatform/du-ad-platform/src/main/java/com/google/ads/mediation/dap/forwarder/DapRewardedVideoEventForwarder.java
santoshbagadi/googleads-mobile-android-mediation
b2a3a403d336ef0018c8c67db3e548a87990a912
[ "Apache-2.0" ]
null
null
null
44.279412
123
0.71903
1,002,400
package com.google.ads.mediation.dap.forwarder; import com.duapps.ad.AdError; import com.duapps.ad.video.AdResult; import com.duapps.ad.video.DuVideoAdListener; import com.google.ads.mediation.dap.DuAdMediation; import com.google.ads.mediation.dap.DuRewardedAdAdapter; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.reward.mediation.MediationRewardedVideoAdAdapter; import com.google.android.gms.ads.reward.mediation.MediationRewardedVideoAdListener; public class DapRewardedVideoEventForwarder implements DuVideoAdListener { private static final String TAG = DuRewardedAdAdapter.class.getSimpleName(); private final MediationRewardedVideoAdListener mRewardedVideoListener; private final MediationRewardedVideoAdAdapter mMediationRewardedVideoAdAdapter; public DapRewardedVideoEventForwarder( MediationRewardedVideoAdAdapter adapter, MediationRewardedVideoAdListener listener) { mRewardedVideoListener = listener; mMediationRewardedVideoAdAdapter = adapter; } @Override public void onAdEnd(AdResult adResult) { if (mRewardedVideoListener != null) { if (adResult.isCallToActionClicked()) { // these are invoked after the video ad is ended as we currently don`t support ad click instant // callback. We will support it in future if the our publishers do have such need. mRewardedVideoListener.onAdClicked(mMediationRewardedVideoAdAdapter); mRewardedVideoListener.onAdLeftApplication(mMediationRewardedVideoAdAdapter); DuAdMediation.d(TAG, "Dap Rewarded Video clicked."); } if (adResult.isSuccessfulView()) { mRewardedVideoListener.onRewarded(mMediationRewardedVideoAdAdapter, null); } mRewardedVideoListener.onAdClosed(mMediationRewardedVideoAdAdapter); DuAdMediation.d(TAG, "Dap Rewarded Video closed."); } } @Override public void onAdStart() { if (mRewardedVideoListener != null) { DuAdMediation.d(TAG, "Dap Rewarded Video started playing."); mRewardedVideoListener.onAdOpened(mMediationRewardedVideoAdAdapter); mRewardedVideoListener.onVideoStarted(mMediationRewardedVideoAdAdapter); } } @Override public void onAdError(AdError adError) { if (mRewardedVideoListener != null) { DuAdMediation.d(TAG, "Loading/Playing Dap Rewarded Video encountered an error: " + adError.getErrorCode()); mRewardedVideoListener.onAdFailedToLoad(mMediationRewardedVideoAdAdapter, AdRequest.ERROR_CODE_INTERNAL_ERROR); } } @Override public void onAdPlayable() { if (mRewardedVideoListener != null) { DuAdMediation.d(TAG, "Dap Rewarded Video loaded successfully, Forwarder instance: " + this); mRewardedVideoListener.onAdLoaded(mMediationRewardedVideoAdAdapter); } } }
9242c0440c838f9ac341db9bf7edac2b5688e172
710
java
Java
04_04_start/src/main/java/com/readlearncode/RandomNumberGenerator.java
pdibenedetto/Context-and-Dependency-Injection-CDI-with-Java-EE
69aff10edb1e63c8b33dbdd680ac18347a2f120d
[ "MIT" ]
1
2020-06-11T03:52:21.000Z
2020-06-11T03:52:21.000Z
04_04_start/src/main/java/com/readlearncode/RandomNumberGenerator.java
readlearncode/Context-and-Dependency-Injection-CDI-with-Java-EE
69aff10edb1e63c8b33dbdd680ac18347a2f120d
[ "MIT" ]
null
null
null
04_04_start/src/main/java/com/readlearncode/RandomNumberGenerator.java
readlearncode/Context-and-Dependency-Injection-CDI-with-Java-EE
69aff10edb1e63c8b33dbdd680ac18347a2f120d
[ "MIT" ]
3
2019-01-31T19:24:10.000Z
2021-05-08T19:10:15.000Z
22.1875
65
0.642254
1,002,401
package com.readlearncode; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import java.util.ArrayList; import java.util.Random; /** * Source code github.com/readlearncode * * @author Alex Theedom www.readlearncode.com * @version 1.0 */ public class RandomNumberGenerator { private Random ran = new Random(); @Produces private ArrayList<Integer> get() { return new ArrayList<Integer>() {{ add(ran.nextInt(100)); add(ran.nextInt(100)); add(ran.nextInt(100)); add(ran.nextInt(100)); }}; } public void clearArray(@Disposes ArrayList<Integer> numbers){ numbers.clear();; } }
9242c14c59b183520825cdf74a8e3ea9984e372e
9,754
java
Java
src/com/raylib/java/rlgl/data/State.java
CreedVI/Raylib-J
4d256314d1c73c7b964aefa7a8851efccb86fafc
[ "Zlib" ]
17
2021-03-20T11:49:29.000Z
2022-03-07T10:28:56.000Z
src/com/raylib/java/rlgl/data/State.java
CreedVI/Raylib-J
4d256314d1c73c7b964aefa7a8851efccb86fafc
[ "Zlib" ]
15
2021-03-18T19:03:50.000Z
2022-02-28T20:11:36.000Z
src/com/raylib/java/rlgl/data/State.java
CreedVI/Raylib-J
4d256314d1c73c7b964aefa7a8851efccb86fafc
[ "Zlib" ]
4
2021-09-10T16:14:18.000Z
2022-02-22T20:18:57.000Z
27.710227
131
0.65245
1,002,402
package com.raylib.java.rlgl.data; import com.raylib.java.raymath.Matrix; import static com.raylib.java.rlgl.RLGL.*; public class State{ // Renderer state public int vertexCounter; // Current active render batch vertex counter (generic, used for all batches) public float texcoordx, texcoordy; // Current active texture coordinate (added on glVertex*()) public float normalx, normaly, normalz; // Current active normal (added on glVertex*()) public byte colorr, colorg, colorb, colora; // Current active color (added on glVertex*()) public int currentMatrixMode; // Current matrix mode public Matrix currentMatrix; // Current matrix pointer public Matrix modelview; // Default modelview matrix public Matrix projection; // Default projection matrix public Matrix transform; // Transform matrix to be used with rlTranslate, rlRotate, rlScale public boolean transformRequired; // Require transform matrix application to current draw-call vertex (if required) public Matrix[] stack; // Matrix stack for push/pop public int stackCounter; // Matrix stack counter public int defaultTextureId; // Default texture used on shapes/poly drawing (required by shader) public int[] activeTextureId; // Active texture ids to be enabled on batch drawing (0 active by default) public int defaultVShaderId; // Default vertex shader id (used by default shader program) public int defaultFShaderId; // Default fragment shader id (used by default shader program) public int defaultShaderId; // Default shader program id, supports vertex color and diffuse texture public int[] defaultShaderLocs; // Default shader locations pointer to be used on rendering public int currentShaderId; // Current shader id to be used on rendering (by default, defaultShaderId) public int[] currentShaderLocs; // Current shader locations pointer to be used on rendering (by default, defaultShaderLocs) public boolean stereoRender; // Stereo rendering flag public Matrix[] projectionStereo; // VR stereo rendering eyes projection matrices public Matrix[] viewOffsetStereo; // VR stereo rendering eyes view offset matrices public int currentBlendMode; // Blending mode active public int glBlendSrcFactor; // Blending source factor public int glBlendDstFactor; // Blending destination factor public int glBlendEquation; // Blending equation public int framebufferWidth; // Default framebuffer width public int framebufferHeight; // Default framebuffer height public State(){ stack = new Matrix[MAX_MATRIX_STACK_SIZE]; activeTextureId = new int[MAX_BATCH_ACTIVE_TEXTURES]; projectionStereo = new Matrix[2]; viewOffsetStereo = new Matrix[2]; } public Matrix getCurrentMatrix(){ if(currentMatrixMode == RL_PROJECTION){ return projection; } else { return modelview; } } public void setCurrentMatrix(Matrix currentMatrix){ if(currentMatrixMode == RL_PROJECTION){ projection = currentMatrix; } else if(currentMatrixMode == RL_MODELVIEW){ modelview = currentMatrix; } } public void setCurrentMatrix(int mode, Matrix currentMatrix){ if(mode == RL_PROJECTION){ projection = currentMatrix; } else if(mode == RL_MODELVIEW){ modelview = currentMatrix; } } public int getVertexCounter(){ return vertexCounter; } public void setVertexCounter(int vertexCounter){ this.vertexCounter = vertexCounter; } public float getTexcoordx(){ return texcoordx; } public void setTexcoordx(float texcoordx){ this.texcoordx = texcoordx; } public float getTexcoordy(){ return texcoordy; } public void setTexcoordy(float texcoordy){ this.texcoordy = texcoordy; } public float getNormalx(){ return normalx; } public void setNormalx(float normalx){ this.normalx = normalx; } public float getNormaly(){ return normaly; } public void setNormaly(float normaly){ this.normaly = normaly; } public float getNormalz(){ return normalz; } public void setNormalz(float normalz){ this.normalz = normalz; } public int getColorr(){ return colorr; } public void setColorr(byte colorr){ this.colorr = colorr; } public int getColorg(){ return colorg; } public void setColorg(byte colorg){ this.colorg = colorg; } public int getColorb(){ return colorb; } public void setColorb(byte colorb){ this.colorb = colorb; } public int getColora(){ return colora; } public void setColora(byte colora){ this.colora = colora; } public int getCurrentMatrixMode(){ return currentMatrixMode; } public void setCurrentMatrixMode(int currentMatrixMode){ this.currentMatrixMode = currentMatrixMode; } public Matrix getModelview(){ return modelview; } public void setModelview(Matrix modelview){ this.modelview = modelview; } public Matrix getProjection(){ return projection; } public void setProjection(Matrix projection){ this.projection = projection; } public Matrix getTransform(){ return transform; } public void setTransform(Matrix transform){ this.transform = transform; } public boolean isTransformRequired(){ return transformRequired; } public void setTransformRequired(boolean transformRequired){ this.transformRequired = transformRequired; } public Matrix[] getStack(){ return stack; } public void setStack(Matrix[] stack){ this.stack = stack; } public int getStackCounter(){ return stackCounter; } public void setStackCounter(int stackCounter){ this.stackCounter = stackCounter; } public int getDefaultTextureId(){ return defaultTextureId; } public void setDefaultTextureId(int defaultTextureId){ this.defaultTextureId = defaultTextureId; } public int[] getActiveTextureId(){ return activeTextureId; } public void setActiveTextureId(int[] activeTextureId){ this.activeTextureId = activeTextureId; } public int getDefaultVShaderId(){ return defaultVShaderId; } public void setDefaultVShaderId(int defaultVShaderId){ this.defaultVShaderId = defaultVShaderId; } public int getDefaultFShaderId(){ return defaultFShaderId; } public void setDefaultFShaderId(int defaultFShaderId){ this.defaultFShaderId = defaultFShaderId; } public int getDefaultShaderId(){ return defaultShaderId; } public void setDefaultShaderId(int defaultShaderId){ this.defaultShaderId = defaultShaderId; } public int[] getDefaultShaderLocs(){ return defaultShaderLocs; } public void setDefaultShaderLocs(int[] defaultShaderLocs){ this.defaultShaderLocs = defaultShaderLocs; } public int getCurrentShaderId(){ return currentShaderId; } public void setCurrentShaderId(int currentShaderId){ this.currentShaderId = currentShaderId; } public int[] getCurrentShaderLocs(){ return currentShaderLocs; } public void setCurrentShaderLocs(int[] currentShaderLocs){ this.currentShaderLocs = currentShaderLocs; } public boolean isStereoRender(){ return stereoRender; } public void setStereoRender(boolean stereoRender){ this.stereoRender = stereoRender; } public Matrix[] getProjectionStereo(){ return projectionStereo; } public void setProjectionStereo(Matrix[] projectionStereo){ this.projectionStereo = projectionStereo; } public Matrix[] getViewOffsetStereo(){ return viewOffsetStereo; } public void setViewOffsetStereo(Matrix[] viewOffsetStereo){ this.viewOffsetStereo = viewOffsetStereo; } public int getCurrentBlendMode(){ return currentBlendMode; } public void setCurrentBlendMode(int currentBlendMode){ this.currentBlendMode = currentBlendMode; } public int getGlBlendSrcFactor(){ return glBlendSrcFactor; } public void setGlBlendSrcFactor(int glBlendSrcFactor){ this.glBlendSrcFactor = glBlendSrcFactor; } public int getGlBlendDstFactor(){ return glBlendDstFactor; } public void setGlBlendDstFactor(int glBlendDstFactor){ this.glBlendDstFactor = glBlendDstFactor; } public int getGlBlendEquation(){ return glBlendEquation; } public void setGlBlendEquation(int glBlendEquation){ this.glBlendEquation = glBlendEquation; } public int getFramebufferWidth(){ return framebufferWidth; } public void setFramebufferWidth(int framebufferWidth){ this.framebufferWidth = framebufferWidth; } public int getFramebufferHeight(){ return framebufferHeight; } public void setFramebufferHeight(int framebufferHeight){ this.framebufferHeight = framebufferHeight; } }
9242c189c01da60a23d3c3ff88ae8cc1bdbf00ff
2,568
java
Java
app/src/main/java/com/liuxe/energyweather/bean/WeathersBean.java
liuxe66/EneryWeather
96c648b43dd07588e259dafc2dff14d6a14081c4
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/liuxe/energyweather/bean/WeathersBean.java
liuxe66/EneryWeather
96c648b43dd07588e259dafc2dff14d6a14081c4
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/liuxe/energyweather/bean/WeathersBean.java
liuxe66/EneryWeather
96c648b43dd07588e259dafc2dff14d6a14081c4
[ "Apache-2.0" ]
null
null
null
19.753846
56
0.604361
1,002,403
package com.liuxe.energyweather.bean; import java.io.Serializable; public class WeathersBean implements Serializable { /** * date : 2019-12-19 * img : 1 * sun_down_time : 17:17 * sun_rise_time : 07:30 * temp_day_c : 10 * temp_day_f : 50.0 * temp_night_c : -2 * temp_night_f : 28.4 * wd : * weather : 多云 * week : 星期四 * ws : */ private String date; private String img; private String sun_down_time; private String sun_rise_time; private String temp_day_c; private String temp_day_f; private String temp_night_c; private String temp_night_f; private String wd; private String weather; private String week; private String ws; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getSun_down_time() { return sun_down_time; } public void setSun_down_time(String sun_down_time) { this.sun_down_time = sun_down_time; } public String getSun_rise_time() { return sun_rise_time; } public void setSun_rise_time(String sun_rise_time) { this.sun_rise_time = sun_rise_time; } public String getTemp_day_c() { return temp_day_c; } public void setTemp_day_c(String temp_day_c) { this.temp_day_c = temp_day_c; } public String getTemp_day_f() { return temp_day_f; } public void setTemp_day_f(String temp_day_f) { this.temp_day_f = temp_day_f; } public String getTemp_night_c() { return temp_night_c; } public void setTemp_night_c(String temp_night_c) { this.temp_night_c = temp_night_c; } public String getTemp_night_f() { return temp_night_f; } public void setTemp_night_f(String temp_night_f) { this.temp_night_f = temp_night_f; } public String getWd() { return wd; } public void setWd(String wd) { this.wd = wd; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } public String getWeek() { return week; } public void setWeek(String week) { this.week = week; } public String getWs() { return ws; } public void setWs(String ws) { this.ws = ws; } }
9242c1b2345ec134509e4037a72dd1152a617b92
12,280
java
Java
src/test/java/nl/jqno/equalsverifier/integration/basic_contract/TransitivityTest.java
dfa1/equalsverifier
d0be167bbaf20af007ff892d5e1a1b8c4a38008b
[ "Apache-2.0" ]
613
2015-01-30T03:25:37.000Z
2022-03-22T17:20:05.000Z
src/test/java/nl/jqno/equalsverifier/integration/basic_contract/TransitivityTest.java
dfa1/equalsverifier
d0be167bbaf20af007ff892d5e1a1b8c4a38008b
[ "Apache-2.0" ]
345
2015-03-18T09:12:14.000Z
2022-03-25T11:51:10.000Z
src/test/java/nl/jqno/equalsverifier/integration/basic_contract/TransitivityTest.java
dfa1/equalsverifier
d0be167bbaf20af007ff892d5e1a1b8c4a38008b
[ "Apache-2.0" ]
124
2015-03-01T10:27:09.000Z
2022-02-11T19:06:20.000Z
28.55814
94
0.519544
1,002,404
package nl.jqno.equalsverifier.integration.basic_contract; import static nl.jqno.equalsverifier.testhelpers.Util.defaultHashCode; import java.util.Objects; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.testhelpers.ExpectedException; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; public class TransitivityTest { @Test public void succeed_whenEqualityForTwoFieldsIsCombinedUsingAnd() { EqualsVerifier.forClass(TwoFieldsUsingAnd.class).verify(); } @Test public void fail_whenEqualityForTwoFieldsIsCombinedUsingOr() { ExpectedException .when(() -> EqualsVerifier .forClass(TwoFieldsUsingOr.class) .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) .verify() ) .assertFailure() .assertMessageContains( "Transitivity", "two of these three instances are equal to each other, so the third one" + " should be, too", TwoFieldsUsingOr.class.getSimpleName() ); } @Test public void succeed_whenEqualityForThreeFieldsIsCombinedUsingAnd() { EqualsVerifier.forClass(ThreeFieldsUsingAnd.class).verify(); } @Test public void fail_whenEqualityForThreeFieldsIsCombinedUsingOr() { ExpectedException .when(() -> EqualsVerifier .forClass(ThreeFieldsUsingOr.class) .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) .verify() ) .assertFailure() .assertMessageContains("Transitivity"); } @Test public void fail_whenEqualityForThreeFieldsIsCombinedUsingOr_givenRelaxedEqualExamples() { ThreeFieldsUsingOr one = new ThreeFieldsUsingOr("a", "1", "alpha"); ThreeFieldsUsingOr two = new ThreeFieldsUsingOr("b", "1", "alpha"); ThreeFieldsUsingOr three = new ThreeFieldsUsingOr("c", "1", "alpha"); ThreeFieldsUsingOr other = new ThreeFieldsUsingOr("d", "4", "delta"); ExpectedException .when(() -> EqualsVerifier .forRelaxedEqualExamples(one, two, three) .andUnequalExample(other) .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) .verify() ) .assertFailure() .assertMessageContains("Transitivity"); } @Test public void fail_whenEqualityForThreeFieldsIsCombinedUsingAndAndOr() { ExpectedException .when(() -> EqualsVerifier .forClass(ThreeFieldsUsingAndOr.class) .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) .verify() ) .assertFailure() .assertMessageContains("Transitivity"); } @Test public void fail_whenEqualityForThreeFieldsIsCombinedUsingOrAndAnd() { ExpectedException .when(() -> EqualsVerifier .forClass(ThreeFieldsUsingOrAnd.class) .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) .verify() ) .assertFailure() .assertMessageContains("Transitivity"); } @Test public void fail_whenEqualityForFiveFieldsIsCombinedUsingOr() { ExpectedException .when(() -> EqualsVerifier .forClass(FiveFieldsUsingOr.class) .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) .verify() ) .assertFailure() .assertMessageContains("Transitivity"); } @Test public void fail_whenEqualityForFiveFieldsIsCombinedUsingAndsAndOrs() { ExpectedException .when(() -> EqualsVerifier .forClass(FiveFieldsUsingAndsAndOrs.class) .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) .verify() ) .assertFailure() .assertMessageContains("Transitivity"); } @Disabled("This class is not transitive, and it should fail. See issue 78.") @Test public void fail_whenInstancesAreEqualIfAtLeastTwoFieldsAreEqual() { ExpectedException .when(() -> EqualsVerifier .forClass(AtLeast2FieldsAreEqual.class) .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) .verify() ) .assertFailure() .assertMessageContains("Transitivity"); } static final class TwoFieldsUsingAnd { private final String f; private final String g; public TwoFieldsUsingAnd(String f, String g) { this.f = f; this.g = g; } @Override public boolean equals(Object obj) { if (!(obj instanceof TwoFieldsUsingAnd)) { return false; } TwoFieldsUsingAnd other = (TwoFieldsUsingAnd) obj; return Objects.equals(f, other.f) && Objects.equals(g, other.g); } @Override public int hashCode() { return defaultHashCode(this); } } static final class TwoFieldsUsingOr { private final String f; private final String g; public TwoFieldsUsingOr(String f, String g) { this.f = f; this.g = g; } @Override public boolean equals(Object obj) { if (!(obj instanceof TwoFieldsUsingOr)) { return false; } TwoFieldsUsingOr other = (TwoFieldsUsingOr) obj; return Objects.equals(f, other.f) || Objects.equals(g, other.g); } @Override public int hashCode() { return 42; } } static final class ThreeFieldsUsingAnd { private final String f; private final String g; private final String h; public ThreeFieldsUsingAnd(String f, String g, String h) { this.f = f; this.g = g; this.h = h; } @Override public boolean equals(Object obj) { if (!(obj instanceof ThreeFieldsUsingAnd)) { return false; } ThreeFieldsUsingAnd other = (ThreeFieldsUsingAnd) obj; return ( Objects.equals(f, other.f) && Objects.equals(g, other.g) && Objects.equals(h, other.h) ); } @Override public int hashCode() { return defaultHashCode(this); } } static final class ThreeFieldsUsingOr { private final String f; private final String g; private final String h; public ThreeFieldsUsingOr(String f, String g, String h) { this.f = f; this.g = g; this.h = h; } @Override public boolean equals(Object obj) { if (!(obj instanceof ThreeFieldsUsingOr)) { return false; } ThreeFieldsUsingOr other = (ThreeFieldsUsingOr) obj; return ( Objects.equals(f, other.f) || Objects.equals(g, other.g) || Objects.equals(h, other.h) ); } @Override public int hashCode() { return 42; } } static final class ThreeFieldsUsingAndOr { private final String f; private final String g; private final String h; public ThreeFieldsUsingAndOr(String f, String g, String h) { this.f = f; this.g = g; this.h = h; } @Override public boolean equals(Object obj) { if (!(obj instanceof ThreeFieldsUsingAndOr)) { return false; } ThreeFieldsUsingAndOr other = (ThreeFieldsUsingAndOr) obj; return ( Objects.equals(f, other.f) && Objects.equals(g, other.g) || Objects.equals(h, other.h) ); } @Override public int hashCode() { return 42; } } static final class ThreeFieldsUsingOrAnd { private final String f; private final String g; private final String h; public ThreeFieldsUsingOrAnd(String f, String g, String h) { this.f = f; this.g = g; this.h = h; } @Override public boolean equals(Object obj) { if (!(obj instanceof ThreeFieldsUsingOrAnd)) { return false; } ThreeFieldsUsingOrAnd other = (ThreeFieldsUsingOrAnd) obj; return ( Objects.equals(f, other.f) || Objects.equals(g, other.g) && Objects.equals(h, other.h) ); } @Override public int hashCode() { return 42; } } static final class FiveFieldsUsingOr { private final String f; private final String g; private final String h; private final String i; private final String j; public FiveFieldsUsingOr(String f, String g, String h, String i, String j) { this.f = f; this.g = g; this.h = h; this.i = i; this.j = j; } @Override public boolean equals(Object obj) { if (!(obj instanceof FiveFieldsUsingOr)) { return false; } FiveFieldsUsingOr other = (FiveFieldsUsingOr) obj; return ( Objects.equals(f, other.f) || Objects.equals(g, other.g) || Objects.equals(h, other.h) || Objects.equals(i, other.i) || Objects.equals(j, other.j) ); } @Override public int hashCode() { return 42; } } static final class FiveFieldsUsingAndsAndOrs { private final String f; private final String g; private final String h; private final String i; private final String j; public FiveFieldsUsingAndsAndOrs(String f, String g, String h, String i, String j) { this.f = f; this.g = g; this.h = h; this.i = i; this.j = j; } @Override public boolean equals(Object obj) { if (!(obj instanceof FiveFieldsUsingAndsAndOrs)) { return false; } FiveFieldsUsingAndsAndOrs other = (FiveFieldsUsingAndsAndOrs) obj; return ( Objects.equals(f, other.f) || Objects.equals(g, other.g) && Objects.equals(h, other.h) || Objects.equals(i, other.i) && Objects.equals(j, other.j) ); } @Override public int hashCode() { return 42; } } static final class AtLeast2FieldsAreEqual { private final int i; private final int j; private final int k; private final int l; public AtLeast2FieldsAreEqual(int i, int j, int k, int l) { this.i = i; this.j = j; this.k = k; this.l = l; } @Override public boolean equals(Object obj) { if (!(obj instanceof AtLeast2FieldsAreEqual)) { return false; } AtLeast2FieldsAreEqual other = (AtLeast2FieldsAreEqual) obj; int x = 0; if (i == other.i) { x++; } if (j == other.j) { x++; } if (k == other.k) { x++; } if (l == other.l) { x++; } return x >= 2; } @Override public int hashCode() { return 42; } } }
9242c20e1defe12208772041ffd5a63e28144ee6
1,860
java
Java
engine/src/main/java/org/archive/crawler/reporting/Report.java
JLLeitschuh/heritrix3
015c5e7f8066f1832f9dda6ca0517386e8ab7467
[ "Apache-2.0" ]
2,180
2015-01-03T19:24:06.000Z
2022-03-31T17:53:29.000Z
engine/src/main/java/org/archive/crawler/reporting/Report.java
mfirdausharun/heritrix3
deda35eedd8011da6a51233af2dca2bd49c6be84
[ "Apache-2.0" ]
221
2015-02-23T19:43:16.000Z
2022-03-28T07:59:02.000Z
engine/src/main/java/org/archive/crawler/reporting/Report.java
mfirdausharun/heritrix3
deda35eedd8011da6a51233af2dca2bd49c6be84
[ "Apache-2.0" ]
760
2015-01-01T09:50:43.000Z
2022-03-30T16:30:52.000Z
33.214286
80
0.710753
1,002,405
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.crawler.reporting; import java.io.PrintWriter; /** * Abstract superclass for named crawl reports that need only a * StatisticsTracker and can dump a plain-text representation to a * PrintWriter. * * @author gojomo */ public abstract class Report { public Report() { } public abstract void write(PrintWriter writer, StatisticsTracker stats); public abstract String getFilename(); private boolean shouldReportAtEndOfCrawl = true; public boolean getShouldReportAtEndOfCrawl() { return shouldReportAtEndOfCrawl; } public void setShouldReportAtEndOfCrawl(boolean shouldReportAtEndOfCrawl) { this.shouldReportAtEndOfCrawl = shouldReportAtEndOfCrawl; } private boolean shouldReportDuringCrawl = true; public boolean getShouldReportDuringCrawl() { return shouldReportDuringCrawl; } public void setShouldReportDuringCrawl(boolean shouldReportDuringCrawl) { this.shouldReportDuringCrawl = shouldReportDuringCrawl; } }
9242c322669378435e0f463bea0c2e7606970352
1,086
java
Java
test/top/limitart/base/CoupleTest.java
HankXV/limitart
3e48335170764f01b832a82f5af05c30f3038716
[ "Apache-2.0" ]
16
2017-07-02T02:23:40.000Z
2021-10-14T16:49:31.000Z
test/top/limitart/base/CoupleTest.java
HankXV/limitart
3e48335170764f01b832a82f5af05c30f3038716
[ "Apache-2.0" ]
1
2017-07-10T03:06:13.000Z
2017-07-10T03:06:13.000Z
test/top/limitart/base/CoupleTest.java
HankXV/limitart
3e48335170764f01b832a82f5af05c30f3038716
[ "Apache-2.0" ]
9
2017-06-30T07:48:32.000Z
2021-04-15T08:13:51.000Z
27.15
75
0.692449
1,002,406
/* * Copyright (c) 2016-present The Limitart Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.limitart.base; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author hank * @version 2017/11/2 0002 20:43 */ public class CoupleTest { private Couple<Integer, String> couple; @Before public void setUp() { couple = Couple.ofImmutable(10, "wife"); } @Test public void proc() { Assert.assertTrue(couple.get1() == 10); Assert.assertTrue(couple.get2().equals("wife")); } }
9242c44a41f274a5495ff7ac8340de99df78e839
282
java
Java
android/app/src/main/java/com/ember/ember/model/ChatList.java
Sean2108/Ember
400a749a829af34fdbe9aa8acade330c20193ba8
[ "Apache-2.0" ]
2
2018-08-28T22:10:02.000Z
2018-08-29T07:30:09.000Z
android/app/src/main/java/com/ember/ember/model/ChatList.java
Sean2108/Ember
400a749a829af34fdbe9aa8acade330c20193ba8
[ "Apache-2.0" ]
null
null
null
android/app/src/main/java/com/ember/ember/model/ChatList.java
Sean2108/Ember
400a749a829af34fdbe9aa8acade330c20193ba8
[ "Apache-2.0" ]
2
2018-11-18T13:16:01.000Z
2019-08-19T06:06:13.000Z
16.588235
36
0.595745
1,002,407
package com.ember.ember.model; import java.util.List; public class ChatList { private String status; private List<String> data; public String getStatus() { return status; } public List<String> getData() { return data; } }
9242c606d3d210dcdead666572905f7f051b7e9a
1,554
java
Java
src/main/java/org/sonarsource/sonarlint/core/container/PicoUtils.java
billyan2018/java-rules
8ddad67c252b01d76495954251e500c561eb9a22
[ "Apache-2.0" ]
null
null
null
src/main/java/org/sonarsource/sonarlint/core/container/PicoUtils.java
billyan2018/java-rules
8ddad67c252b01d76495954251e500c561eb9a22
[ "Apache-2.0" ]
null
null
null
src/main/java/org/sonarsource/sonarlint/core/container/PicoUtils.java
billyan2018/java-rules
8ddad67c252b01d76495954251e500c561eb9a22
[ "Apache-2.0" ]
null
null
null
32.375
77
0.712355
1,002,408
/* * SonarLint Core - Implementation (trimmed) * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonarsource.sonarlint.core.container; import com.google.common.base.Throwables; import org.picocontainer.PicoLifecycleException; class PicoUtils { private PicoUtils() { // only static methods } static Throwable sanitize(Throwable t) { Throwable result = t; Throwable cause = t.getCause(); if (t instanceof PicoLifecycleException && cause != null) { if ("wrapper".equals(cause.getMessage()) && cause.getCause() != null) { result = cause.getCause(); } else { result = cause; } } return result; } static RuntimeException propagate(Throwable t) { throw Throwables.propagate(sanitize(t)); } }
9242c6988a7eb0cf7f7c6fe3459be8bb0230ad27
561
java
Java
Amazon/Arrays/3. Longest Substring Without Repeating Characters.java
dsupriya/LeetCode
c1d3b2e612a08a5c7b7fdf52445578747dbe62e0
[ "MIT" ]
3
2020-07-13T17:53:54.000Z
2021-12-29T06:50:42.000Z
Amazon/Arrays/3. Longest Substring Without Repeating Characters.java
dsupriya/LeetCode
c1d3b2e612a08a5c7b7fdf52445578747dbe62e0
[ "MIT" ]
null
null
null
Amazon/Arrays/3. Longest Substring Without Repeating Characters.java
dsupriya/LeetCode
c1d3b2e612a08a5c7b7fdf52445578747dbe62e0
[ "MIT" ]
null
null
null
22.44
59
0.365419
1,002,409
class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(); HashSet <Character> hs = new HashSet <Character>(); int i,j; i=j=0; int max = 0; while(i<n && j<n) { if(!hs.contains(s.charAt(j))) { hs.add(s.charAt(j)); max = Math.max(max,j-i+1); j++; } else { hs.remove(s.charAt(i)); i++; } } return max; } }
9242c6ed68a2a39d4890cab58c75a53fc3b4ecad
2,206
java
Java
polygenesis-craftsman/src/test/java/com/invoiceful/genesis/contexts/access/SignInDomainService.java
polygenesis-projects/polygenesis-platform
68467e6c51314d370e93b26ccb65431818acfa37
[ "Apache-2.0" ]
7
2019-07-17T21:45:21.000Z
2021-01-26T06:35:31.000Z
polygenesis-craftsman/src/test/java/com/invoiceful/genesis/contexts/access/SignInDomainService.java
polygenesis-projects/polygenesis-platform
68467e6c51314d370e93b26ccb65431818acfa37
[ "Apache-2.0" ]
null
null
null
polygenesis-craftsman/src/test/java/com/invoiceful/genesis/contexts/access/SignInDomainService.java
polygenesis-projects/polygenesis-platform
68467e6c51314d370e93b26ccb65431818acfa37
[ "Apache-2.0" ]
2
2020-07-25T17:46:40.000Z
2021-12-17T15:31:30.000Z
39.392857
94
0.654125
1,002,410
/*- * ==========================LICENSE_START================================= * PolyGenesis Platform * ======================================================================== * Copyright (C) 2015 - 2019 OREGOR LTD * ======================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ===========================LICENSE_END================================== */ package com.invoiceful.genesis.contexts.access; import io.polygenesis.abstraction.data.DataPrimitive; import io.polygenesis.abstraction.data.PrimitiveType; import io.polygenesis.abstraction.thing.Purpose; import io.polygenesis.abstraction.thing.Thing; import io.polygenesis.abstraction.thing.dsl.FunctionBuilder; import io.polygenesis.abstraction.thing.dsl.ThingBuilder; import io.polygenesis.commons.valueobjects.PackageName; import io.polygenesis.commons.valueobjects.VariableName; /** @author Christos Tsakostas */ public class SignInDomainService { /** * Create thing. * * @param rootPackageName the root package name * @return the thing */ public static Thing create(PackageName rootPackageName) { Thing signInDomainService = ThingBuilder.domainService("signInDomainService") .setPreferredPackage("com.invoiceful.access.identity") .createThing(); signInDomainService.addFunction( FunctionBuilder.of(signInDomainService, "create", Purpose.create()) .addArgument(DataPrimitive.of(PrimitiveType.STRING, new VariableName("email"))) .addArgument(DataPrimitive.of(PrimitiveType.STRING, new VariableName("password"))) .build()); return signInDomainService; } }
9242c780d3fbc362bc2565ff2693e7b282000ff2
13,553
java
Java
lit-support/src/main/java/com/github/lit/support/data/jdbc/JdbcRepositoryImpl.java
l8744607990/lit-tools
3a0dd9badbcfabc5cf5767d7a711897c24c20078
[ "Apache-2.0" ]
13
2018-05-18T07:32:35.000Z
2021-12-31T01:31:16.000Z
lit-support/src/main/java/com/github/lit/support/data/jdbc/JdbcRepositoryImpl.java
l8744607990/lit-tools
3a0dd9badbcfabc5cf5767d7a711897c24c20078
[ "Apache-2.0" ]
null
null
null
lit-support/src/main/java/com/github/lit/support/data/jdbc/JdbcRepositoryImpl.java
l8744607990/lit-tools
3a0dd9badbcfabc5cf5767d7a711897c24c20078
[ "Apache-2.0" ]
8
2018-11-16T03:14:34.000Z
2021-12-13T10:00:15.000Z
40.822289
123
0.676603
1,002,411
package com.github.lit.support.data.jdbc; import com.github.lit.support.data.SQL; import com.github.lit.support.data.SQLUtils; import com.github.lit.support.data.domain.*; import com.github.lit.support.util.ClassUtils; import com.github.lit.support.util.bean.BeanUtils; import com.github.lit.support.util.lamabda.SerializedFunction; import com.github.lit.support.util.lamabda.SerializedLambdaUtils; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.namedparam.EmptySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import java.beans.PropertyDescriptor; import java.util.*; /** * @author liulu * @version v1.0 * date 2018-12-10 14:28 */ @Slf4j @NoArgsConstructor public class JdbcRepositoryImpl implements JdbcRepository { private static final String PARAM = "param"; private static final String PARAM_EQ = " = :param"; private static final String PARAM_IN = " in (:param)"; @Setter private String dbName; @Getter @Setter private NamedParameterJdbcOperations jdbcOperations; private String getDbName() { if (StringUtils.isEmpty(dbName)) { dbName = jdbcOperations.getJdbcOperations() .execute((ConnectionCallback<String>) con -> con.getMetaData().getDatabaseProductName()); } return dbName; } public JdbcRepositoryImpl(NamedParameterJdbcOperations jdbcOperations) { this.jdbcOperations = jdbcOperations; } @Override public <E> int insert(E entity) { Objects.requireNonNull(entity, "insert with entity can not be null"); Class<?> entityClass = entity.getClass(); TableMetaDate metaDate = TableMetaDate.forClass(entityClass); String sql = SQLUtils.insertSQL(entity, SQL.Type.JDBC).toString(); KeyHolder keyHolder = new GeneratedKeyHolder(); SqlParameterSource sqlParameterSource = getSqlParameterSource(entity); logSqlAndParams(sql, sqlParameterSource); int insert = jdbcOperations.update(sql, sqlParameterSource, keyHolder); PropertyDescriptor keyPs = BeanUtils.getPropertyDescriptor(entityClass, metaDate.getKeyProperty()); // set key property if (keyPs != null) { ReflectionUtils.invokeMethod(keyPs.getWriteMethod(), entity, Objects.requireNonNull(keyHolder.getKey()).longValue()); } return insert; } @Override public <E> int batchInsert(Collection<E> eList) { if (CollectionUtils.isEmpty(eList)) { return 0; } E entity = eList.iterator().next(); SQL sql = SQLUtils.insertSQL(entity, SQL.Type.JDBC); SqlParameterSource[] parameterSources = eList.stream() .map(this::getSqlParameterSource).toArray(SqlParameterSource[]::new); int[] updateResult = jdbcOperations.batchUpdate(sql.toString(), parameterSources); int row = 0; for (int res : updateResult) { row += res; } return row; } @Override public <E> int update(E entity) { SQL sql = SQLUtils.updateSQL(entity, false, SQL.Type.JDBC); return jdbcOperations.update(sql.toString(), getSqlParameterSource(entity)); } @Override public <E> int updateSelective(E entity) { String sql = SQLUtils.updateSQL(entity, true, SQL.Type.JDBC).toString(); SqlParameterSource sqlParameterSource = getSqlParameterSource(entity); logSqlAndParams(sql, sqlParameterSource); return jdbcOperations.update(sql, sqlParameterSource); } @Override public <E> int delete(E entity) { Assert.notNull(entity, "deleteById with entity can not be null"); TableMetaDate metaDate = TableMetaDate.forClass(entity.getClass()); PropertyDescriptor keyPs = BeanUtils.getPropertyDescriptor(entity.getClass(), metaDate.getKeyProperty()); Assert.notNull(keyPs, "can not find key property from " + entity.getClass().getName()); Object keyValue = ReflectionUtils.invokeMethod(keyPs.getReadMethod(), entity); Assert.notNull(keyValue, "key value can not be null"); String sql = SQLUtils.deleteSQL(entity.getClass(), SQL.Type.JDBC).toString(); SqlParameterSource sqlParam = getSqlParameterSource(Collections.singletonMap(metaDate.getKeyProperty(), keyValue)); logSqlAndParams(sql, sqlParam); return jdbcOperations.update(sql, sqlParam); } @Override public <E> int deleteById(Class<E> eClass, Long id) { Assert.notNull(id, "id can not be null"); TableMetaDate metaDate = TableMetaDate.forClass(eClass); String sql = SQLUtils.deleteSQL(eClass, SQL.Type.JDBC).toString(); SqlParameterSource sqlParam = getSqlParameterSource(Collections.singletonMap(metaDate.getKeyProperty(), id)); logSqlAndParams(sql, sqlParam); return jdbcOperations.update(sql, sqlParam); } @Override public <E> int deleteByIds(Class<E> eClass, Collection<Long> ids) { if (CollectionUtils.isEmpty(ids)) { return 0; } TableMetaDate metaDate = TableMetaDate.forClass(eClass); String sql = SQL.init().DELETE_FROM(metaDate.getTableName()) .WHERE(metaDate.getKeyColumn() + PARAM_IN) .toString(); SqlParameterSource sqlParam = getSqlParameterSource(Collections.singletonMap(PARAM, ids)); logSqlAndParams(sql, sqlParam); return jdbcOperations.update(sql, sqlParam); } @Override public <E> E selectById(Class<E> eClass, Long id) { TableMetaDate metaDate = TableMetaDate.forClass(eClass); SQL sql = SQL.init().SELECT(metaDate.getBaseColumns()) .FROM(metaDate.getTableName()) .WHERE(metaDate.getKeyColumn() + PARAM_EQ); return selectForObject(sql, Collections.singletonMap(PARAM, id), eClass); } @Override public <E> List<E> selectByIds(Class<E> eClass, Collection<Long> ids) { if (CollectionUtils.isEmpty(ids)) { return Collections.emptyList(); } TableMetaDate metaDate = TableMetaDate.forClass(eClass); SQL sql = SQL.init().SELECT(metaDate.getBaseColumns()) .FROM(metaDate.getTableName()) .WHERE(metaDate.getKeyColumn() + PARAM_IN); return selectForList(sql, Collections.singletonMap(PARAM, ids), eClass); } @Override public <E> List<E> selectAll(Class<E> eClass) { TableMetaDate metaDate = TableMetaDate.forClass(eClass); String sql = SQL.init().SELECT(metaDate.getBaseColumns()) .FROM(metaDate.getTableName()) .toString(); logSqlAndParams(sql, null); return jdbcOperations.query(sql, Collections.emptyMap(), AnnotationRowMapper.newInstance(eClass)); } @Override public <E, R> E selectByProperty(SerializedFunction<E, R> serializedFunction, Object value) { Class<E> eClass = SerializedLambdaUtils.getLambdaClass(serializedFunction); SQL sql = getSelectByPropertySql(serializedFunction, eClass); return selectForObject(sql, Collections.singletonMap(PARAM, value), eClass); } @Override public <E, R> List<E> selectListByProperty(SerializedFunction<E, R> serializedFunction, Object value) { Class<E> eClass = SerializedLambdaUtils.getLambdaClass(serializedFunction); String sql = getSelectByPropertySql(serializedFunction, eClass).toString(); SqlParameterSource sqlParams = getSqlParameterSource(Collections.singletonMap(PARAM, value)); logSqlAndParams(sql, sqlParams); return jdbcOperations.query(sql, sqlParams, AnnotationRowMapper.newInstance(eClass)); } private <E, R> SQL getSelectByPropertySql(SerializedFunction<E, R> serializedFunction, Class<E> eClass) { String property = SerializedLambdaUtils.getProperty(serializedFunction); TableMetaDate metaDate = TableMetaDate.forClass(eClass); String column = metaDate.getFieldColumnMap().get(property); return SQL.init().SELECT(metaDate.getBaseColumns()) .FROM(metaDate.getTableName()) .WHERE(column + PARAM_EQ); } @Override public <E, C> List<E> selectList(Class<E> eClass, C condition) { return selectListWithOrder(eClass, condition, null); } @Override public <E, C> List<E> selectListWithOrder(Class<E> eClass, C condition, Sort sort) { String sql = SQLUtils.selectSQL(eClass, condition, sort, SQL.Type.JDBC).toString(); SqlParameterSource sqlParams = getSqlParameterSource(condition); logSqlAndParams(sql, sqlParams); return jdbcOperations.query(sql, sqlParams, AnnotationRowMapper.newInstance(eClass)); } @Override public <E, C extends Pageable> Page<E> selectPageList(Class<E> eClass, C condition) { SQL sql = SQLUtils.selectSQL(eClass, condition, condition.getSort(), SQL.Type.JDBC); return selectForPageList(sql, condition, eClass); } @Override public <E> E selectForObject(SQL sql, Object args, Class<E> requiredType) { List<E> rs = selectForList(sql, args, requiredType); if (CollectionUtils.isEmpty(rs)) { return null; } if (rs.size() > 1) { throw new IncorrectResultSizeDataAccessException(1, rs.size()); } return rs.iterator().next(); } @Override public <E> List<E> selectForList(SQL sql, Object args, Class<E> requiredType) { if (args == null) { args = Collections.emptyMap(); } String sqlStr = sql.toString(); SqlParameterSource parameterSource = getSqlParameterSource(args); logSqlAndParams(sqlStr, parameterSource); if (ClassUtils.isSimpleValueType(requiredType)) { return jdbcOperations.queryForList(sqlStr, parameterSource, requiredType); } return jdbcOperations.query(sqlStr, parameterSource, AnnotationRowMapper.newInstance(requiredType)); } @Override public <E> Page<E> selectForPageList(SQL sql, Pageable args, Class<E> requiredType) { Integer count = 0; SqlParameterSource sqlParameterSource = getSqlParameterSource(args); if (args.isCount()) { String countSql = sql.countSql(); logSqlAndParams(countSql, sqlParameterSource); count = jdbcOperations.queryForObject(countSql, sqlParameterSource, int.class); if (count == null || count <= 0) { return Page.emptyPage(); } } String pageSql = SQLUtils.getPageSql(getDbName(), sql.toString(), args.getPageSize(), args.getPageNum()); logSqlAndParams(pageSql, sqlParameterSource); List<E> rs = jdbcOperations.query(pageSql, sqlParameterSource, AnnotationRowMapper.newInstance(requiredType)); PageInfo pageInfo = new PageInfo(args.getPageSize(), args.getPageNum(), count); return new Page<>(rs, pageInfo); } @Override public <E> int count(Class<E> eClass) { TableMetaDate metaDate = TableMetaDate.forClass(eClass); SQL sql = SQL.init().SELECT("count(*)") .FROM(metaDate.getTableName()); return selectForObject(sql, Collections.emptyMap(), int.class); } @Override public <E, R> int countByProperty(SerializedFunction<E, R> serializedFunction, Object value) { Class<E> eClass = SerializedLambdaUtils.getLambdaClass(serializedFunction); String property = SerializedLambdaUtils.getProperty(serializedFunction); TableMetaDate metaDate = TableMetaDate.forClass(eClass); SQL sql = SQL.init().SELECT("count(*)") .FROM(metaDate.getTableName()) .WHERE(metaDate.getColumn(property) + PARAM_EQ); return selectForObject(sql, Collections.singletonMap(PARAM, value), int.class); } private void logSqlAndParams(String sql, SqlParameterSource params) { if (params == null || params.getParameterNames() == null) { log.info("\n sql: {} \n params: ", sql); return; } StringBuilder paramLog = new StringBuilder(); for (String parameterName : params.getParameterNames()) { Object value = params.getValue(parameterName); if (!StringUtils.isEmpty(value)) { paramLog.append(parameterName).append("=").append(value).append(", "); } } log.info("\n sql: {} \n params: {}", sql, paramLog); } private <E> SqlParameterSource getSqlParameterSource(E params) { if (params == null) { return new EmptySqlParameterSource(); } Map<String, Object> paramMap = params instanceof Map ? (Map) params : BeanUtils.beanToMap(params); return new MapSqlParameterSource(paramMap); } }
9242c93069b2aa3d7f88ca9d32fe2270e5ae1739
1,731
java
Java
PTsix/src/main/java/com/PT/tools/ResponseData.java
Chen-Dixi/spring-end
4a7882177a6e843af10be80a82c0d5a5e7b13d2e
[ "MIT" ]
null
null
null
PTsix/src/main/java/com/PT/tools/ResponseData.java
Chen-Dixi/spring-end
4a7882177a6e843af10be80a82c0d5a5e7b13d2e
[ "MIT" ]
null
null
null
PTsix/src/main/java/com/PT/tools/ResponseData.java
Chen-Dixi/spring-end
4a7882177a6e843af10be80a82c0d5a5e7b13d2e
[ "MIT" ]
5
2018-03-05T11:33:16.000Z
2018-06-07T13:37:26.000Z
27.919355
69
0.630272
1,002,412
package com.PT.tools; import java.util.HashMap; import java.util.Map; /** * created by yxhuang * 快速返回信息类,包括很多常用操作 */ public class ResponseData { private String message; private int code; private Map<String, Object> data = new HashMap<String, Object>(); public String getMessage() { return message; } public int getCode() { return code; } public Map<String, Object> getData() { return data; } public ResponseData putDataValue(String key, Object value) { data.put(key, value); return this; } private ResponseData(int code, String message) { this.code = code; this.message = message; } public void setError(int status, String message) { data.put("statusCode", status); data.put("errorDesc", message); } public Map getBody() { return this.data; } public static ResponseData ok() { return new ResponseData(200, "Ok"); } public static ResponseData createOk() { return new ResponseData(201, "Ok"); } public static ResponseData notFound() { return new ResponseData(404, "Not Found"); } public static ResponseData badRequest() { return new ResponseData(400, "Bad Request"); } public static ResponseData forbidden() { return new ResponseData(403, "Forbidden"); } public static ResponseData unauthorized() { return new ResponseData(401, "unauthorized"); } public static ResponseData serverInternalError() { return new ResponseData(500, "Server Internal Error"); } public static ResponseData customerError() { return new ResponseData(1001, "customer Error"); } }
9242ca4bb0ed85e5ff285a8f4262fd0f95acec49
1,503
java
Java
src/main/java/com/example/javamavenjunithelloworld/HelloApp.java
akshaykamthe651/sonarqube-demoProject
94529c93513ad71cfe4efd2d7268ef99ec21f2ca
[ "Unlicense" ]
null
null
null
src/main/java/com/example/javamavenjunithelloworld/HelloApp.java
akshaykamthe651/sonarqube-demoProject
94529c93513ad71cfe4efd2d7268ef99ec21f2ca
[ "Unlicense" ]
null
null
null
src/main/java/com/example/javamavenjunithelloworld/HelloApp.java
akshaykamthe651/sonarqube-demoProject
94529c93513ad71cfe4efd2d7268ef99ec21f2ca
[ "Unlicense" ]
1
2021-08-12T11:27:55.000Z
2021-08-12T11:27:55.000Z
31.978723
109
0.606121
1,002,413
package com.example.javamavenjunithelloworld; /** * A very basic program that demonstrates the use of JUnit tests. The tests include a sample unit test and an * integration test. */ public class HelloApp { static int DEFAULT_TIMES = 3; static int EXIT_STATUS_PARAMETER_NOT_UNDERSTOOD = 2; static int EXIT_STATUS_HELLO_FAILED = 4; /** * The main method of this program. * * @param args Arguments passed to this program. */ public static void main(String[] args) { int times = DEFAULT_TIMES; if (args.length >= 1) { try { times = Integer.valueOf(args[0]); } catch (NumberFormatException e) { System.err.println("I don't understand the parameter you passed me. Is it a number? " + "Parameter was: [" + args[0] + "]"); System.exit(EXIT_STATUS_PARAMETER_NOT_UNDERSTOOD); } } Hello hi = new Hello(); try { hi.setTimes(times); } catch (IllegalArgumentException e) { System.err.println("Something went wrong: " + e.getMessage()); System.exit(EXIT_STATUS_HELLO_FAILED); } hi.sayHello(System.out); System.out.println("checking Qualitygate fail Condition on Sonarqube"); System.out.println("checking Qualitygate fail Condition on Sonarqube"); System.out.println("checking Qualitygate fail Condition on Sonarqube"); } }
9242cc3224a793f134961b8ddac7d4dcca2a7c56
399
java
Java
fiber-demo/fiber-demo-dubbo/src/main/java/com/fiber/demo/dubbo/service/impl/TestServiceImpl.java
panyox/fiber
e8c1a73cb86fb551b77d35c907b83f23af66f7e8
[ "Apache-2.0" ]
null
null
null
fiber-demo/fiber-demo-dubbo/src/main/java/com/fiber/demo/dubbo/service/impl/TestServiceImpl.java
panyox/fiber
e8c1a73cb86fb551b77d35c907b83f23af66f7e8
[ "Apache-2.0" ]
null
null
null
fiber-demo/fiber-demo-dubbo/src/main/java/com/fiber/demo/dubbo/service/impl/TestServiceImpl.java
panyox/fiber
e8c1a73cb86fb551b77d35c907b83f23af66f7e8
[ "Apache-2.0" ]
null
null
null
21
53
0.721805
1,002,414
package com.fiber.demo.dubbo.service.impl; import com.fiber.demo.dubbo.service.TestService; import com.fiber.rpc.dubbo.annotation.FiberService; import com.fiber.rpc.dubbo.annotation.GetRoute; /** * @author panyox */ @FiberService("test") public class TestServiceImpl implements TestService { @Override @GetRoute("hello") public String test() { return "hello world"; } }
9242cc393619055fcd42c108f808036dd9d310bf
437
java
Java
blog/src/main/java/com/kerbores/utils/ua/BrowserType.java
lihongwu19921215/blog
9019f3c1368c4452960238270d340e4ae046933a
[ "Apache-2.0" ]
null
null
null
blog/src/main/java/com/kerbores/utils/ua/BrowserType.java
lihongwu19921215/blog
9019f3c1368c4452960238270d340e4ae046933a
[ "Apache-2.0" ]
null
null
null
blog/src/main/java/com/kerbores/utils/ua/BrowserType.java
lihongwu19921215/blog
9019f3c1368c4452960238270d340e4ae046933a
[ "Apache-2.0" ]
null
null
null
16.807692
57
0.627002
1,002,415
package com.kerbores.utils.ua; public enum BrowserType { WEB_BROWSER("Browser"), MOBILE_BROWSER("Browser (mobile)"), TEXT_BROWSER("Browser (text only)"), EMAIL_CLIENT("Email Client"), ROBOT("Robot"), TOOL("Downloading tool"), UNKNOWN("unknown"); private String name; private BrowserType(String name) { this.name = name; } public String getName() { return this.name; } }
9242cc5fb68afd99ad4b754c233405a31a7cd6ca
29,844
java
Java
unused/mine/packages/org.cakelab.blender.fileviewer-src-0.0.10/src-dna/org/blender/dna/TintGpencilModifierData.java
sirivus/studioonline
536cb4f3f8a8640821a47c0bdbef3877fe2e6f7a
[ "MIT" ]
null
null
null
unused/mine/packages/org.cakelab.blender.fileviewer-src-0.0.10/src-dna/org/blender/dna/TintGpencilModifierData.java
sirivus/studioonline
536cb4f3f8a8640821a47c0bdbef3877fe2e6f7a
[ "MIT" ]
null
null
null
unused/mine/packages/org.cakelab.blender.fileviewer-src-0.0.10/src-dna/org/blender/dna/TintGpencilModifierData.java
sirivus/studioonline
536cb4f3f8a8640821a47c0bdbef3877fe2e6f7a
[ "MIT" ]
null
null
null
30.329268
179
0.684995
1,002,416
package org.blender.dna; import java.io.IOException; import org.cakelab.blender.io.block.Block; import org.cakelab.blender.io.block.BlockTable; import org.cakelab.blender.nio.CArrayFacade; import org.cakelab.blender.nio.CFacade; import org.cakelab.blender.nio.CMetaData; import org.cakelab.blender.nio.CPointer; /** * Generated facet for DNA struct type 'TintGpencilModifierData'. * * <h3>Class Documentation</h3> * */ @CMetaData(size32=340, size64=368) public class TintGpencilModifierData extends CFacade { /** * This is the sdna index of the struct TintGpencilModifierData. * <p> * It is required when allocating a new block to store data for TintGpencilModifierData. * </p> * @see {@link org.cakelab.blender.io.dna.internal.StructDNA} * @see {@link org.cakelab.blender.io.block.BlockTable#allocate} */ public static final int __DNA__SDNA_INDEX = 614; /** * Field descriptor (offset) for struct member 'modifier'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__modifier); * CPointer&lt;GpencilModifierData&gt; p_modifier = p.cast(new Class[]{GpencilModifierData.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'modifier'</li> * <li>Signature: 'GpencilModifierData'</li> * <li>Actual Size (32bit/64bit): 92/104</li> * </ul> */ public static final long[] __DNA__FIELD__modifier = new long[]{0, 0}; /** * Field descriptor (offset) for struct member 'object'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__object); * CPointer&lt;CPointer&lt;BlenderObject&gt;&gt; p_object = p.cast(new Class[]{CPointer.class, BlenderObject.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'object'</li> * <li>Signature: 'Object*'</li> * <li>Actual Size (32bit/64bit): 4/8</li> * </ul> */ public static final long[] __DNA__FIELD__object = new long[]{92, 104}; /** * Field descriptor (offset) for struct member 'material'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p>{@link Material} for filtering. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__material); * CPointer&lt;CPointer&lt;Material&gt;&gt; p_material = p.cast(new Class[]{CPointer.class, Material.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'material'</li> * <li>Signature: 'Material*'</li> * <li>Actual Size (32bit/64bit): 4/8</li> * </ul> */ public static final long[] __DNA__FIELD__material = new long[]{96, 112}; /** * Field descriptor (offset) for struct member 'layername'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Layer name. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__layername); * CPointer&lt;CArrayFacade&lt;Byte&gt;&gt; p_layername = p.cast(new Class[]{CArrayFacade.class, Byte.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'layername'</li> * <li>Signature: 'char[64]'</li> * <li>Actual Size (32bit/64bit): 64/64</li> * </ul> */ public static final long[] __DNA__FIELD__layername = new long[]{100, 120}; /** * Field descriptor (offset) for struct member 'materialname'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p>{@link Material} name. * @deprecated * Deprecated</p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__materialname); * CPointer&lt;CArrayFacade&lt;Byte&gt;&gt; p_materialname = p.cast(new Class[]{CArrayFacade.class, Byte.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'materialname'</li> * <li>Signature: 'char[64]'</li> * <li>Actual Size (32bit/64bit): 64/64</li> * </ul> */ public static final long[] __DNA__FIELD__materialname = new long[]{164, 184}; /** * Field descriptor (offset) for struct member 'vgname'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Optional vertexgroup name, MAX_VGROUP_NAME. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__vgname); * CPointer&lt;CArrayFacade&lt;Byte&gt;&gt; p_vgname = p.cast(new Class[]{CArrayFacade.class, Byte.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'vgname'</li> * <li>Signature: 'char[64]'</li> * <li>Actual Size (32bit/64bit): 64/64</li> * </ul> */ public static final long[] __DNA__FIELD__vgname = new long[]{228, 248}; /** * Field descriptor (offset) for struct member 'pass_index'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Custom index for passes. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__pass_index); * CPointer&lt;Integer&gt; p_pass_index = p.cast(new Class[]{Integer.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'pass_index'</li> * <li>Signature: 'int'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__pass_index = new long[]{292, 312}; /** * Field descriptor (offset) for struct member 'layer_pass'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Custom index for passes. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__layer_pass); * CPointer&lt;Integer&gt; p_layer_pass = p.cast(new Class[]{Integer.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'layer_pass'</li> * <li>Signature: 'int'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__layer_pass = new long[]{296, 316}; /** * Field descriptor (offset) for struct member 'flag'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Flags. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__flag); * CPointer&lt;Integer&gt; p_flag = p.cast(new Class[]{Integer.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'flag'</li> * <li>Signature: 'int'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__flag = new long[]{300, 320}; /** * Field descriptor (offset) for struct member 'mode'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Mode (Stroke/Fill/Both). </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__mode); * CPointer&lt;Integer&gt; p_mode = p.cast(new Class[]{Integer.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'mode'</li> * <li>Signature: 'int'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__mode = new long[]{304, 324}; /** * Field descriptor (offset) for struct member 'factor'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__factor); * CPointer&lt;Float&gt; p_factor = p.cast(new Class[]{Float.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'factor'</li> * <li>Signature: 'float'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__factor = new long[]{308, 328}; /** * Field descriptor (offset) for struct member 'radius'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__radius); * CPointer&lt;Float&gt; p_radius = p.cast(new Class[]{Float.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'radius'</li> * <li>Signature: 'float'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__radius = new long[]{312, 332}; /** * Field descriptor (offset) for struct member 'rgb'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Simple Tint color. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__rgb); * CPointer&lt;CArrayFacade&lt;Float&gt;&gt; p_rgb = p.cast(new Class[]{CArrayFacade.class, Float.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'rgb'</li> * <li>Signature: 'float[3]'</li> * <li>Actual Size (32bit/64bit): 12/12</li> * </ul> */ public static final long[] __DNA__FIELD__rgb = new long[]{316, 336}; /** * Field descriptor (offset) for struct member 'type'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Type of Tint. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__type); * CPointer&lt;Integer&gt; p_type = p.cast(new Class[]{Integer.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'type'</li> * <li>Signature: 'int'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__type = new long[]{328, 348}; /** * Field descriptor (offset) for struct member 'curve_intensity'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__curve_intensity); * CPointer&lt;CPointer&lt;CurveMapping&gt;&gt; p_curve_intensity = p.cast(new Class[]{CPointer.class, CurveMapping.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'curve_intensity'</li> * <li>Signature: 'CurveMapping*'</li> * <li>Actual Size (32bit/64bit): 4/8</li> * </ul> */ public static final long[] __DNA__FIELD__curve_intensity = new long[]{332, 352}; /** * Field descriptor (offset) for struct member 'colorband'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * TintGpencilModifierData tintgpencilmodifierdata = ...; * CPointer&lt;Object&gt; p = tintgpencilmodifierdata.__dna__addressof(TintGpencilModifierData.__DNA__FIELD__colorband); * CPointer&lt;CPointer&lt;ColorBand&gt;&gt; p_colorband = p.cast(new Class[]{CPointer.class, ColorBand.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'colorband'</li> * <li>Signature: 'ColorBand*'</li> * <li>Actual Size (32bit/64bit): 4/8</li> * </ul> */ public static final long[] __DNA__FIELD__colorband = new long[]{336, 360}; public TintGpencilModifierData(long __address, Block __block, BlockTable __blockTable) { super(__address, __block, __blockTable); } protected TintGpencilModifierData(TintGpencilModifierData that) { super(that.__io__address, that.__io__block, that.__io__blockTable); } /** * Get method for struct member 'modifier'. * @see #__DNA__FIELD__modifier */ public GpencilModifierData getModifier() throws IOException { if ((__io__pointersize == 8)) { return new GpencilModifierData(__io__address + 0, __io__block, __io__blockTable); } else { return new GpencilModifierData(__io__address + 0, __io__block, __io__blockTable); } } /** * Set method for struct member 'modifier'. * @see #__DNA__FIELD__modifier */ public void setModifier(GpencilModifierData modifier) throws IOException { long __dna__offset; if ((__io__pointersize == 8)) { __dna__offset = 0; } else { __dna__offset = 0; } if (__io__equals(modifier, __io__address + __dna__offset)) { return; } else if (__io__same__encoding(this, modifier)) { __io__native__copy(__io__block, __io__address + __dna__offset, modifier); } else { __io__generic__copy( getModifier(), modifier); } } /** * Get method for struct member 'object'. * @see #__DNA__FIELD__object */ public CPointer<BlenderObject> getObject() throws IOException { long __dna__targetAddress; if ((__io__pointersize == 8)) { __dna__targetAddress = __io__block.readLong(__io__address + 104); } else { __dna__targetAddress = __io__block.readLong(__io__address + 92); } Class<?>[] __dna__targetTypes = new Class[]{BlenderObject.class}; return new CPointer<BlenderObject>(__dna__targetAddress, __dna__targetTypes, __io__blockTable.getBlock(__dna__targetAddress, BlenderObject.__DNA__SDNA_INDEX), __io__blockTable); } /** * Set method for struct member 'object'. * @see #__DNA__FIELD__object */ public void setObject(CPointer<BlenderObject> object) throws IOException { long __address = ((object == null) ? 0 : object.getAddress()); if ((__io__pointersize == 8)) { __io__block.writeLong(__io__address + 104, __address); } else { __io__block.writeLong(__io__address + 92, __address); } } /** * Get method for struct member 'material'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p>{@link Material} for filtering. </p> * @see #__DNA__FIELD__material */ public CPointer<Material> getMaterial() throws IOException { long __dna__targetAddress; if ((__io__pointersize == 8)) { __dna__targetAddress = __io__block.readLong(__io__address + 112); } else { __dna__targetAddress = __io__block.readLong(__io__address + 96); } Class<?>[] __dna__targetTypes = new Class[]{Material.class}; return new CPointer<Material>(__dna__targetAddress, __dna__targetTypes, __io__blockTable.getBlock(__dna__targetAddress, Material.__DNA__SDNA_INDEX), __io__blockTable); } /** * Set method for struct member 'material'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p>{@link Material} for filtering. </p> * @see #__DNA__FIELD__material */ public void setMaterial(CPointer<Material> material) throws IOException { long __address = ((material == null) ? 0 : material.getAddress()); if ((__io__pointersize == 8)) { __io__block.writeLong(__io__address + 112, __address); } else { __io__block.writeLong(__io__address + 96, __address); } } /** * Get method for struct member 'layername'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Layer name. </p> * @see #__DNA__FIELD__layername */ public CArrayFacade<Byte> getLayername() throws IOException { Class<?>[] __dna__targetTypes = new Class[]{Byte.class}; int[] __dna__dimensions = new int[]{ 64 }; if ((__io__pointersize == 8)) { return new CArrayFacade<Byte>(__io__address + 120, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } else { return new CArrayFacade<Byte>(__io__address + 100, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } } /** * Set method for struct member 'layername'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Layer name. </p> * @see #__DNA__FIELD__layername */ public void setLayername(CArrayFacade<Byte> layername) throws IOException { long __dna__offset; if ((__io__pointersize == 8)) { __dna__offset = 120; } else { __dna__offset = 100; } if (__io__equals(layername, __io__address + __dna__offset)) { return; } else if (__io__same__encoding(this, layername)) { __io__native__copy(__io__block, __io__address + __dna__offset, layername); } else { __io__generic__copy( getLayername(), layername); } } /** * Get method for struct member 'materialname'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p>{@link Material} name. * @deprecated * Deprecated</p> * @see #__DNA__FIELD__materialname */ public CArrayFacade<Byte> getMaterialname() throws IOException { Class<?>[] __dna__targetTypes = new Class[]{Byte.class}; int[] __dna__dimensions = new int[]{ 64 }; if ((__io__pointersize == 8)) { return new CArrayFacade<Byte>(__io__address + 184, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } else { return new CArrayFacade<Byte>(__io__address + 164, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } } /** * Set method for struct member 'materialname'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p>{@link Material} name. * @deprecated * Deprecated</p> * @see #__DNA__FIELD__materialname */ public void setMaterialname(CArrayFacade<Byte> materialname) throws IOException { long __dna__offset; if ((__io__pointersize == 8)) { __dna__offset = 184; } else { __dna__offset = 164; } if (__io__equals(materialname, __io__address + __dna__offset)) { return; } else if (__io__same__encoding(this, materialname)) { __io__native__copy(__io__block, __io__address + __dna__offset, materialname); } else { __io__generic__copy( getMaterialname(), materialname); } } /** * Get method for struct member 'vgname'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Optional vertexgroup name, MAX_VGROUP_NAME. </p> * @see #__DNA__FIELD__vgname */ public CArrayFacade<Byte> getVgname() throws IOException { Class<?>[] __dna__targetTypes = new Class[]{Byte.class}; int[] __dna__dimensions = new int[]{ 64 }; if ((__io__pointersize == 8)) { return new CArrayFacade<Byte>(__io__address + 248, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } else { return new CArrayFacade<Byte>(__io__address + 228, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } } /** * Set method for struct member 'vgname'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Optional vertexgroup name, MAX_VGROUP_NAME. </p> * @see #__DNA__FIELD__vgname */ public void setVgname(CArrayFacade<Byte> vgname) throws IOException { long __dna__offset; if ((__io__pointersize == 8)) { __dna__offset = 248; } else { __dna__offset = 228; } if (__io__equals(vgname, __io__address + __dna__offset)) { return; } else if (__io__same__encoding(this, vgname)) { __io__native__copy(__io__block, __io__address + __dna__offset, vgname); } else { __io__generic__copy( getVgname(), vgname); } } /** * Get method for struct member 'pass_index'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Custom index for passes. </p> * @see #__DNA__FIELD__pass_index */ public int getPass_index() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readInt(__io__address + 312); } else { return __io__block.readInt(__io__address + 292); } } /** * Set method for struct member 'pass_index'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Custom index for passes. </p> * @see #__DNA__FIELD__pass_index */ public void setPass_index(int pass_index) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeInt(__io__address + 312, pass_index); } else { __io__block.writeInt(__io__address + 292, pass_index); } } /** * Get method for struct member 'layer_pass'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Custom index for passes. </p> * @see #__DNA__FIELD__layer_pass */ public int getLayer_pass() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readInt(__io__address + 316); } else { return __io__block.readInt(__io__address + 296); } } /** * Set method for struct member 'layer_pass'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Custom index for passes. </p> * @see #__DNA__FIELD__layer_pass */ public void setLayer_pass(int layer_pass) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeInt(__io__address + 316, layer_pass); } else { __io__block.writeInt(__io__address + 296, layer_pass); } } /** * Get method for struct member 'flag'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Flags. </p> * @see #__DNA__FIELD__flag */ public int getFlag() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readInt(__io__address + 320); } else { return __io__block.readInt(__io__address + 300); } } /** * Set method for struct member 'flag'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Flags. </p> * @see #__DNA__FIELD__flag */ public void setFlag(int flag) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeInt(__io__address + 320, flag); } else { __io__block.writeInt(__io__address + 300, flag); } } /** * Get method for struct member 'mode'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Mode (Stroke/Fill/Both). </p> * @see #__DNA__FIELD__mode */ public int getMode() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readInt(__io__address + 324); } else { return __io__block.readInt(__io__address + 304); } } /** * Set method for struct member 'mode'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Mode (Stroke/Fill/Both). </p> * @see #__DNA__FIELD__mode */ public void setMode(int mode) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeInt(__io__address + 324, mode); } else { __io__block.writeInt(__io__address + 304, mode); } } /** * Get method for struct member 'factor'. * @see #__DNA__FIELD__factor */ public float getFactor() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readFloat(__io__address + 328); } else { return __io__block.readFloat(__io__address + 308); } } /** * Set method for struct member 'factor'. * @see #__DNA__FIELD__factor */ public void setFactor(float factor) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeFloat(__io__address + 328, factor); } else { __io__block.writeFloat(__io__address + 308, factor); } } /** * Get method for struct member 'radius'. * @see #__DNA__FIELD__radius */ public float getRadius() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readFloat(__io__address + 332); } else { return __io__block.readFloat(__io__address + 312); } } /** * Set method for struct member 'radius'. * @see #__DNA__FIELD__radius */ public void setRadius(float radius) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeFloat(__io__address + 332, radius); } else { __io__block.writeFloat(__io__address + 312, radius); } } /** * Get method for struct member 'rgb'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Simple Tint color. </p> * @see #__DNA__FIELD__rgb */ public CArrayFacade<Float> getRgb() throws IOException { Class<?>[] __dna__targetTypes = new Class[]{Float.class}; int[] __dna__dimensions = new int[]{ 3 }; if ((__io__pointersize == 8)) { return new CArrayFacade<Float>(__io__address + 336, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } else { return new CArrayFacade<Float>(__io__address + 316, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } } /** * Set method for struct member 'rgb'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Simple Tint color. </p> * @see #__DNA__FIELD__rgb */ public void setRgb(CArrayFacade<Float> rgb) throws IOException { long __dna__offset; if ((__io__pointersize == 8)) { __dna__offset = 336; } else { __dna__offset = 316; } if (__io__equals(rgb, __io__address + __dna__offset)) { return; } else if (__io__same__encoding(this, rgb)) { __io__native__copy(__io__block, __io__address + __dna__offset, rgb); } else { __io__generic__copy( getRgb(), rgb); } } /** * Get method for struct member 'type'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Type of Tint. </p> * @see #__DNA__FIELD__type */ public int getType() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readInt(__io__address + 348); } else { return __io__block.readInt(__io__address + 328); } } /** * Set method for struct member 'type'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Type of Tint. </p> * @see #__DNA__FIELD__type */ public void setType(int type) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeInt(__io__address + 348, type); } else { __io__block.writeInt(__io__address + 328, type); } } /** * Get method for struct member 'curve_intensity'. * @see #__DNA__FIELD__curve_intensity */ public CPointer<CurveMapping> getCurve_intensity() throws IOException { long __dna__targetAddress; if ((__io__pointersize == 8)) { __dna__targetAddress = __io__block.readLong(__io__address + 352); } else { __dna__targetAddress = __io__block.readLong(__io__address + 332); } Class<?>[] __dna__targetTypes = new Class[]{CurveMapping.class}; return new CPointer<CurveMapping>(__dna__targetAddress, __dna__targetTypes, __io__blockTable.getBlock(__dna__targetAddress, CurveMapping.__DNA__SDNA_INDEX), __io__blockTable); } /** * Set method for struct member 'curve_intensity'. * @see #__DNA__FIELD__curve_intensity */ public void setCurve_intensity(CPointer<CurveMapping> curve_intensity) throws IOException { long __address = ((curve_intensity == null) ? 0 : curve_intensity.getAddress()); if ((__io__pointersize == 8)) { __io__block.writeLong(__io__address + 352, __address); } else { __io__block.writeLong(__io__address + 332, __address); } } /** * Get method for struct member 'colorband'. * @see #__DNA__FIELD__colorband */ public CPointer<ColorBand> getColorband() throws IOException { long __dna__targetAddress; if ((__io__pointersize == 8)) { __dna__targetAddress = __io__block.readLong(__io__address + 360); } else { __dna__targetAddress = __io__block.readLong(__io__address + 336); } Class<?>[] __dna__targetTypes = new Class[]{ColorBand.class}; return new CPointer<ColorBand>(__dna__targetAddress, __dna__targetTypes, __io__blockTable.getBlock(__dna__targetAddress, ColorBand.__DNA__SDNA_INDEX), __io__blockTable); } /** * Set method for struct member 'colorband'. * @see #__DNA__FIELD__colorband */ public void setColorband(CPointer<ColorBand> colorband) throws IOException { long __address = ((colorband == null) ? 0 : colorband.getAddress()); if ((__io__pointersize == 8)) { __io__block.writeLong(__io__address + 360, __address); } else { __io__block.writeLong(__io__address + 336, __address); } } /** * Instantiates a pointer on this instance. */ public CPointer<TintGpencilModifierData> __io__addressof() { return new CPointer<TintGpencilModifierData>(__io__address, new Class[]{TintGpencilModifierData.class}, __io__block, __io__blockTable); } }
9242ccdc1e2035ded5dd1edc570781f2b6f504f9
18,071
java
Java
openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryImpl.java
danielemariano/openJPA-test
e2c0b29f9f93d2373a843547dac316c6bea6b276
[ "Apache-2.0" ]
104
2015-01-31T01:11:05.000Z
2022-03-20T05:28:58.000Z
openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryImpl.java
danielemariano/openJPA-test
e2c0b29f9f93d2373a843547dac316c6bea6b276
[ "Apache-2.0" ]
56
2016-09-30T14:04:31.000Z
2022-02-21T11:23:53.000Z
openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryImpl.java
danielemariano/openJPA-test
e2c0b29f9f93d2373a843547dac316c6bea6b276
[ "Apache-2.0" ]
127
2015-01-11T14:18:46.000Z
2022-03-23T13:46:58.000Z
35.713439
116
0.645177
1,002,417
/* * 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.openjpa.persistence; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.persistence.Cache; import javax.persistence.EntityGraph; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnitUtil; import javax.persistence.Query; import javax.persistence.SynchronizationType; import javax.persistence.spi.LoadState; import org.apache.openjpa.conf.OpenJPAConfiguration; import org.apache.openjpa.kernel.AutoDetach; import org.apache.openjpa.kernel.Broker; import org.apache.openjpa.kernel.BrokerFactory; import org.apache.openjpa.kernel.DelegatingBrokerFactory; import org.apache.openjpa.kernel.DelegatingFetchConfiguration; import org.apache.openjpa.kernel.FetchConfiguration; import org.apache.openjpa.lib.conf.Configurations; import org.apache.openjpa.lib.conf.Value; import org.apache.openjpa.lib.log.Log; import org.apache.openjpa.lib.util.Closeable; import org.apache.openjpa.lib.util.Localizer; import org.apache.openjpa.lib.util.StringUtil; import org.apache.openjpa.meta.MetaDataModes; import org.apache.openjpa.meta.MetaDataRepository; import org.apache.openjpa.meta.QueryMetaData; import org.apache.openjpa.persistence.criteria.CriteriaBuilderImpl; import org.apache.openjpa.persistence.criteria.OpenJPACriteriaBuilder; import org.apache.openjpa.persistence.meta.MetamodelImpl; import org.apache.openjpa.persistence.query.OpenJPAQueryBuilder; import org.apache.openjpa.persistence.query.QueryBuilderImpl; /** * Implementation of {@link EntityManagerFactory} that acts as a * facade to a {@link BrokerFactory}. * * @author Marc Prud'hommeaux */ public class EntityManagerFactoryImpl implements OpenJPAEntityManagerFactory, OpenJPAEntityManagerFactorySPI, Closeable, PersistenceUnitUtil { private static final long serialVersionUID = 1L; private static final Localizer _loc = Localizer.forPackage (EntityManagerFactoryImpl.class); private DelegatingBrokerFactory _factory = null; private transient Constructor<FetchPlan> _plan = null; private transient StoreCache _cache = null; private transient QueryResultCache _queryCache = null; private transient MetamodelImpl _metaModel; private transient Map<String, Object> properties; private transient Map<String, Object> emEmptyPropsProperties; /** * Default constructor provided for auto-instantiation. */ public EntityManagerFactoryImpl() { } /** * Supply delegate on construction. */ public EntityManagerFactoryImpl(BrokerFactory factory) { setBrokerFactory(factory); } /** * Delegate. */ public BrokerFactory getBrokerFactory() { return _factory.getDelegate(); } /** * Delegate must be provided before use. */ public void setBrokerFactory(BrokerFactory factory) { _factory = new DelegatingBrokerFactory(factory, PersistenceExceptions.TRANSLATOR); } @Override public OpenJPAConfiguration getConfiguration() { return _factory.getConfiguration(); } @Override public Map<String,Object> getProperties() { if (properties == null) { Map<String,Object> props = _factory.getProperties(); // convert to user readable values if (emEmptyPropsProperties != null) { props.putAll(emEmptyPropsProperties); } else { props.putAll(doCreateEM(SynchronizationType.SYNCHRONIZED, null, true).getProperties()); } // no need to sync or volatile, worse case concurrent threads create 2 instances // we just want to avoid to do it after some "init" phase this.properties = props; } return properties; } @Override public Object putUserObject(Object key, Object val) { return _factory.putUserObject(key, val); } @Override public Object getUserObject(Object key) { return _factory.getUserObject(key); } @Override public StoreCache getStoreCache() { _factory.lock(); try { if (_cache == null) { OpenJPAConfiguration conf = _factory.getConfiguration(); _cache = new StoreCacheImpl(this, conf.getDataCacheManagerInstance().getSystemDataCache()); } return _cache; } finally { _factory.unlock(); } } @Override public StoreCache getStoreCache(String cacheName) { return new StoreCacheImpl(this, _factory.getConfiguration(). getDataCacheManagerInstance().getDataCache(cacheName, true)); } @Override public QueryResultCache getQueryResultCache() { _factory.lock(); try { if (_queryCache == null) _queryCache = new QueryResultCacheImpl(_factory. getConfiguration().getDataCacheManagerInstance(). getSystemQueryCache()); return _queryCache; } finally { _factory.unlock(); } } @Override public OpenJPAEntityManagerSPI createEntityManager() { return createEntityManager((Map) null); } @Override public OpenJPAEntityManagerSPI createEntityManager(SynchronizationType synchronizationType) { return createEntityManager(synchronizationType, null); } @Override public OpenJPAEntityManagerSPI createEntityManager(Map props) { return createEntityManager(SynchronizationType.SYNCHRONIZED, props); } /** * Creates and configures a entity manager with the given properties. * * The property keys in the given map can be either qualified or not. * * @return list of exceptions raised or empty list. */ @Override public OpenJPAEntityManagerSPI createEntityManager(SynchronizationType synchronizationType, Map props) { return doCreateEM(synchronizationType, props, false); } private OpenJPAEntityManagerSPI doCreateEM(SynchronizationType synchronizationType, Map props, boolean byPassSynchronizeMappings) { if (synchronizationType == null) { throw new NullPointerException("SynchronizationType must not be null"); } if (SynchronizationType.UNSYNCHRONIZED.equals(synchronizationType)) { throw new UnsupportedOperationException("TODO - implement JPA 2.1 feature"); } if (props == null) { props = Collections.EMPTY_MAP; } else if (!props.isEmpty()) { props = new HashMap(props); } boolean canCacheGetProperties = props.isEmpty(); // nominal case OpenJPAConfiguration conf = getConfiguration(); Log log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); String user = (String) Configurations.removeProperty("ConnectionUserName", props); if (user == null) user = conf.getConnectionUserName(); String pass = (String) Configurations.removeProperty("ConnectionPassword", props); if (pass == null) pass = conf.getConnectionPassword(); String str = (String) Configurations.removeProperty("TransactionMode", props); boolean managed; if (str == null) managed = conf.isTransactionModeManaged(); else { Value val = conf.getValue("TransactionMode"); managed = Boolean.parseBoolean(val.unalias(str)); } Object obj = Configurations.removeProperty("ConnectionRetainMode", props); int retainMode; if (obj instanceof Number) { retainMode = ((Number) obj).intValue(); } else if (obj == null) { retainMode = conf.getConnectionRetainModeConstant(); } else { Value val = conf.getValue("ConnectionRetainMode"); try { retainMode = Integer.parseInt(val.unalias((String) obj)); } catch (Exception e) { throw new ArgumentException(_loc.get("bad-em-prop", "openjpa.ConnectionRetainMode", obj), new Throwable[]{ e }, obj, true); } } // javax.persistence.jtaDataSource and openjpa.ConnectionFactory name are equivalent. // prefer javax.persistence for now. String cfName = (String) Configurations.removeProperty("jtaDataSource", props); if(cfName == null) { cfName = (String) Configurations.removeProperty("ConnectionFactoryName", props); } String cf2Name = (String) Configurations.removeProperty("nonJtaDataSource", props); if(cf2Name == null) { cf2Name = (String) Configurations.removeProperty("ConnectionFactory2Name", props); } if (log != null && log.isTraceEnabled()) { if(StringUtil.isNotEmpty(cfName)) { log.trace("Found ConnectionFactoryName from props: " + cfName); } if(StringUtil.isNotEmpty(cf2Name)) { log.trace("Found ConnectionFactory2Name from props: " + cf2Name); } } validateCfNameProps(conf, cfName, cf2Name); Broker broker = byPassSynchronizeMappings ? conf.newBrokerInstance(user, pass) : _factory.newBroker(user, pass, managed, retainMode, false, cfName, cf2Name); // add autodetach for close and rollback conditions to the configuration broker.setAutoDetach(AutoDetach.DETACH_CLOSE, true); broker.setAutoDetach(AutoDetach.DETACH_ROLLBACK, true); broker.setDetachedNew(false); OpenJPAEntityManagerSPI em = newEntityManagerImpl(broker); // allow setting of other bean properties of EM if (!props.isEmpty()) { Set<Map.Entry> entrySet = props.entrySet(); for (Map.Entry entry : entrySet) { em.setProperty(entry.getKey().toString(), entry.getValue()); } } if (canCacheGetProperties) { if (emEmptyPropsProperties == null) { emEmptyPropsProperties = em.getProperties(); } else if (EntityManagerImpl.class.isInstance(em)) { EntityManagerImpl.class.cast(em).setProperties(emEmptyPropsProperties); } } if (log != null && log.isTraceEnabled()) { log.trace(this + " created EntityManager " + em + "."); } return em; } /** * Create a new entity manager around the given broker. */ protected EntityManagerImpl newEntityManagerImpl(Broker broker) { return new EntityManagerImpl(this, broker); } @Override public void addLifecycleListener(Object listener, Class... classes) { _factory.addLifecycleListener(listener, classes); } @Override public void removeLifecycleListener(Object listener) { _factory.removeLifecycleListener(listener); } @Override public void addTransactionListener(Object listener) { _factory.addTransactionListener(listener); } @Override public void removeTransactionListener(Object listener) { _factory.removeTransactionListener(listener); } @Override public void close() { Log log = _factory.getConfiguration().getLog(OpenJPAConfiguration.LOG_RUNTIME); if (log.isTraceEnabled()) { log.trace(this + ".close() invoked."); } _factory.close(); } @Override public boolean isOpen() { return !_factory.isClosed(); } @Override public int hashCode() { return (_factory == null) ? 0 : _factory.hashCode(); } @Override public boolean equals(Object other) { if (other == this) return true; if ((other == null) || (other.getClass() != this.getClass())) return false; if (_factory == null) return false; return _factory.equals(((EntityManagerFactoryImpl) other)._factory); } /** * Create a store-specific facade for the given fetch configuration. * If no facade class exists, we use the default {@link FetchPlan}. */ FetchPlan toFetchPlan(Broker broker, FetchConfiguration fetch) { if (fetch == null) return null; if (fetch instanceof DelegatingFetchConfiguration) fetch = ((DelegatingFetchConfiguration) fetch). getInnermostDelegate(); try { if (_plan == null) { Class storeType = (broker == null) ? null : broker. getStoreManager().getInnermostDelegate().getClass(); Class cls = _factory.getConfiguration(). getStoreFacadeTypeRegistry(). getImplementation(FetchPlan.class, storeType, FetchPlanImpl.class); _plan = cls.getConstructor(FetchConfiguration.class); } return _plan.newInstance(fetch); } catch (InvocationTargetException ite) { throw PersistenceExceptions.toPersistenceException (ite.getTargetException()); } catch (Exception e) { throw PersistenceExceptions.toPersistenceException(e); } } @Override public Cache getCache() { _factory.assertOpen(); return getStoreCache(); } @Override public OpenJPACriteriaBuilder getCriteriaBuilder() { return new CriteriaBuilderImpl().setMetaModel(getMetamodel()); } @Override public OpenJPAQueryBuilder getDynamicQueryBuilder() { return new QueryBuilderImpl(this); } @Override public Set<String> getSupportedProperties() { return _factory.getSupportedProperties(); } @Override public MetamodelImpl getMetamodel() { if (_metaModel == null) { MetaDataRepository mdr = getConfiguration().getMetaDataRepositoryInstance(); mdr.setValidate(MetaDataRepository.VALIDATE_RUNTIME, true); mdr.setResolve(MetaDataModes.MODE_MAPPING_INIT, true); _metaModel = new MetamodelImpl(mdr); } return _metaModel; } @Override public PersistenceUnitUtil getPersistenceUnitUtil() { return this; } @Override public void addNamedQuery(String name, Query query) { org.apache.openjpa.kernel.Query kernelQuery = ((QueryImpl<?>)query).getDelegate(); MetaDataRepository metaDataRepositoryInstance = _factory.getConfiguration().getMetaDataRepositoryInstance(); QueryMetaData metaData = metaDataRepositoryInstance.newQueryMetaData(null, null); metaData.setFrom(kernelQuery); metaDataRepositoryInstance.addQueryMetaData(metaData); } @Override public <T> T unwrap(Class<T> cls) { if (cls.isInstance(this)) { return cls.cast(this); } throw new javax.persistence.PersistenceException(this + " is not a " + cls); } @Override public <T> void addNamedEntityGraph(String graphName, EntityGraph<T> entityGraph) { throw new UnsupportedOperationException("JPA 2.1"); } /** * Get the identifier for the specified entity. If not managed by any * of the em's in this PU or not persistence capable, return null. */ @Override public Object getIdentifier(Object entity) { return OpenJPAPersistenceUtil.getIdentifier(this, entity); } @Override public boolean isLoaded(Object entity) { return isLoaded(entity, null); } @Override public boolean isLoaded(Object entity, String attribute) { if (entity == null) { return false; } return (OpenJPAPersistenceUtil.isManagedBy(this, entity) && (OpenJPAPersistenceUtil.isLoaded(entity, attribute) == LoadState.LOADED)); } private void validateCfNameProps(OpenJPAConfiguration conf, String cfName, String cf2Name) { if (StringUtil.isNotEmpty(cfName) || StringUtil.isNotEmpty(cf2Name)) { if (conf.getDataCache() != "false" && conf.getDataCache() != null) { throw new ArgumentException(_loc.get("invalid-cfname-prop", new Object[] { "openjpa.DataCache (L2 Cache)", cfName, cf2Name }), null, null, true); } if (conf.getQueryCache() != "false" && conf.getQueryCache() != null) { throw new ArgumentException(_loc.get("invalid-cfname-prop", new Object[] { "openjpa.QueryCache", cfName, cf2Name }), null, null, true); } Object syncMap = conf.toProperties(false).get("openjpa.jdbc.SynchronizeMappings"); if(syncMap != null) { throw new ArgumentException(_loc.get("invalid-cfname-prop", new Object[] { "openjpa.jdbc.SynchronizeMappings", cfName, cf2Name }), null, null, true); } } } }
9242ccfaff038f5bdc65919d1d35797bc3b2006a
1,169
java
Java
autodoc-webapp/model/src/main/java/com/autodoc/model/models/tasks/Task.java
xbreizh/Autodoc
4ed5f6a8b89d71442ffcb6f993b0fffc9a71c238
[ "Apache-2.0" ]
null
null
null
autodoc-webapp/model/src/main/java/com/autodoc/model/models/tasks/Task.java
xbreizh/Autodoc
4ed5f6a8b89d71442ffcb6f993b0fffc9a71c238
[ "Apache-2.0" ]
2
2019-09-25T08:35:10.000Z
2019-09-25T08:36:51.000Z
autodoc-webapp/model/src/main/java/com/autodoc/model/models/tasks/Task.java
xbreizh/Autodoc
4ed5f6a8b89d71442ffcb6f993b0fffc9a71c238
[ "Apache-2.0" ]
1
2020-04-01T16:34:17.000Z
2020-04-01T16:34:17.000Z
18.854839
72
0.599658
1,002,418
package com.autodoc.model.models.tasks; import lombok.Getter; import lombok.Setter; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotNull; @Getter @Setter public class Task { private int id; @NotNull private String name; private String description; @DecimalMin(value = "0.5", message = "estimatedTime cannot be null") private double estimatedTime; @NotNull private boolean template; public Task(String name, String description, double estimatedTime) { this.name = name; this.description = description; this.estimatedTime = estimatedTime; } public Task() { } public void setName(String name) { this.name = name.toUpperCase(); } public void setDescription(String description) { this.description = description.toUpperCase(); } @Override public String toString() { return "Task{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", estimatedTime=" + estimatedTime + '}'; } }
9242cde9514ea53a46850476fd0f8a29d61bca61
487
java
Java
src/main/java/org/sphinx/pool/PooledObjectFactoryException.java
bcowdery/sphinx-api-pool
873f23591b00dd392582fe77ed7191794958b2fe
[ "MIT" ]
6
2015-08-11T05:52:49.000Z
2020-10-20T03:11:20.000Z
src/main/java/org/sphinx/pool/PooledObjectFactoryException.java
bcowdery/sphinx-api-pool
873f23591b00dd392582fe77ed7191794958b2fe
[ "MIT" ]
null
null
null
src/main/java/org/sphinx/pool/PooledObjectFactoryException.java
bcowdery/sphinx-api-pool
873f23591b00dd392582fe77ed7191794958b2fe
[ "MIT" ]
null
null
null
24.35
85
0.724846
1,002,419
package org.sphinx.pool; /** * Exceptions thrown by the pooled object factory. Can be used to propagate errors up * to through pool for application handling. * * @author Brian Cowdery * @since 29-05-2015 */ public class PooledObjectFactoryException extends RuntimeException { public PooledObjectFactoryException(String message) { super(message); } public PooledObjectFactoryException(String message, Throwable cause) { super(message, cause); } }
9242d028e87135c2d1492ecf48498af15614c73f
1,447
java
Java
src/org/virtue/config/db/dbtabletype/DBTableType.java
itsgreco/Virtue865
36ce128a4433043cda82eda01c5720e4f1d0dddc
[ "MIT" ]
1
2020-09-06T19:10:20.000Z
2020-09-06T19:10:20.000Z
src/org/virtue/config/db/dbtabletype/DBTableType.java
itsgreco/Virtue865
36ce128a4433043cda82eda01c5720e4f1d0dddc
[ "MIT" ]
null
null
null
src/org/virtue/config/db/dbtabletype/DBTableType.java
itsgreco/Virtue865
36ce128a4433043cda82eda01c5720e4f1d0dddc
[ "MIT" ]
1
2019-07-19T21:39:17.000Z
2019-07-19T21:39:17.000Z
24.116667
86
0.651693
1,002,420
package org.virtue.config.db.dbtabletype; import java.nio.ByteBuffer; import org.virtue.cache.utility.ByteBufferUtils; import org.virtue.config.ConfigType; import org.virtue.config.db.DBUtils; import org.virtue.config.vartype.constants.ScriptVarType; public class DBTableType implements ConfigType { public Object[][] defaultValues; public ScriptVarType[][] columnTypes; public DBTableType (int id, DBTableTypeList list) { } @Override public void decode(ByteBuffer buffer) { for (;;) { int i_0_ = buffer.get() & 0xff; if (0 == i_0_) break; decode(buffer, i_0_); } } void decode(ByteBuffer buffer, int i) { if (i == 1) { int i_2_ = buffer.get() & 0xff; if (null == columnTypes) { columnTypes = new ScriptVarType[i_2_][]; } for (int i_3_ = buffer.get() & 0xff; 255 != i_3_; i_3_ = buffer.get() & 0xff) { int i_4_ = i_3_ & 0x7f; boolean bool = 0 != (i_3_ & 0x80); ScriptVarType[] types = new ScriptVarType[buffer.get() & 0xff]; for (int i_5_ = 0; i_5_ < types.length; i_5_++) { types[i_5_] = ScriptVarType.getById(ByteBufferUtils.getUnsignedSmartInt(buffer)); } columnTypes[i_4_] = types; if (bool) { if (null == defaultValues) { defaultValues = new Object[columnTypes.length][]; } defaultValues[i_4_] = DBUtils.getDataValues(buffer, types); } } } } public void postDecode() { /* empty */ } DBTableType() { /* empty */ } }
9242d144309a595d65606214fe26b78f34d0e126
1,842
java
Java
src/main/java/com/leetcode/tree/medium/PathSumII_113.java
Nalhin/Leetcode
1ab17f073c35f6d5babf6d0dd2a89dd248e599c8
[ "MIT" ]
1
2021-01-10T10:56:31.000Z
2021-01-10T10:56:31.000Z
src/main/java/com/leetcode/tree/medium/PathSumII_113.java
Nalhin/Leetcode
1ab17f073c35f6d5babf6d0dd2a89dd248e599c8
[ "MIT" ]
null
null
null
src/main/java/com/leetcode/tree/medium/PathSumII_113.java
Nalhin/Leetcode
1ab17f073c35f6d5babf6d0dd2a89dd248e599c8
[ "MIT" ]
1
2020-12-19T11:52:20.000Z
2020-12-19T11:52:20.000Z
24.891892
99
0.629207
1,002,421
package com.leetcode.tree.medium; // Given a binary tree and a sum, find all root-to-leaf paths where each path's s // um equals the given sum. // // Note: A leaf is a node with no children. // // Example: // // Given the below binary tree and sum = 22, // // // 5 // / \ // 4 8 // / / \ // 11 13 4 // / \ / \ // 7 2 5 1 // // // Return: // // // [ // [5,4,11,2], // [5,8,4,5] // ] // // Related Topics Tree Depth-first Search // 👍 2387 👎 85 // leetcode submit region begin(Prohibit modification and deletion) import com.leetcode.utils.BinaryTree.TreeNode; import java.util.ArrayList; import java.util.List; /** * Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode * right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, * TreeNode right) { this.val = val; this.left = left; this.right = right; } } */ /* O(n^2) Runtime: 1 ms, faster than 100.00% of Java online submissions for Path Sum II. O(n^2) Memory Usage: 39.5 MB, less than 57.68% of Java online submissions for Path Sum II. */ public class PathSumII_113 { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> result = new ArrayList<>(); pathSumDfs(root, sum, new ArrayList<>(), result); return result; } private void pathSumDfs(TreeNode root, int sum, List<Integer> path, List<List<Integer>> result) { if (root == null) { return; } path.add(root.val); if (root.left == null && root.right == null && sum == root.val) { result.add(new ArrayList<>(path)); } pathSumDfs(root.left, sum - root.val, path, result); pathSumDfs(root.right, sum - root.val, path, result); path.remove(path.size() - 1); } } // leetcode submit region end(Prohibit modification and deletion)
9242d17c02156580e3b7ef3fdee2e47ad23e2e79
816
java
Java
src/main/java/application/service/ITrainerService.java
A-DNAN/cs-oop-javafx
ae951408561c63963ed7d7ec83f9bb30da5aa9c4
[ "Apache-2.0" ]
null
null
null
src/main/java/application/service/ITrainerService.java
A-DNAN/cs-oop-javafx
ae951408561c63963ed7d7ec83f9bb30da5aa9c4
[ "Apache-2.0" ]
null
null
null
src/main/java/application/service/ITrainerService.java
A-DNAN/cs-oop-javafx
ae951408561c63963ed7d7ec83f9bb30da5aa9c4
[ "Apache-2.0" ]
null
null
null
29.214286
88
0.768949
1,002,422
/** * @Author ADNAN <[email protected]> */ package application.service; import application.bean.Customer; import application.bean.Diet; import application.bean.ExercicePlan; import application.bean.Trainer; import javafx.collections.ObservableList; /** * @Author ADNAN <[email protected]> * */ public interface ITrainerService { public void addTrainer(Trainer trainer); public void updateTrainer(Trainer trainer); public ObservableList<Trainer> findAll(); public ObservableList<Diet> findAllDietsOfATrainer(Integer trainerId); public ObservableList<ExercicePlan> findAllExercicePlansOfATrainer(Integer trainerId); //list of subscription - > list of membership - > list of customers public ObservableList<Customer> findAllMyCustomersBySubscription(Integer trainerId); }
9242d2139c1b827a8c7063010899acbe7551ac4b
518
java
Java
Network/src/main/java/com/liyafeng/network/response/ResponseEntity.java
pop1234o/BestPracticeApp
74a7d979d51b7843bf8bde0ab5c5a04fd4f577a9
[ "Apache-2.0" ]
50
2017-11-23T20:57:19.000Z
2021-09-27T12:29:19.000Z
Network/src/main/java/com/liyafeng/network/response/ResponseEntity.java
pop1234o/CustomViewApp
14cf681b5172904b0d127d3707f93c24b518a715
[ "Apache-2.0" ]
1
2018-07-14T09:40:42.000Z
2018-07-18T04:02:01.000Z
Network/src/main/java/com/liyafeng/network/response/ResponseEntity.java
pop1234o/CustomViewApp
14cf681b5172904b0d127d3707f93c24b518a715
[ "Apache-2.0" ]
9
2017-11-23T20:57:34.000Z
2021-03-17T08:41:33.000Z
15.235294
38
0.559846
1,002,423
package com.liyafeng.network.response; public class ResponseEntity<T> { private int state; public int getState() { return state; } public void setState(int state) { this.state = state; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } private String msg; private T data; }
9242d21d7cee050e57ea94ead966464586d5ab04
500
java
Java
app/src/main/java/com/vipul/bit_hotels/activity/BaseActivity.java
rohan-rodrigues/MedX
44d621978333f82c388a5380d831a48ddb8fa8b6
[ "MIT" ]
52
2017-01-06T05:55:35.000Z
2022-03-14T09:13:34.000Z
app/src/main/java/com/vipul/bit_hotels/activity/BaseActivity.java
dheerajkotwani/betterHotels
f37c6a12494da2b1d09359c2270bb6c098379304
[ "MIT" ]
null
null
null
app/src/main/java/com/vipul/bit_hotels/activity/BaseActivity.java
dheerajkotwani/betterHotels
f37c6a12494da2b1d09359c2270bb6c098379304
[ "MIT" ]
35
2017-01-04T08:43:45.000Z
2021-06-25T06:30:14.000Z
25
73
0.79
1,002,424
package com.vipul.bit_hotels.activity; import android.content.Context; import android.support.design.widget.AppBarFlingFixBehavior; import android.support.v7.app.AppCompatActivity; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; /** * Created by vipulkumar on 17/08/16. */ public class BaseActivity extends AppCompatActivity { @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } }
9242d33ebf447e8e6ef64c0a23e2c02a6346d09b
2,426
java
Java
src/main/java/CourseSession.java
luckyzhangzhen/1123test
0b1e0ff4e3b1f1589f4eb749909aa70f384c4efd
[ "Apache-2.0" ]
null
null
null
src/main/java/CourseSession.java
luckyzhangzhen/1123test
0b1e0ff4e3b1f1589f4eb749909aa70f384c4efd
[ "Apache-2.0" ]
null
null
null
src/main/java/CourseSession.java
luckyzhangzhen/1123test
0b1e0ff4e3b1f1589f4eb749909aa70f384c4efd
[ "Apache-2.0" ]
null
null
null
28.209302
86
0.639736
1,002,425
import java.util.*; import java.lang.StringBuilder; public class CourseSession { private String department; private String number; // private int numberOfStudents=0; static int count; private ArrayList<Student> students=new ArrayList<Student>(); private Date startDate; public static final String NEWLINE=System.getProperty("line.separator"); public static final String ROSTER_REPORT_HEADER="Student"+NEWLINE+"-----"+NEWLINE; public static final String ROSTER_REPORT_FOOTER=NEWLINE+"# students ="; public CourseSession(String department,String number,Date startDate){ this.department=department; this.number=number; this.startDate=startDate; CourseSession.count=CourseSession.count+1; CourseSession.incrementCount(); } /* 计数类方法 */ private static void incrementCount(){ count=count++; } public String getDepartment(){ return department; } public String getNumber(){ return number; } public int getNumberOfStudents(){ return students.size(); } public void enroll(Student student){ // numberOfStudents+=1; students.add(student); } public ArrayList<Student> getAllStudents(){ return students; } public Student get(int index){ return students.get(index); } public Date getEndDate(){ GregorianCalendar calendar=new GregorianCalendar(); calendar.setTime(startDate); int numberOfDays=16*7-3; calendar.add(Calendar.DAY_OF_YEAR,numberOfDays); Date endDate=calendar.getTime(); return endDate; } public String getRosterReport(){ StringBuilder buffer =new StringBuilder(); buffer.append(ROSTER_REPORT_HEADER); // Student student=students.get(0); // buffer.append(student.getName()); // buffer.append(NEWLINE); // // student=students.get(1); // buffer.append(student.getName()); // buffer.append(NEWLINE); // 将集合students的每一个对象赋值给Student类型引用,引用的名称为student,执行循环体 for (Student student:students){ buffer.append(student.getName()); buffer.append(NEWLINE); } // for (int i=0;i<students.size();i++){ // students[i] // } buffer.append(ROSTER_REPORT_FOOTER+students.size()+NEWLINE); return buffer.toString(); } }
9242d421b0946a4c0941a4b118ec357f185e0724
7,172
java
Java
kernel/impl/fabric3-fabric/src/main/java/org/fabric3/fabric/node/ServiceResolverImpl.java
chrisphe/fabric3-core
3a29d2cb19fcce33678e3f81f3f7c09271ca7b84
[ "Apache-2.0" ]
null
null
null
kernel/impl/fabric3-fabric/src/main/java/org/fabric3/fabric/node/ServiceResolverImpl.java
chrisphe/fabric3-core
3a29d2cb19fcce33678e3f81f3f7c09271ca7b84
[ "Apache-2.0" ]
null
null
null
kernel/impl/fabric3-fabric/src/main/java/org/fabric3/fabric/node/ServiceResolverImpl.java
chrisphe/fabric3-core
3a29d2cb19fcce33678e3f81f3f7c09271ca7b84
[ "Apache-2.0" ]
null
null
null
46.270968
135
0.748606
1,002,426
/* * Fabric3 * Copyright (c) 2009-2015 Metaform Systems * * 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.fabric3.fabric.node; import javax.xml.namespace.QName; import java.net.URI; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.fabric3.api.host.Fabric3Exception; import org.fabric3.api.host.HostNamespaces; import org.fabric3.api.host.Names; import org.fabric3.api.model.type.component.Binding; import org.fabric3.api.model.type.component.Component; import org.fabric3.api.model.type.component.ComponentType; import org.fabric3.api.model.type.component.Composite; import org.fabric3.api.model.type.component.Multiplicity; import org.fabric3.api.model.type.component.Reference; import org.fabric3.api.node.NotFoundException; import org.fabric3.fabric.container.builder.Connector; import org.fabric3.fabric.domain.LogicalComponentManager; import org.fabric3.fabric.domain.generator.wire.WireGenerator; import org.fabric3.fabric.domain.instantiator.wire.AutowireResolver; import org.fabric3.fabric.node.nonmanaged.NonManagedImplementation; import org.fabric3.fabric.node.nonmanaged.NonManagedWireSource; import org.fabric3.spi.classloader.ClassLoaderRegistry; import org.fabric3.spi.model.instance.LogicalBinding; import org.fabric3.spi.model.instance.LogicalComponent; import org.fabric3.spi.model.instance.LogicalCompositeComponent; import org.fabric3.spi.model.instance.LogicalReference; import org.fabric3.spi.model.instance.LogicalService; import org.fabric3.spi.model.instance.LogicalWire; import org.fabric3.spi.model.physical.PhysicalWire; import org.fabric3.spi.model.type.java.JavaServiceContract; /** * */ public class ServiceResolverImpl implements ServiceResolver { private static final URI SYNTHETIC_CONTRIBUTION = URI.create("Synthetic"); private Introspector introspector; private LogicalComponentManager lcm; private AutowireResolver autowireResolver; private WireGenerator wireGenerator; private Connector connector; private ClassLoaderRegistry classLoaderRegistry; private AtomicInteger idCounter = new AtomicInteger(); public ServiceResolverImpl(@org.oasisopen.sca.annotation.Reference Introspector introspector, @org.oasisopen.sca.annotation.Reference(name = "lcm") LogicalComponentManager lcm, @org.oasisopen.sca.annotation.Reference AutowireResolver autowireResolver, @org.oasisopen.sca.annotation.Reference WireGenerator wireGenerator, @org.oasisopen.sca.annotation.Reference Connector connector, @org.oasisopen.sca.annotation.Reference ClassLoaderRegistry classLoaderRegistry) { this.introspector = introspector; this.lcm = lcm; this.autowireResolver = autowireResolver; this.wireGenerator = wireGenerator; this.connector = connector; this.classLoaderRegistry = classLoaderRegistry; } public <T> T resolve(Class<T> interfaze) throws Fabric3Exception { LogicalWire logicalWire = createWire(interfaze); PhysicalWire physicalWire = wireGenerator.generateWire(logicalWire); NonManagedWireSource source = (NonManagedWireSource) physicalWire.getSource(); URI uri = ContributionResolver.getContribution(interfaze); ClassLoader classLoader = classLoaderRegistry.getClassLoader(uri); physicalWire.getTarget().setClassLoader(classLoader); source.setClassLoader(classLoader); connector.connect(physicalWire); return interfaze.cast(source.getProxy()); } public <T> T resolve(Class<T> interfaze, Binding binding, Class<?> implClass) throws Fabric3Exception { LogicalReference logicalReference = createReference(interfaze); LogicalBinding<?> logicalBinding = new LogicalBinding<>(binding, logicalReference); logicalReference.addBinding(logicalBinding); PhysicalWire physicalWire = wireGenerator.generateReference(logicalBinding); NonManagedWireSource source = (NonManagedWireSource) physicalWire.getSource(); URI uri = ContributionResolver.getContribution(interfaze); ClassLoader classLoader = classLoaderRegistry.getClassLoader(uri); physicalWire.getTarget().setClassLoader(classLoader); source.setClassLoader(classLoader); connector.connect(physicalWire); return interfaze.cast(source.getProxy()); } private <T> LogicalWire createWire(Class<T> interfaze) throws Fabric3Exception { LogicalReference logicalReference = createReference(interfaze); LogicalCompositeComponent domainComponent = lcm.getDomainComposite(); List<LogicalService> services = autowireResolver.resolve(logicalReference, domainComponent); if (services.isEmpty()) { throw new NotFoundException("Service not found for type: " + interfaze.getName()); } LogicalService targetService = services.get(0); return new LogicalWire(domainComponent, logicalReference, targetService, SYNTHETIC_CONTRIBUTION); } private LogicalReference createReference(Class<?> interfaze) { LogicalCompositeComponent domainComponent = lcm.getDomainComposite(); int id = idCounter.getAndIncrement(); String name = "Synthetic" + id; URI componentUri = URI.create(domainComponent.getUri().toString() + "/" + name); URI referenceUri = URI.create(componentUri.toString() + "#reference"); QName qName = new QName(HostNamespaces.SYNTHESIZED, "SyntheticComposite" + id); Composite composite = new Composite(qName); Component<NonManagedImplementation> component = new Component<>(name); component.setParent(composite); component.setContributionUri(Names.HOST_CONTRIBUTION); NonManagedImplementation implementation = new NonManagedImplementation(); component.setImplementation(implementation); Reference<ComponentType> reference = new Reference<>("reference", Multiplicity.ONE_ONE); composite.add(reference); JavaServiceContract contract = introspector.introspect(interfaze); LogicalComponent<NonManagedImplementation> logicalComponent = new LogicalComponent<>(componentUri, component, domainComponent); reference.setServiceContract(contract); LogicalReference logicalReference = new LogicalReference(referenceUri, reference, logicalComponent); logicalReference.setServiceContract(contract); logicalComponent.addReference(logicalReference); return logicalReference; } }
9242d4301379a52b7115d8903b74a655381cca77
1,623
java
Java
src/main/java/com/services/ListService.java
AUraihQA/ToDoWebApplication
e4488e8f55b6d81740b6ba55a1f11f57b42a963e
[ "MIT" ]
null
null
null
src/main/java/com/services/ListService.java
AUraihQA/ToDoWebApplication
e4488e8f55b6d81740b6ba55a1f11f57b42a963e
[ "MIT" ]
null
null
null
src/main/java/com/services/ListService.java
AUraihQA/ToDoWebApplication
e4488e8f55b6d81740b6ba55a1f11f57b42a963e
[ "MIT" ]
null
null
null
24.223881
94
0.752927
1,002,427
package com.services; import java.util.List; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service; import com.persistence.domain.ListDomain; import com.persistence.dtos.ListDTO; import com.persistence.repos.ListRepo; import com.utils.MyBeanUtils; @Service public class ListService { private ListRepo repo; private ModelMapper mapper; @Autowired public ListService(ListRepo repo, ModelMapper mapper) { super(); this.repo = repo; this.mapper = mapper; } private ListDTO mapToDTO(ListDomain model) { return this.mapper.map(model, ListDTO.class); } public ListDTO create(ListDomain list) { return this.mapToDTO(this.repo.save(list)); } public List<ListDTO> readAll() { List<ListDomain> dbList = this.repo.findAll(); List<ListDTO> resultList = dbList.stream().map(this::mapToDTO).collect(Collectors.toList()); return resultList; } public ListDTO readOne(Long id) { return mapToDTO(this.repo.findById(id).orElseThrow()); } public ListDTO update(Long id, ListDomain newDetails) { ListDomain updatedList = this.repo.findById(id).orElseThrow(); MyBeanUtils.mergeNotNull(newDetails, updatedList); return this.mapToDTO(this.repo.save(updatedList)); } public boolean delete(Long id) { try { this.repo.deleteById(id); boolean flag = !this.repo.existsById(id); return flag; } catch (EmptyResultDataAccessException e) { e.printStackTrace(); return false; } } }
9242d4493c1a8683e12ecb966072f1896ddee71b
2,616
java
Java
example/src/test/java/org/brekka/stillingar/example/PollingReloadTest.java
brekka/stillingar
24171c40874760fa79b4358dbc2559a578a2247c
[ "Apache-2.0" ]
null
null
null
example/src/test/java/org/brekka/stillingar/example/PollingReloadTest.java
brekka/stillingar
24171c40874760fa79b4358dbc2559a578a2247c
[ "Apache-2.0" ]
null
null
null
example/src/test/java/org/brekka/stillingar/example/PollingReloadTest.java
brekka/stillingar
24171c40874760fa79b4358dbc2559a578a2247c
[ "Apache-2.0" ]
2
2016-01-07T10:59:30.000Z
2019-04-23T02:46:20.000Z
34.421053
80
0.737385
1,002,428
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.brekka.stillingar.example; import static org.junit.Assert.assertEquals; import org.brekka.stillingar.example.support.MessageOfTheDay; import org.brekka.stillingar.example.support.TestSupport; import org.brekka.xml.stillingar.example.v1.ConfigurationDocument; import org.brekka.xml.stillingar.example.v1.ConfigurationDocument.Configuration; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; /** * Verify that the polling mechanism for reloading works. * * @author Andrew Taylor ([email protected]) */ @ContextConfiguration @DirtiesContext public class PollingReloadTest extends AbstractJUnit4SpringContextTests { @Autowired private MessageOfTheDay messageOfTheDay; @BeforeClass public static void setOverrideProperty() { // Simulate JDK < 7 System.setProperty("stillingar.reload-watcher.disabled", "true"); writeConfig("Reload check"); } @AfterClass public static void unSetProperty() { System.setProperty("stillingar.reload-watcher.disabled", "false"); } @Test public void testPolling() throws Exception { assertEquals("Reload check", messageOfTheDay.getMessage()); Thread.sleep(2000); for (int i = 0; i < 3; i++) { String msg = "Message has been updated " + i; writeConfig(msg); Thread.sleep(3000); assertEquals(msg, messageOfTheDay.getMessage()); } } private static void writeConfig(String message) { ConfigurationDocument doc = ConfigurationDocument.Factory.newInstance(); Configuration newConfiguration = doc.addNewConfiguration(); newConfiguration.setMOTD(message); TestSupport.write(doc); } }
9242d49bac597ce9b8847561ee80d9640ecbe351
1,499
java
Java
recyclo/src/main/java/br/ufes/informatica/recyclo/core/persistence/UsuarioDAOJPA.java
dwws-ufes/2020-Recyclo
fd0143037c6303cf2f265b8a620cfff9e87015eb
[ "MIT" ]
1
2021-12-03T14:44:47.000Z
2021-12-03T14:44:47.000Z
recyclo/src/main/java/br/ufes/informatica/recyclo/core/persistence/UsuarioDAOJPA.java
dwws-ufes/2020-Recyclo
fd0143037c6303cf2f265b8a620cfff9e87015eb
[ "MIT" ]
null
null
null
recyclo/src/main/java/br/ufes/informatica/recyclo/core/persistence/UsuarioDAOJPA.java
dwws-ufes/2020-Recyclo
fd0143037c6303cf2f265b8a620cfff9e87015eb
[ "MIT" ]
1
2021-02-28T11:27:43.000Z
2021-02-28T11:27:43.000Z
34.068182
86
0.751835
1,002,429
package br.ufes.informatica.recyclo.core.persistence; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import br.ufes.inf.nemo.jbutler.ejb.persistence.BaseJPADAO; import br.ufes.informatica.recyclo.core.domain.Usuario; /** TODO: generated by FrameWeb. Should be documented. */ @Stateless public class UsuarioDAOJPA extends BaseJPADAO<Usuario> implements UsuarioDAO { /** Serialization id (using default value, change if necessary). */ private static final long serialVersionUID = 1L; /** TODO: generated by FrameWeb. Should be documented. */ @PersistenceContext private EntityManager entityManager; /** TODO: generated by FrameWeb. Should be documented. */ @Override protected EntityManager getEntityManager() { return entityManager; } /** TODO: generated by FrameWeb. Should be documented. */ @Override public Usuario efetuarLogin(Usuario usuario) { String jpql = "select u from Usuario u where u.email = :email and u.senha = :senha"; return entityManager.createQuery(jpql, Usuario.class) .setParameter("email", usuario.getEmail()) .setParameter("senha", usuario.getSenha()) .getSingleResult(); } public int verificaEmailRegistrado(Usuario usuario) { String jpql = "select u from Usuario u where u.email = :email"; int quantidade = entityManager.createQuery(jpql, Usuario.class) .setParameter("email", usuario.getEmail()) .getResultList().size(); return quantidade; } }
9242d4f3e08fcbe5796bdbff82f4d36a4a37a1ef
2,293
java
Java
android/src/main/java/com/showmerotatosalads/alarmclock/AlarmclockPlugin.java
tinhajj/alarmclock
fcf209e06434a6182eb696b5616547c65da46561
[ "MIT" ]
7
2020-02-17T23:13:13.000Z
2021-03-08T05:05:34.000Z
android/src/main/java/com/showmerotatosalads/alarmclock/AlarmclockPlugin.java
tinhajj/alarmclock
fcf209e06434a6182eb696b5616547c65da46561
[ "MIT" ]
null
null
null
android/src/main/java/com/showmerotatosalads/alarmclock/AlarmclockPlugin.java
tinhajj/alarmclock
fcf209e06434a6182eb696b5616547c65da46561
[ "MIT" ]
1
2020-12-15T23:07:24.000Z
2020-12-15T23:07:24.000Z
29.397436
115
0.716529
1,002,430
package com.showmerotatosalads.alarmclock; import android.app.Activity; import android.content.Intent; import android.provider.AlarmClock; import android.content.Context; import org.json.JSONArray; import io.flutter.plugin.common.JSONMethodCodec; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.PluginRegistry.Registrar; /** AlarmclockPlugin */ public class AlarmclockPlugin implements MethodCallHandler { private Registrar mRegistrar; private AlarmclockPlugin(Registrar registrar) { this.mRegistrar = registrar; } /** * Plugin registration. */ public static void registerWith(Registrar registrar) { final MethodChannel channel = new MethodChannel(registrar.messenger(), "alarmclock", JSONMethodCodec.INSTANCE); channel.setMethodCallHandler(new AlarmclockPlugin(registrar)); } @Override public void onMethodCall(MethodCall call, Result result) { if (call.method.equals("getPlatformVersion")) { result.success("Android " + android.os.Build.VERSION.RELEASE); } else if (call.method.equals("setAlarm")) { boolean ok = startAlarmClockActivity(call); if (ok) { result.success(true); } else { result.success(false); } } else { result.notImplemented(); } } private Context getActiveContext() { return (mRegistrar.activity() != null) ? mRegistrar.activity() : mRegistrar.context(); } public boolean startAlarmClockActivity(MethodCall call) { try { Context context = getActiveContext(); Intent i = new Intent(AlarmClock.ACTION_SET_ALARM); JSONArray args = (JSONArray) call.arguments; boolean skipui = args.getBoolean(0); Integer hour = args.getInt(1); Integer minute = args.getInt(2); String message = args.getString(3); i.putExtra(AlarmClock.EXTRA_SKIP_UI, skipui); i.putExtra(AlarmClock.EXTRA_HOUR, hour); i.putExtra(AlarmClock.EXTRA_MINUTES, minute); i.putExtra(AlarmClock.EXTRA_MESSAGE, message); context.startActivity(i); } catch (Exception e) { return false; } return true; } }
9242d67e276515d8ab1dcf3c397658dce17fbaed
531
java
Java
src/main/java/com/deephathi/crack/code/ch1_stringarrays/ex1_3/SpaceEncodingsCharArray.java
deephathi/crack-code
415d49b585c0bbd592fe7dca483c2c113c598e2e
[ "MIT" ]
null
null
null
src/main/java/com/deephathi/crack/code/ch1_stringarrays/ex1_3/SpaceEncodingsCharArray.java
deephathi/crack-code
415d49b585c0bbd592fe7dca483c2c113c598e2e
[ "MIT" ]
null
null
null
src/main/java/com/deephathi/crack/code/ch1_stringarrays/ex1_3/SpaceEncodingsCharArray.java
deephathi/crack-code
415d49b585c0bbd592fe7dca483c2c113c598e2e
[ "MIT" ]
null
null
null
31.235294
69
0.612053
1,002,431
package com.deephathi.crack.code.ch1_stringarrays.ex1_3; public class SpaceEncodingsCharArray extends AbstractSpaceEncodings { @Override public String encodeString(String str) { StringBuilder resultBuilder = new StringBuilder(); for (Character strChar : str.trim().toCharArray()) { if(strChar.equals(' ')) { resultBuilder.append("%20"); } else { resultBuilder.append(strChar); } } return resultBuilder.toString(); } }
9242d726c9fb4a204635d5adaf26ea8dd7e91065
5,816
java
Java
ph-commons/src/main/java/com/helger/commons/codec/IByteArrayStreamDecoder.java
phax/ph-commons
973db756523f3f49217e14fac8589fb504bae481
[ "Apache-2.0" ]
29
2015-09-08T06:44:38.000Z
2022-02-25T08:15:02.000Z
ph-commons/src/main/java/com/helger/commons/codec/IByteArrayStreamDecoder.java
phax/ph-commons
973db756523f3f49217e14fac8589fb504bae481
[ "Apache-2.0" ]
20
2017-01-05T16:31:14.000Z
2022-01-04T11:17:40.000Z
ph-commons/src/main/java/com/helger/commons/codec/IByteArrayStreamDecoder.java
phax/ph-commons
973db756523f3f49217e14fac8589fb504bae481
[ "Apache-2.0" ]
14
2015-03-23T13:43:32.000Z
2022-01-11T07:08:42.000Z
33.425287
136
0.65784
1,002,432
/* * Copyright (C) 2014-2021 Philip Helger (www.helger.com) * philip[at]helger[dot]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.helger.commons.codec; import java.io.OutputStream; import java.nio.charset.Charset; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.WillNotClose; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.io.stream.NonBlockingByteArrayOutputStream; /** * Interface for a single decoder of bytes, based on streams. * * @author Philip Helger */ @FunctionalInterface public interface IByteArrayStreamDecoder extends IByteArrayDecoder { /** * Decode a byte array. * * @param aEncodedBuffer * The byte array to be decoded. May be <code>null</code>. * @param aOS * The output stream to write to. May not be <code>null</code> and is * NOT closed afterwards! * @throws DecodeException * in case something goes wrong * @since 9.0.0 */ default void decode (@Nullable final byte [] aEncodedBuffer, @Nonnull @WillNotClose final OutputStream aOS) { if (aEncodedBuffer == null) decode (null, 0, 0, aOS); else decode (aEncodedBuffer, 0, aEncodedBuffer.length, aOS); } /** * Decode (part of) a byte array. * * @param aEncodedBuffer * The byte array to be decoded. May be <code>null</code>. * @param nOfs * Offset into the byte array to start from. * @param nLen * Number of bytes starting from offset to consider. * @param aOS * The output stream to write to. May not be <code>null</code> and is * NOT closed afterwards! * @throws DecodeException * in case something goes wrong */ void decode (@Nullable byte [] aEncodedBuffer, @Nonnegative int nOfs, @Nonnegative int nLen, @Nonnull @WillNotClose OutputStream aOS); /** * Decode a byte array. * * @param aEncodedBuffer * The byte array to be decoded. May be <code>null</code>. * @param nOfs * Offset into the byte array to start from. * @param nLen * Number of bytes starting from offset to consider. * @return The decoded byte array or <code>null</code> if the parameter was * <code>null</code>. * @throws DecodeException * in case something goes wrong */ @Nullable @ReturnsMutableCopy default byte [] getDecoded (@Nullable final byte [] aEncodedBuffer, @Nonnegative final int nOfs, @Nonnegative final int nLen) { if (aEncodedBuffer == null) return null; try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream (getMaximumDecodedLength (nLen))) { decode (aEncodedBuffer, nOfs, nLen, aBAOS); return aBAOS.getBufferOrCopy (); } } @Nullable default String getDecodedAsString (@Nullable final byte [] aEncodedBuffer, @Nonnull final Charset aCharset) { if (aEncodedBuffer == null) return null; return getDecodedAsString (aEncodedBuffer, 0, aEncodedBuffer.length, aCharset); } @Nullable default String getDecodedAsString (@Nullable final byte [] aEncodedBuffer, @Nonnegative final int nOfs, @Nonnegative final int nLen, @Nonnull final Charset aCharset) { if (aEncodedBuffer == null) return null; try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream (getMaximumDecodedLength (nLen))) { decode (aEncodedBuffer, nOfs, nLen, aBAOS); return aBAOS.getAsString (aCharset); } } /** * Decode the passed string. * * @param sEncoded * The string to be decoded. May be <code>null</code>. * @param aCharset * The charset to be used for encoding AND decoding. May not be * <code>null</code>. * @return <code>null</code> if the input string is <code>null</code>. * @throws DecodeException * in case something goes wrong */ @Nullable default String getDecodedAsString (@Nullable final String sEncoded, @Nonnull final Charset aCharset) { return getDecodedAsString (sEncoded, aCharset, aCharset); } /** * Decode the passed string. * * @param sEncoded * The string to be decoded. May be <code>null</code>. * @param aEncodedCharset * The charset to be used for the encoded string. May not be * <code>null</code>. * @param aDecodedCharset * The charset to be used for the decoded result string. May not be * <code>null</code>. * @return <code>null</code> if the input string is <code>null</code>. * @throws DecodeException * in case something goes wrong * @since 9.3.6 */ @Nullable default String getDecodedAsString (@Nullable final String sEncoded, @Nonnull final Charset aEncodedCharset, @Nonnull final Charset aDecodedCharset) { if (sEncoded == null) return null; final byte [] aEncoded = sEncoded.getBytes (aEncodedCharset); return getDecodedAsString (aEncoded, 0, aEncoded.length, aDecodedCharset); } }
9242d72cefff7558e90e7237d389ead68ddd97b6
1,889
java
Java
modules/flowable-bpmn-converter/src/test/java/org/flowable/editor/language/xml/EncodingConverterTest.java
gaoyida/flowable-engine
b6875949741c9807da6d2c34121bc4dee1e63b3f
[ "Apache-2.0" ]
3
2019-05-07T02:58:38.000Z
2021-03-12T05:50:45.000Z
modules/flowable-bpmn-converter/src/test/java/org/flowable/editor/language/xml/EncodingConverterTest.java
gaoyida/flowable-engine
b6875949741c9807da6d2c34121bc4dee1e63b3f
[ "Apache-2.0" ]
6
2018-10-16T06:04:06.000Z
2021-12-08T05:59:47.000Z
modules/flowable-bpmn-converter/src/test/java/org/flowable/editor/language/xml/EncodingConverterTest.java
gaoyida/flowable-engine
b6875949741c9807da6d2c34121bc4dee1e63b3f
[ "Apache-2.0" ]
2
2018-12-03T11:14:18.000Z
2018-12-03T13:09:27.000Z
34.981481
91
0.727898
1,002,433
/* 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.flowable.editor.language.xml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.flowable.bpmn.model.BpmnModel; import org.flowable.bpmn.model.FlowElement; import org.flowable.bpmn.model.UserTask; import org.junit.Test; public class EncodingConverterTest extends AbstractConverterTest { @Test public void convertXMLToModel() throws Exception { BpmnModel bpmnModel = readXMLFile(); validateModel(bpmnModel); } @Test public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); validateModel(parsedModel); } private void validateModel(BpmnModel model) { FlowElement flowElement = model.getMainProcess().getFlowElement("writeReportTask"); assertNotNull(flowElement); assertTrue(flowElement instanceof UserTask); assertEquals("writeReportTask", flowElement.getId()); UserTask userTask = (UserTask) flowElement; assertEquals("writeReportTask", userTask.getId()); assertEquals("Fazer relatório", userTask.getName()); } @Override protected String getResource() { return "encoding.bpmn"; } }
9242d8701c83e76f95507a4e2080c256efe3acaf
349
java
Java
SpringBootDynamicFilteringTestWebServices/src/main/java/com/hari/SpringBootDynamicFilteringTestWebServices.java
NarahariP/Web_Services
4b591e00d9fedf6c4dd660745259f0e85f28cb09
[ "Apache-2.0" ]
1
2019-12-29T03:49:35.000Z
2019-12-29T03:49:35.000Z
SpringBootDynamicFilteringTestWebServices/src/main/java/com/hari/SpringBootDynamicFilteringTestWebServices.java
NarahariP/Web_Services
4b591e00d9fedf6c4dd660745259f0e85f28cb09
[ "Apache-2.0" ]
null
null
null
SpringBootDynamicFilteringTestWebServices/src/main/java/com/hari/SpringBootDynamicFilteringTestWebServices.java
NarahariP/Web_Services
4b591e00d9fedf6c4dd660745259f0e85f28cb09
[ "Apache-2.0" ]
null
null
null
24.928571
79
0.842407
1,002,434
package com.hari; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootDynamicFilteringTestWebServices { public static void main(String[] args) { SpringApplication.run(SpringBootDynamicFilteringTestWebServices.class, args); } }
9242d8cff310059235d742864e488e553fc4d769
4,867
java
Java
influent-server/src/main/java/influent/server/search/DataViewEntitySearch.java
unchartedsoftware/influent
25793f299331b226e00aef2a43aa5f5c86937867
[ "Apache-2.0" ]
34
2015-04-02T17:09:53.000Z
2020-08-30T03:59:38.000Z
influent-server/src/main/java/influent/server/search/DataViewEntitySearch.java
unchartedsoftware/influent
25793f299331b226e00aef2a43aa5f5c86937867
[ "Apache-2.0" ]
10
2015-03-19T10:29:11.000Z
2016-07-14T17:28:41.000Z
influent-server/src/main/java/influent/server/search/DataViewEntitySearch.java
unchartedsoftware/influent
25793f299331b226e00aef2a43aa5f5c86937867
[ "Apache-2.0" ]
22
2015-04-22T06:54:13.000Z
2021-11-30T15:48:37.000Z
27.811429
103
0.764126
1,002,435
/* * Copyright 2013-2016 Uncharted Software Inc. * * Property of Uncharted(TM), formerly Oculus Info Inc. * https://uncharted.software/ * * 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 influent.server.search; import influent.idl.*; import influent.idlhelper.EntityHelper; import influent.idlhelper.PropertyDescriptorHelper; import influent.server.dataaccess.DataNamespaceHandler; import influent.server.dataaccess.SearchSQLHelper; import influent.server.sql.SQLBuilder; import influent.server.utilities.*; import influent.server.configuration.ApplicationConfiguration; import oculus.aperture.spi.common.Properties; import org.apache.avro.AvroRemoteException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * Created by cdickson on 22/10/2014. */ public class DataViewEntitySearch implements FL_EntitySearch { protected final SQLConnectionPool _connectionPool; protected final DataNamespaceHandler _namespaceHandler; protected final SQLBuilder _sqlBuilder; protected final SearchSQLHelper _sqlHelper; protected final ApplicationConfiguration _applicationConfiguration; protected static final Logger s_logger = LoggerFactory.getLogger(DataViewEntitySearch.class); protected Logger getLogger() { return s_logger; } public DataViewEntitySearch( Properties config, SQLConnectionPool connectionPool, DataNamespaceHandler namespaceHandler, SQLBuilder sqlBuilder ) { _connectionPool = connectionPool; _namespaceHandler = namespaceHandler; _sqlBuilder = sqlBuilder; _applicationConfiguration = ApplicationConfiguration.getInstance(config); _sqlHelper = new SearchSQLHelper( _sqlBuilder, _connectionPool, _applicationConfiguration, FL_Entity.class ); } @Override public FL_SearchResults search( Map<String, List<FL_PropertyMatchDescriptor>> termMap, List<FL_OrderBy> orderBy, long start, long max, FL_LevelOfDetail levelOfDetail ) throws AvroRemoteException { ArrayList<FL_SearchResult> matches = new ArrayList<FL_SearchResult>(); List<Object> entityList = _sqlHelper.getObjectsFromTerms(termMap, orderBy, levelOfDetail, true); long end = start + max < entityList.size() ? start + max : entityList.size(); for (long i = start; i < end; i++) { Object entity = entityList.get((int) i); matches.add(new FL_SearchResult(1.0, entity)); } return FL_SearchResults.newBuilder() .setTotal((long) matches.size()) .setResults(matches) .setLevelOfDetail(levelOfDetail) .build(); } @Override public FL_PropertyDescriptors getDescriptors() throws AvroRemoteException { return _applicationConfiguration.getEntityDescriptors(); } public PropertyField.Provider getPropertyFieldProvider() { return _applicationConfiguration; } protected FL_Entity createEntity(String id, String label, String type, List<FL_Property> props) { String uid = _namespaceHandler.globalFromLocalEntityId(InfluentId.ACCOUNT, type, id); return new EntityHelper(uid, label, type, FL_EntityTag.ACCOUNT, props); } protected DataNamespaceHandler getNamespaceHandler() { return _namespaceHandler; } /* (non-Javadoc) * @see influent.idl.FL_EntitySearch#getPropertyHeaders(influent.idl.FL_SearchResults, java.util.List) */ @Override public FL_PropertyDescriptors getKeyDescriptors(FL_SearchResults results, List<FL_OrderBy> resultOrder ) throws AvroRemoteException { final FL_PropertyDescriptors all = _applicationConfiguration.getEntityDescriptors(); final List<FL_PropertyDescriptor> props = all.getProperties(); final List<FL_PropertyDescriptor> keyFields= new ArrayList<FL_PropertyDescriptor>(); if (!props.isEmpty()) { for (FL_PropertyDescriptor pd : all.getProperties()) { if (FL_LevelOfDetail.KEY.equals(pd.getLevelOfDetail())) { keyFields.add(pd); } } if (keyFields.isEmpty()) { addIfNotNull(keyFields, PropertyDescriptorHelper.find(FL_RequiredPropertyKey.NAME.name(), props)); } if (keyFields.isEmpty()) { keyFields.add(props.get(0)); } } return FL_PropertyDescriptors.newBuilder() .setOrderBy(resultOrder) .setProperties(keyFields) .setTypes(all.getTypes()) .build(); } private void addIfNotNull(List<FL_PropertyDescriptor> list, FL_PropertyDescriptor item) { if (item != null) { list.add(item); } } }
9242d8e119177dc0f6da62338705303708656499
524
java
Java
lib/src/main/java/com/tamatea/model/entity/objects/Attack.java
tamateea/torn-java-api
124efe96873f7f3acb441bbbf38ae6380bdc3424
[ "CC0-1.0" ]
null
null
null
lib/src/main/java/com/tamatea/model/entity/objects/Attack.java
tamateea/torn-java-api
124efe96873f7f3acb441bbbf38ae6380bdc3424
[ "CC0-1.0" ]
null
null
null
lib/src/main/java/com/tamatea/model/entity/objects/Attack.java
tamateea/torn-java-api
124efe96873f7f3acb441bbbf38ae6380bdc3424
[ "CC0-1.0" ]
null
null
null
20.96
41
0.715649
1,002,436
package com.tamatea.model.entity.objects; public class Attack { String code; long timestamp_start; long timestamp_ended; int attacker_id; String attacker_name; int attacker_faction; String attacker_factionname; int defender_id; String defender_name; int defender_faction; String defender_factionname; AttackType result; boolean stealthed; double respect; int chain; int raid; double respect_gain; double respect_loss; AttackModifier modifiers; }
9242d916033df75abbc41a594a367af69610581e
1,136
java
Java
extjsf/src/main/java/net/java/jsf/extjs/faces/system/LocalFaceletViewHandlingStrategy.java
AntonBaukin/extjsf
61cae8caf940383e77e1d4a748da100c7eef1910
[ "Unlicense" ]
null
null
null
extjsf/src/main/java/net/java/jsf/extjs/faces/system/LocalFaceletViewHandlingStrategy.java
AntonBaukin/extjsf
61cae8caf940383e77e1d4a748da100c7eef1910
[ "Unlicense" ]
null
null
null
extjsf/src/main/java/net/java/jsf/extjs/faces/system/LocalFaceletViewHandlingStrategy.java
AntonBaukin/extjsf
61cae8caf940383e77e1d4a748da100c7eef1910
[ "Unlicense" ]
null
null
null
21.942308
72
0.743208
1,002,437
package net.java.jsf.extjs.faces.system; /* Java */ import java.io.IOException; /* JavaServer Faces */ import javax.faces.FacesException; import javax.faces.context.FacesContext; /* JavaServer Faces Reference Implementation */ import com.sun.faces.application.view.FaceletViewHandlingStrategy; /* extjsf: support */ import net.java.jsf.extjs.support.EX; import net.java.jsf.extjs.support.misc.HiddenError; /** * JSF system level class. It's present goal is * to treat exceptions during the JSF processing. * * @author [email protected] */ public class LocalFaceletViewHandlingStrategy extends FaceletViewHandlingStrategy { /* protected: FaceletViewHandlingStrategy (error handling) */ protected void handleRenderException(FacesContext context, Exception e) throws IOException { //?: {this error must be logged} if(EX.search(e, HiddenError.class) == null) { super.handleRenderException(context, e); return; } //!: throw the error if(e instanceof RuntimeException) throw (RuntimeException)e; if(e instanceof IOException) throw (IOException)e; throw new FacesException(e); } }
9242da7a019fac38e3fda05933a9539282f75b25
490
java
Java
src/main/java/com/github/msemys/esjc/CatchUpSubscriptionListener.java
dunfield-synopsys/esjc
ded2c3ea843a68f86181fe019ed1cc633af1ffd5
[ "MIT" ]
116
2016-03-11T22:24:12.000Z
2022-02-02T07:46:34.000Z
src/main/java/com/github/msemys/esjc/CatchUpSubscriptionListener.java
dunfield-synopsys/esjc
ded2c3ea843a68f86181fe019ed1cc633af1ffd5
[ "MIT" ]
65
2016-03-25T08:54:05.000Z
2021-09-17T08:02:13.000Z
src/main/java/com/github/msemys/esjc/CatchUpSubscriptionListener.java
dunfield-synopsys/esjc
ded2c3ea843a68f86181fe019ed1cc633af1ffd5
[ "MIT" ]
38
2016-05-28T07:07:29.000Z
2022-03-08T14:45:54.000Z
27.222222
111
0.753061
1,002,438
package com.github.msemys.esjc; /** * The listener interface for receiving catch-up subscription action events. */ public interface CatchUpSubscriptionListener extends SubscriptionListener<CatchUpSubscription, ResolvedEvent> { /** * Invoked when the subscription switches from the reading phase to the live subscription phase. * * @param subscription target subscription. */ default void onLiveProcessingStarted(CatchUpSubscription subscription) { } }
9242dbedff7e6d67383dddf688dc62b5892a014b
677
java
Java
src/main/java/com/net/oya/service/RememberService.java
mounirzz/OYA
4f5efc00a7ca280ce689148c2fa9bcb82306c8c9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/net/oya/service/RememberService.java
mounirzz/OYA
4f5efc00a7ca280ce689148c2fa9bcb82306c8c9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/net/oya/service/RememberService.java
mounirzz/OYA
4f5efc00a7ca280ce689148c2fa9bcb82306c8c9
[ "Apache-2.0" ]
null
null
null
21.21875
62
0.726068
1,002,439
package com.net.oya.service; import com.net.oya.model.Remember; import com.net.oya.repository.RememberRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author Mounir * @email [email protected] * @date 2017-10-20 */ @Service public class RememberService { @Autowired RememberRepository rememberRepository; public void add(Remember remember) { rememberRepository.save(remember); } public void delete(String uuid){ rememberRepository.delete(uuid); } public Remember findById(String uuid){ return rememberRepository.findOne(uuid); } }
9242dbf086473dc4c8c4c689466fb5bf18b6abc4
1,946
java
Java
jstorm-core/src/main/java/com/alibaba/jstorm/callback/BackpressureCallback.java
chenqixu/jstorm
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
[ "Apache-2.0" ]
4,124
2015-01-03T15:58:17.000Z
2022-03-31T11:06:25.000Z
jstorm-core/src/main/java/com/alibaba/jstorm/callback/BackpressureCallback.java
chenqixu/jstorm
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
[ "Apache-2.0" ]
596
2015-01-05T14:11:02.000Z
2021-08-05T20:44:39.000Z
jstorm-core/src/main/java/com/alibaba/jstorm/callback/BackpressureCallback.java
chenqixu/jstorm
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
[ "Apache-2.0" ]
2,064
2015-01-04T10:54:02.000Z
2022-03-29T06:55:43.000Z
33.551724
90
0.702467
1,002,440
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.jstorm.callback; import java.util.Map; import java.util.Set; import org.jboss.netty.channel.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import backtype.storm.utils.DisruptorQueue; import com.alibaba.jstorm.message.netty.NettyServerFlowCtrlHandler; public class BackpressureCallback implements Callback { private static final Logger LOG = LoggerFactory.getLogger(BackpressureCallback.class); private NettyServerFlowCtrlHandler handler; private int taskId; public BackpressureCallback(NettyServerFlowCtrlHandler handler, int taskId) { this.taskId = taskId; this.handler = handler; } public <T> Object execute(T... args) { DisruptorQueue queue = (DisruptorQueue) args[0]; if (handler.checkIfUnderFlowCtrl(queue)) { try { handler.releaseFlowCtrl(taskId); } catch (InterruptedException e) { LOG.warn("Failed to release flow control for task-{}", taskId); return false; } return true; } else { return false; } } }
9242dc7faf880f64dea7cbf412c3a3440d68d730
368
java
Java
src/main/java/cn/lands/liuwang/investservice/config/WebMvcConfig.java
jasonLiu001/invest-service
3b86730f24351e88b5c07dcfaa33b8178d3b50ae
[ "MIT" ]
null
null
null
src/main/java/cn/lands/liuwang/investservice/config/WebMvcConfig.java
jasonLiu001/invest-service
3b86730f24351e88b5c07dcfaa33b8178d3b50ae
[ "MIT" ]
null
null
null
src/main/java/cn/lands/liuwang/investservice/config/WebMvcConfig.java
jasonLiu001/invest-service
3b86730f24351e88b5c07dcfaa33b8178d3b50ae
[ "MIT" ]
null
null
null
26.285714
81
0.831522
1,002,441
package cn.lands.liuwang.investservice.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * * Spring MVC 配置 */ @Configuration public class WebMvcConfig implements WebMvcConfigurer { }
9242dd04bcd6b294ba86623d0f82acd5625cc31b
451
java
Java
hxcpp-debugger-protocol/src/JavaProtocol/src/haxe/lang/VarArgsFunction.java
yanhick/intellij-haxe-nightly-builds
415cee0cb0d6027227c5629e59c53fec30745d34
[ "Apache-2.0" ]
48
2015-01-01T06:32:10.000Z
2022-01-13T11:05:25.000Z
template/deploy/src/haxe/lang/VarArgsFunction.java
haxorplatform/androidhx
6644be77b59e6de5805646a0f47c5c191284bd01
[ "MIT" ]
14
2015-04-14T20:35:21.000Z
2017-08-05T01:49:03.000Z
template/deploy/src/haxe/lang/VarArgsFunction.java
haxorplatform/androidhx
6644be77b59e6de5805646a0f47c5c191284bd01
[ "MIT" ]
25
2015-01-08T10:35:06.000Z
2021-11-10T07:17:12.000Z
18.04
80
0.702882
1,002,442
package haxe.lang; import haxe.root.*; @SuppressWarnings(value={"rawtypes", "unchecked"}) public class VarArgsFunction extends haxe.lang.VarArgsBase { public VarArgsFunction(haxe.lang.Function fun) { super(-1, -1); this.fun = fun; } public haxe.lang.Function fun; @Override public java.lang.Object __hx_invokeDynamic(haxe.root.Array dynArgs) { return ((java.lang.Object) (this.fun.__hx_invoke1_o(0.0, dynArgs)) ); } }
9242dd934e0b8bea9b608cae752022b07d96c46d
2,460
java
Java
src/test/java/PostalGeocoderTester.java
OpenSextant/Xponents
5291040ac6e78bcaee3f4edd0e3dd4fdcbaa761b
[ "Apache-2.0" ]
48
2015-01-12T18:26:09.000Z
2022-02-27T23:15:02.000Z
src/test/java/PostalGeocoderTester.java
OpenSextant/Xponents
5291040ac6e78bcaee3f4edd0e3dd4fdcbaa761b
[ "Apache-2.0" ]
64
2015-02-27T17:05:25.000Z
2022-02-07T19:10:27.000Z
src/test/java/PostalGeocoderTester.java
OpenSextant/Xponents
5291040ac6e78bcaee3f4edd0e3dd4fdcbaa761b
[ "Apache-2.0" ]
4
2015-02-27T15:37:26.000Z
2021-08-19T14:13:51.000Z
38.4375
121
0.654065
1,002,443
import org.opensextant.ConfigException; import org.opensextant.data.TextInput; import org.opensextant.extraction.ExtractionException; import org.opensextant.extraction.TextMatch; import org.opensextant.extractors.geo.PlaceGeocoder; import org.opensextant.extractors.geo.PostalGeocoder; import org.opensextant.extractors.test.TestGazMatcher; import java.util.List; public class PostalGeocoderTester extends TestGazMatcher { PlaceGeocoder preTagger = null; public PostalGeocoderTester() throws ConfigException { geocoder = new PostalGeocoder(); geocoder.configure(); preTagger = new PlaceGeocoder(); preTagger.configure(); } protected void tagText(TextInput t) throws ExtractionException { print("TEST:\t" + t.buffer + "\n====================="); // Step 0. You can stop here and return postal matches if you want. List<TextMatch> postalMatches = geocoder.extract(t); // Step 1. Fully tag text to find related geography and associate City + Postal. // NOTE: this assumes that the postal tagger is incomplete and any pre-selected geocoding is tossed away. List<TextMatch> matches = preTagger.extract(t); PostalGeocoder.associateMatches(matches, postalMatches); // Step 2. (Only if Step 1 occurred) Generate new spans with the finest location chosen. // "derivedMatches" here is a super set of the originals and any derivations. List<TextMatch> derivedMatches = PostalGeocoder.deriveMatches(postalMatches, t); // Emit just postal matches here -- to not overwhelm output. // But in general the super set of matches is output. summarizeFindings(derivedMatches); print(" ** Only Postal Geotags were emitted. **\n"); } public static void main(String[] args) { PostalGeocoderTester tester = null; try { tester = new PostalGeocoderTester(); tester.parseOptions(args); if (tester.params.inputFile != null && tester.params.inputFile.endsWith(".json")) { tester.tagBatch(tester.params.inputFile); } else { tester.tagText(tester.inputText); } } catch (Exception err) { err.printStackTrace(); } if (tester!=null) { tester.geocoder.cleanup(); tester.preTagger.cleanup(); } System.exit(0); } }
9242df0ba95295b78f91b87766f5129496596003
1,432
java
Java
src/main/java/it/polimi/ingsw/utils/messages/serverMessages/SoloModeMatchWinnerMessage.java
domenicoputignano/ing-sw-2021-Putignano-Rendina-Restelli
14a0750aa41c9efcb1183f8f7a218d401cea51f4
[ "MIT" ]
null
null
null
src/main/java/it/polimi/ingsw/utils/messages/serverMessages/SoloModeMatchWinnerMessage.java
domenicoputignano/ing-sw-2021-Putignano-Rendina-Restelli
14a0750aa41c9efcb1183f8f7a218d401cea51f4
[ "MIT" ]
null
null
null
src/main/java/it/polimi/ingsw/utils/messages/serverMessages/SoloModeMatchWinnerMessage.java
domenicoputignano/ing-sw-2021-Putignano-Rendina-Restelli
14a0750aa41c9efcb1183f8f7a218d401cea51f4
[ "MIT" ]
2
2021-09-17T13:39:59.000Z
2021-12-24T19:27:40.000Z
28.078431
109
0.690642
1,002,444
package it.polimi.ingsw.utils.messages.serverMessages; import it.polimi.ingsw.model.gameEvents.ConclusionEvent; import it.polimi.ingsw.network.Client; /** * Class consisting of a message sent at the end of a solo mode game. */ public class SoloModeMatchWinnerMessage implements ServerMessage{ /** * Boolean attribute that establishes if player won. */ private final boolean playerWon; /** * If the player has won this number becomes relevant because * represents how many points has been gained. */ private final int victoryPoints; /** * Event that triggered game conclusion. */ private final ConclusionEvent conclusionEvent; public SoloModeMatchWinnerMessage(boolean playerWon, int victoryPoints,ConclusionEvent conclusionEvent) { this.playerWon = playerWon; this.victoryPoints = victoryPoints; this.conclusionEvent = conclusionEvent; } public boolean hasPlayerWon() { return playerWon; } public int getVictoryPoints() { return victoryPoints; } public ConclusionEvent getConclusionEvent() { return conclusionEvent; } /** * Method called by client in order to show message itself. * @param handler {@link Client} instance that manages the update itself. */ @Override public void handleMessage(Client handler) { handler.getUI().render(this); } }
9242df257a8689d13fbb1a4ce0cdfb15bc82396e
3,905
java
Java
cto51-lesson15/src/test/java/com/cto51/RedisTest.java
happyhuangjinjin/junit
ee12116680987c8ed233192d3618b09286568767
[ "Apache-2.0" ]
null
null
null
cto51-lesson15/src/test/java/com/cto51/RedisTest.java
happyhuangjinjin/junit
ee12116680987c8ed233192d3618b09286568767
[ "Apache-2.0" ]
null
null
null
cto51-lesson15/src/test/java/com/cto51/RedisTest.java
happyhuangjinjin/junit
ee12116680987c8ed233192d3618b09286568767
[ "Apache-2.0" ]
null
null
null
30.748031
93
0.693982
1,002,445
package com.cto51; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired private RedisTemplate<String, String> redisCacheTemplate; @Test public void stringTest() { // 设置 redisCacheTemplate.opsForValue().set("testString", "公众号 聊点"); // 获取 System.out.println(redisCacheTemplate.opsForValue().get("testString")); } @Test public void expireTest() { // 设置 redisCacheTemplate.opsForValue().set("testString", "公众号 聊点", 10, TimeUnit.SECONDS); // 获取 System.out.println("存在testString = " + redisCacheTemplate.opsForValue().get("testString")); try { Thread.sleep(10000); } catch (InterruptedException e) { } // 获取 System.out.println("不存在testString = " + redisCacheTemplate.hasKey("testString")); } @Test public void deleteTest() { // 设置 redisCacheTemplate.opsForValue().set("testString", "公众号 聊点", 10, TimeUnit.SECONDS); // 获取 System.out.println("存在testString = " + redisCacheTemplate.opsForValue().get("testString")); // 删除 redisCacheTemplate.delete("testString"); // 获取 System.out.println("不存在testString = " + redisCacheTemplate.hasKey("testString")); } @Test public void listTest() { ListOperations<String, String> listOpr = redisCacheTemplate.opsForList(); listOpr.leftPush("list", "java"); listOpr.leftPush("list", "c#"); listOpr.leftPush("list", "c++"); listOpr.rightPush("list", "python"); String value = (String) listOpr.leftPop("list"); System.out.println("list value :" + value.toString()); value = (String) listOpr.rightPop("list"); System.out.println("list value :" + value.toString()); } @Test public void hashTest() { HashOperations<String, String, String> hashOpr = redisCacheTemplate.opsForHash(); hashOpr.put("redisKey", "key1", "java"); hashOpr.put("redisKey", "key2", "c#"); hashOpr.put("redisKey", "key3", "python"); String value1 = hashOpr.get("redisKey", "key3"); System.out.println("key1 = " + value1); } @Test public void setTest() { SetOperations<String, String> setOpr = redisCacheTemplate.opsForSet(); setOpr.add("set", "java"); setOpr.add("set", "c#"); setOpr.add("set", "python"); setOpr.add("set", "java"); Set<String> set = setOpr.members("set"); Iterator<String> items = set.iterator(); while (items.hasNext()) { System.out.println(items.next()); } System.out.println("-----------"); ListOperations<String, String> listOpr = redisCacheTemplate.opsForList(); listOpr.leftPush("listv", "java"); listOpr.leftPush("listv", "c#"); listOpr.leftPush("listv", "python"); listOpr.leftPush("listv", "java"); List<String> list = listOpr.range("listv", 0, -1); items = list.iterator(); while (items.hasNext()) { System.out.println(items.next()); } } @Test public void sortedSetTest() { ZSetOperations<String, String> zset = redisCacheTemplate.opsForZSet(); zset.add("zset", "java", 1); zset.add("zset", "c#", 3); zset.add("zset", "python", 2); zset.add("zset", "c++", 4); Set<String> zsets = zset.range("zset", 0, -1); for (String value : zsets) { System.out.println(value); } System.out.println("------按照socre获取元素--------"); Set<String> zsetB = zset.rangeByScore("zset", 0, 2); for (String value : zsetB) { System.out.println(value); } } }
9242df2bc97edaae8c4f592e039360df7990c808
2,312
java
Java
leetcode/editor/cn/src/main/java/_173_BinarySearchTreeIterator.java
caomu/leetcode_java
3b1d859ff25b33b83c3ec3077bde73fa9bdc9549
[ "MIT" ]
1
2021-02-17T16:05:08.000Z
2021-02-17T16:05:08.000Z
leetcode/editor/cn/src/main/java/_173_BinarySearchTreeIterator.java
caomu/leetcode_java
3b1d859ff25b33b83c3ec3077bde73fa9bdc9549
[ "MIT" ]
null
null
null
leetcode/editor/cn/src/main/java/_173_BinarySearchTreeIterator.java
caomu/leetcode_java
3b1d859ff25b33b83c3ec3077bde73fa9bdc9549
[ "MIT" ]
null
null
null
23.835052
110
0.58045
1,002,446
//实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。 // // 调用 next() 将返回二叉搜索树中的下一个最小的数。 // // // // 示例: // // // // BSTIterator iterator = new BSTIterator(root); //iterator.next(); // 返回 3 //iterator.next(); // 返回 7 //iterator.hasNext(); // 返回 true //iterator.next(); // 返回 9 //iterator.hasNext(); // 返回 true //iterator.next(); // 返回 15 //iterator.hasNext(); // 返回 true //iterator.next(); // 返回 20 //iterator.hasNext(); // 返回 false // // // // 提示: // // // next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。 // 你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。 // // Related Topics 栈 树 设计 // 👍 325 👎 0 import com.caomu.util.TreeNode; import com.caomu.util.Utils; import java.util.ArrayList; import java.util.List; public class _173_BinarySearchTreeIterator { public static void main(String[] args) { BSTIterator solution = new _173_BinarySearchTreeIterator().new BSTIterator(Utils.arrayToTreeNode("")); System.out.println(solution); } //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class BSTIterator { int i; List<Integer> inorder = new ArrayList<>(); public BSTIterator(TreeNode root) { this.i = 0; this.inorder(root); } private void inorder(TreeNode node) { if (node == null) { return; } this.inorder(node.left); this.inorder.add(node.val); this.inorder(node.right); } public int next() { return this.inorder.get(this.i++); } public boolean hasNext() { return this.inorder.size() > this.i; } } /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */ //leetcode submit region end(Prohibit modification and deletion) }
9242dfa846f06acd3c11e9dcf6f82dd1b9c1e140
3,739
java
Java
examples/testing-with-neo4j-harness/src/test/java/org/neo4j/doc/driver/springframework/boot/simple/MoviesServiceAlt3Test.java
fbiville/neo4j-java-driver-spring-boot-starter
a482308b3911ca228511c222b15d8324518f1363
[ "Apache-2.0" ]
35
2019-06-26T16:03:26.000Z
2022-03-02T02:00:59.000Z
examples/testing-with-neo4j-harness/src/test/java/org/neo4j/doc/driver/springframework/boot/simple/MoviesServiceAlt3Test.java
fbiville/neo4j-java-driver-spring-boot-starter
a482308b3911ca228511c222b15d8324518f1363
[ "Apache-2.0" ]
15
2019-07-23T13:32:54.000Z
2021-12-03T09:16:37.000Z
examples/testing-with-neo4j-harness/src/test/java/org/neo4j/doc/driver/springframework/boot/simple/MoviesServiceAlt3Test.java
fbiville/neo4j-java-driver-spring-boot-starter
a482308b3911ca228511c222b15d8324518f1363
[ "Apache-2.0" ]
12
2019-07-26T12:02:15.000Z
2022-02-13T01:23:24.000Z
38.947917
147
0.771329
1,002,447
/* * Copyright (c) 2019-2020 "Neo4j," * Neo4j Sweden AB [https://neo4j.com] * * This file is part of Neo4j. * * 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.neo4j.doc.driver.springframework.boot.simple; import static org.assertj.core.api.Assertions.*; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.neo4j.driver.Driver; import org.neo4j.driver.springframework.boot.test.autoconfigure.Neo4jTestHarnessAutoConfiguration; import org.neo4j.harness.Neo4j; import org.neo4j.harness.Neo4jBuilders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.ContextConfiguration; /** * This variant uses a custom {@link ApplicationContextInitializer} that modifies Springs configuration properties * with the help of {@link TestPropertyValues}. Thus, the autoconfiguration of the driver is kept and all other things * are as you'd expect in production. * <p>If you don't like that setup, look at {@link MoviesServiceAlt1Test}. Here, we expose the embedded server as a Spring Bean * and don't do the manual connection setting. */ // tag::test-harness-example-option3[] @SpringBootTest @EnableAutoConfiguration(exclude = { Neo4jTestHarnessAutoConfiguration.class }) // <.> @ContextConfiguration(initializers = { MoviesServiceAlt3Test.Initializer.class }) class MoviesServiceAlt3Test { private static Neo4j embeddedDatabaseServer; @BeforeAll static void initializeNeo4j() { // <.> embeddedDatabaseServer = Neo4jBuilders.newInProcessBuilder() .withDisabledServer() // <.> .withFixture("" + "CREATE (TheMatrix:Movie {title:'The Matrix', released:1999, tagline:'Welcome to the Real World'})\n" + "CREATE (TheMatrixReloaded:Movie {title:'The Matrix Reloaded', released:2003, tagline:'Free your mind'})\n" + "CREATE (TheMatrixRevolutions:Movie {title:'The Matrix Revolutions', released:2003, tagline:'Everything that has a beginning has an end'})\n" ) .build(); } @AfterAll static void closeNeo4j() { // <.> embeddedDatabaseServer.close(); } // <.> static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { public void initialize(ConfigurableApplicationContext configurableApplicationContext) { TestPropertyValues.of( "org.neo4j.driver.uri=" + embeddedDatabaseServer.boltURI().toString(), "org.neo4j.driver.authentication.password=" ).applyTo(configurableApplicationContext.getEnvironment()); } } @Test void testSomethingWithTheDriver(@Autowired Driver driver) { } // end::test-harness-example-option3[] @Test void shouldRetrieveMovieTitles(@Autowired MoviesService moviesService) { assertThat(moviesService.getMovieTitles()) .hasSize(3) .contains("The Matrix"); } // tag::test-harness-example-option3[] } // end::test-harness-example-option3[]
9242dfc866e0f633689133803ee93431cb361f9a
8,087
java
Java
src/org/gavrog/joss/dsyms/generators/FrankKasper.java
undeadinu/gavrog
159ebdb80ba661c48164b392d59a0519ec643521
[ "Apache-2.0" ]
21
2015-04-13T10:12:41.000Z
2021-12-26T21:24:14.000Z
src/org/gavrog/joss/dsyms/generators/FrankKasper.java
undeadinu/gavrog
159ebdb80ba661c48164b392d59a0519ec643521
[ "Apache-2.0" ]
15
2015-04-13T10:11:25.000Z
2021-01-31T21:16:50.000Z
src/org/gavrog/joss/dsyms/generators/FrankKasper.java
undeadinu/gavrog
159ebdb80ba661c48164b392d59a0519ec643521
[ "Apache-2.0" ]
5
2015-07-24T11:06:02.000Z
2020-03-13T16:15:57.000Z
30.402256
79
0.535551
1,002,448
/* Copyright 2012 Olaf Delgado-Friedrichs 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.gavrog.joss.dsyms.generators; import java.io.FileWriter; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.gavrog.box.collections.Iterators; import org.gavrog.box.simple.Stopwatch; import org.gavrog.joss.algorithms.CheckpointEvent; import org.gavrog.joss.algorithms.ResumableGenerator; import org.gavrog.joss.dsyms.basic.DSymbol; import org.gavrog.joss.dsyms.basic.DelaneySymbol; import org.gavrog.joss.dsyms.basic.DynamicDSymbol; import org.gavrog.joss.dsyms.basic.IndexList; import org.gavrog.joss.dsyms.derived.EuclidicityTester; import buoy.event.EventProcessor; /** * Generates all tile-k-transitive tetrahedra tilings with edge degrees 5 and 6 * only. */ public class FrankKasper extends TileKTransitive { public FrankKasper(final int k, final boolean verbose) { super(new DSymbol("1:1,1,1:3,3"), k, verbose); } protected Iterator<DSymbol> defineBranching(final DSymbol ds) { final DynamicDSymbol out = new DynamicDSymbol(new DSymbol(ds)); final IndexList idx = new IndexList(2, 3); for (final int D: out.orbitReps(idx)) { final int r = out.r(2, 3, D); if (r == 5) { out.redefineV(2, 3, D, 1); } else if (r > 0 && 6 % r == 0) { out.redefineV(2, 3, D, 6 / r); } else { throw new RuntimeException( "this should not happen: r = " + r + " at D = " + D); } } if (out.isLocallyEuclidean3D()) { return Iterators.singleton(new DSymbol(out)); } else { return Iterators.empty(); } } protected ResumableGenerator<DSymbol> extendTo3d(final DSymbol ds) { return new CombineTiles(ds) { protected List<Move> getExtraDeductions( final DelaneySymbol<Integer> ds, final Move move) { final List<Move> out = new ArrayList<Move>(); final int D = move.element; int E = D; int r = 0; List<Integer> cuts = new ArrayList<Integer>(); do { E = ds.op(2, E); if (ds.definesOp(3, E)) { E = ds.op(3, E); } else { cuts.add(E); } ++r; } while (E != D); switch (cuts.size()) { case 0: if (r == 4 || r > 6) { return null; } break; case 1: if (r > 6) { return null; } else if (r == 6) { final int A = cuts.get(0); out.add(new Move(A, A, -1, -1, false, 0)); } break; case 2: if (r > 12) { return null; } else if (r == 12) { final int A = cuts.get(0); final int B = cuts.get(1); out.add(new Move(A, B, -1, -1, false, 0)); } break; default: throw new RuntimeException("this should not happen"); } return out; } }; } public static void usage() { System.err.print( "Usage: java [PATH] [OPTION]... k [FILE]\n" + "\n" + "where" + " PATH = org.gavrog.joss.dsyms.generators.FrankKasper\n" + " k: number of tile orbits in each generated tiling" + "\n" + "Recognized options:\n" + " -e skip euclidicity test\n" + " -i N interval in seconds between writing checkpoints\n" + " -r A-B-C resume generation at a checkpoint\n" + " -v run in verbose mode\n" ); System.exit(1); } public static void main(final String[] args) { try { boolean verbose = false; boolean check = true; int checkpointInterval = 3600; String resume = null; int i = 0; while (i < args.length && args[i].startsWith("-")) { if (args[i].equals("-v")) { verbose = !verbose; } else if (args[i].equals("-e")) { check = !check; } else if (args[i].equals("-i")) { checkpointInterval = Integer.parseInt(args[++i]); } else if (args[i].equals("-r")) { resume = args[++i]; } else { usage(); } ++i; } if (args.length <= i) { usage(); } final int k = Integer.parseInt(args[i]); final Writer output; if (args.length > i + 1) { output = new FileWriter(args[i + 1]); } else { output = new OutputStreamWriter(System.out); } int countGood = 0; int countAmbiguous = 0; final Stopwatch timer = new Stopwatch(); final Stopwatch eTestTimer = new Stopwatch(); timer.start(); output.write("# Program FrankKasper with k = " + k + ".\n"); output.write("# Options:\n"); output.write("# verbose mode: "); output.write((verbose ? "on" : "off") + "\n"); output.write("# euclidicity test: "); output.write((check ? "on" : "off") + "\n"); output.write("# checkpoint interval: "); output.write(checkpointInterval + "sec\n"); if (resume != null) { output.write(String.format("# Resuming at %s.\n", resume)); } output.write("\n"); output.flush(); final FrankKasper iter = new FrankKasper(k, verbose); final Stopwatch chkptTimer = new Stopwatch(); final int interval = 1000 * checkpointInterval; iter.addEventLink(CheckpointEvent.class, new EventProcessor() { @Override public void handleEvent(final Object event) { if (((CheckpointEvent) event).getMessage() != null || chkptTimer.elapsed() > interval) { chkptTimer.reset(); try { output.write(event + "\n"); output.flush(); } catch (Throwable ex) { } } } }); chkptTimer.start(); if (resume != null) { iter.setResumePoint(resume); } for (final DSymbol ds : iter) { final DSymbol out = ds.dual(); if (check) { eTestTimer.start(); EuclidicityTester tester = new EuclidicityTester(out); final boolean bad = tester.isBad(); final boolean ambiguous = tester.isAmbiguous(); eTestTimer.stop(); if (!bad) { if (ambiguous) { output.write("#@ name euclidicity dubious\n"); ++countAmbiguous; } output.write(out + "\n"); ++countGood; } } else { output.write(out + "\n"); } output.flush(); } timer.stop(); output.write("\n"); output.write("# Total execution time in user mode was " + timer.format() + ".\n"); if (check) { output.write("# Time for euclidicity tests was " + eTestTimer.format() + ".\n"); } output.write("\n"); output.write("# " + iter.statistics() + "\n"); if (check) { output.write("# Of those, " + countGood + " were found euclidean.\n"); if (countAmbiguous > 0) { output.write("# For " + countAmbiguous + " symbols, euclidicity remains undetermined.\n"); } } output.flush(); } catch (final Exception ex) { ex.printStackTrace(System.err); } } }
9242e19dba11444e4960ed696f1282f74599644b
4,172
java
Java
imooc_treeview/src/main/java/utils/TreeHelper.java
xiaobao-zhaoyiyang/AllmyTest
43f54c995d25700842cfc426a221c0ce58c9ceae
[ "Apache-2.0" ]
null
null
null
imooc_treeview/src/main/java/utils/TreeHelper.java
xiaobao-zhaoyiyang/AllmyTest
43f54c995d25700842cfc426a221c0ce58c9ceae
[ "Apache-2.0" ]
null
null
null
imooc_treeview/src/main/java/utils/TreeHelper.java
xiaobao-zhaoyiyang/AllmyTest
43f54c995d25700842cfc426a221c0ce58c9ceae
[ "Apache-2.0" ]
null
null
null
28.575342
118
0.495686
1,002,449
package utils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import annotation.TreeNodeId; import annotation.TreeNodeLabel; import annotation.TreeNodePid; import yeeaoo.imooc_treeview.R; /** * Created by yo on 2016/4/26. */ public class TreeHelper { /** * 将用户的数据转化为树形数据 * @param datas * @param <T> * @return */ public static <T> List<Node> convertDatas2Nodes(List<T> datas) throws IllegalAccessException { List<Node> nodes = new ArrayList<>(); Node node = null; for (T t:datas) { int id = -1; int pid = -1; String label = null; node = new Node(); Class clazz = t.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field:fields) { if(field.getAnnotation(TreeNodeId.class) != null){ field.setAccessible(true); id = field.getInt(t); } if(field.getAnnotation(TreeNodePid.class) != null){ field.setAccessible(true); pid = field.getInt(t); } if(field.getAnnotation(TreeNodeLabel.class) != null){ field.setAccessible(true); label = (String) field.get(t); } } node = new Node(id, pid, label); nodes.add(node); } /** * 设置Node间的节点关系 */ for (int i = 0; i < nodes.size(); i ++){ Node n = nodes.get(i); for (int j = i + 1; j < nodes.size(); j ++){ Node m = nodes.get(j); if (m.getpId() == n.getId()){ n.getChildren().add(m); m.setParent(n); }else if (m.getId() == n.getpId()){ m.getChildren().add(n); n.setParent(m); } } } for (Node n : nodes){ setNodeIcon(n); } return nodes; } public static <T> List<Node> getSortedNodes(List<T> datas, int defaultExpandLevel) throws IllegalAccessException { List<Node> result = new ArrayList<>(); List<Node> nodes = convertDatas2Nodes(datas); // 获得树的根节点 List<Node> rootNodes = getRootNodes(nodes); for (Node node : rootNodes){ addNode(result, node, defaultExpandLevel, 1); } return result; } /** * 把一个节点的所有孩子节点都放入result * @param result * @param node * @param defaultExpandLevel * @param currentLevel */ private static void addNode(List<Node> result, Node node, int defaultExpandLevel, int currentLevel) { result.add(node); if (defaultExpandLevel >= currentLevel){ node.setExpand(true); } if (node.isLeaf())return; for (int i = 0; i < node.getChildren().size(); i ++){ addNode(result, node.getChildren().get(i), defaultExpandLevel, currentLevel + 1); } } /** * 过滤出需要显示的 * @param nodes * @return */ public static List<Node> filterVisibleNodes(List<Node> nodes){ List<Node> result = new ArrayList<>(); for (Node node : nodes){ if (node.isRoot() || node.isParentExpand()){ setNodeIcon(node); result.add(node); } } return result; } /** * 从所有节点中过滤分节点 * @param nodes * @return */ private static List<Node> getRootNodes(List<Node> nodes) { List<Node> root = new ArrayList<>(); for (Node node : nodes){ if (node.isRoot()){ root.add(node); } } return root; } /** * 为Node设置图标 * @param n */ private static void setNodeIcon(Node n) { if (n.getChildren().size() > 0 && n.isExpand()){ n.setIcon(R.mipmap.tree_ex); }else if (n.getChildren().size() > 0 && !n.isExpand()){ n.setIcon(R.mipmap.tree_ec); }else{ n.setIcon(-1); } } }
9242e1a3e9b3d2acbfd78d1c79c13a4309d8eda3
2,393
java
Java
src/main/generated/io/vertx/kafka/client/common/KafkaClientOptionsConverter.java
juliantcook/vertx-kafka-client
dd367c0062de15c2139b395b7f7f5f2101c62ccb
[ "Apache-2.0" ]
73
2017-02-12T10:14:26.000Z
2022-02-17T09:43:45.000Z
src/main/generated/io/vertx/kafka/client/common/KafkaClientOptionsConverter.java
juliantcook/vertx-kafka-client
dd367c0062de15c2139b395b7f7f5f2101c62ccb
[ "Apache-2.0" ]
167
2016-12-21T15:30:40.000Z
2022-02-28T15:38:45.000Z
src/main/generated/io/vertx/kafka/client/common/KafkaClientOptionsConverter.java
juliantcook/vertx-kafka-client
dd367c0062de15c2139b395b7f7f5f2101c62ccb
[ "Apache-2.0" ]
78
2016-12-03T11:19:57.000Z
2022-03-20T00:38:30.000Z
36.815385
154
0.658588
1,002,450
package io.vertx.kafka.client.common; import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonArray; import io.vertx.core.json.impl.JsonUtil; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.Base64; /** * Converter and mapper for {@link io.vertx.kafka.client.common.KafkaClientOptions}. * NOTE: This class has been automatically generated from the {@link io.vertx.kafka.client.common.KafkaClientOptions} original class using Vert.x codegen. */ public class KafkaClientOptionsConverter { private static final Base64.Decoder BASE64_DECODER = JsonUtil.BASE64_DECODER; private static final Base64.Encoder BASE64_ENCODER = JsonUtil.BASE64_ENCODER; public static void fromJson(Iterable<java.util.Map.Entry<String, Object>> json, KafkaClientOptions obj) { for (java.util.Map.Entry<String, Object> member : json) { switch (member.getKey()) { case "config": if (member.getValue() instanceof JsonObject) { java.util.Map<String, java.lang.Object> map = new java.util.LinkedHashMap<>(); ((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> { if (entry.getValue() instanceof Object) map.put(entry.getKey(), entry.getValue()); }); obj.setConfig(map); } break; case "tracePeerAddress": if (member.getValue() instanceof String) { obj.setTracePeerAddress((String)member.getValue()); } break; case "tracingPolicy": if (member.getValue() instanceof String) { obj.setTracingPolicy(io.vertx.core.tracing.TracingPolicy.valueOf((String)member.getValue())); } break; } } } public static void toJson(KafkaClientOptions obj, JsonObject json) { toJson(obj, json.getMap()); } public static void toJson(KafkaClientOptions obj, java.util.Map<String, Object> json) { if (obj.getConfig() != null) { JsonObject map = new JsonObject(); obj.getConfig().forEach((key, value) -> map.put(key, value)); json.put("config", map); } if (obj.getTracePeerAddress() != null) { json.put("tracePeerAddress", obj.getTracePeerAddress()); } if (obj.getTracingPolicy() != null) { json.put("tracingPolicy", obj.getTracingPolicy().name()); } } }
9242e1a99131b2b6228dbfe510f72f77c889f6fb
775
java
Java
src/main/java/io/remedymatch/artikel/controller/NeuesArtikelRO.java
JacobRoe/rm-backend
914378d95531129ab61be751c90b9ec32ab8d448
[ "Apache-2.0" ]
9
2020-03-30T21:04:28.000Z
2022-01-07T12:41:03.000Z
src/main/java/io/remedymatch/artikel/controller/NeuesArtikelRO.java
JacobRoe/rm-backend
914378d95531129ab61be751c90b9ec32ab8d448
[ "Apache-2.0" ]
21
2020-03-21T17:22:50.000Z
2020-06-02T21:13:53.000Z
src/main/java/io/remedymatch/artikel/controller/NeuesArtikelRO.java
JacobRoe/rm-backend
914378d95531129ab61be751c90b9ec32ab8d448
[ "Apache-2.0" ]
6
2020-03-21T11:30:04.000Z
2020-05-31T19:41:34.000Z
18.902439
67
0.816774
1,002,451
package io.remedymatch.artikel.controller; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @NoArgsConstructor @AllArgsConstructor @Getter @Setter @ToString @EqualsAndHashCode @Builder class NeuesArtikelRO { @NotNull @Valid private UUID artikelKategorieId; @NotBlank private String name; @NotBlank private String beschreibung; @Valid @Builder.Default private List<NeueArtikelVarianteRO> varianten = new ArrayList<>(); }
9242e206bfb119e2d1c1dabc7670c7563c5ac337
9,077
java
Java
src/com/github/_josephcw/hiddenlorax/configmanager/SimpleConfigManager.java
JosephCW/PluginHiddenLorax
c809b95cf6ed110d7b00a5eff12ebe62aea44092
[ "MIT" ]
2
2016-10-30T18:50:01.000Z
2018-08-19T16:32:56.000Z
src/com/github/_josephcw/hiddenlorax/configmanager/SimpleConfigManager.java
JosephCW/PluginHiddenLorax
c809b95cf6ed110d7b00a5eff12ebe62aea44092
[ "MIT" ]
10
2016-10-30T17:45:02.000Z
2020-06-18T16:23:27.000Z
src/com/github/_josephcw/hiddenlorax/configmanager/SimpleConfigManager.java
JosephCW/PluginHiddenLorax
c809b95cf6ed110d7b00a5eff12ebe62aea44092
[ "MIT" ]
1
2019-06-25T19:32:08.000Z
2019-06-25T19:32:08.000Z
26.386628
115
0.489038
1,002,452
package com.github._josephcw.hiddenlorax.configmanager; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.bukkit.plugin.java.JavaPlugin; public class SimpleConfigManager { private JavaPlugin plugin; /* * Manage custom configurations and files */ public SimpleConfigManager(JavaPlugin plugin) { this.plugin = plugin; } /* * Get new configuration with header * @param filePath - Path to file * @return - New SimpleConfig */ public SimpleConfig getNewConfig(String filePath, String[] header) { File file = this.getConfigFile(filePath); if(!file.exists()) { this.prepareFile(filePath); if(header != null && header.length != 0) { this.setHeader(file, header); } } SimpleConfig config = new SimpleConfig(file, this.getCommentsNum(file), plugin); return config; } /* * Get new configuration * @param filePath - Path to file * @return - New SimpleConfig */ public SimpleConfig getNewConfig(String filePath) { return this.getNewConfig(filePath, null); } /* * Get configuration file from string * @param file - File path * @return - New file object */ private File getConfigFile(String file) { if(file.isEmpty() || file == null) { return null; } File configFile; if(file.contains("/")) { if(file.startsWith("/")) { configFile = new File(plugin.getDataFolder() + file.replace("/", File.separator)); } else { configFile = new File(plugin.getDataFolder() + File.separator + file.replace("/", File.separator)); } } else { configFile = new File(plugin.getDataFolder(), file); } return configFile; } /* * Create new file for config and copy resource into it * @param file - Path to file * @param resource - Resource to copy */ public void prepareFile(String filePath, String resource) { File file = this.getConfigFile(filePath); if(file.exists()) { return; } try { file.getParentFile().mkdirs(); file.createNewFile(); if(resource != null && !resource.isEmpty()) { this.copyResource(plugin.getResource(resource), file); } } catch (Exception e) { e.printStackTrace(); } } /* * Create new file for config without resource * @param file - File to create */ public void prepareFile(String filePath) { this.prepareFile(filePath, null); } /* * Adds header block to config * @param file - Config file * @param header - Header lines */ public void setHeader(File file, String[] header) { if(!file.exists()) { return; } try { String currentLine; StringBuilder config = new StringBuilder(""); BufferedReader reader = new BufferedReader(new FileReader(file)); while((currentLine = reader.readLine()) != null) { config.append(currentLine + "\n"); } reader.close(); config.append("# +----------------------------------------------------+ #\n"); for(String line : header) { if(line.length() > 50) { continue; } int lenght = (50 - line.length()) / 2; StringBuilder finalLine = new StringBuilder(line); for(int i = 0; i < lenght; i++) { finalLine.append(" "); finalLine.reverse(); finalLine.append(" "); finalLine.reverse(); } if(line.length() % 2 != 0) { finalLine.append(" "); } config.append("# < " + finalLine.toString() + " > #\n"); } config.append("# +----------------------------------------------------+ #"); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(this.prepareConfigString(config.toString())); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } /* * Read file and make comments SnakeYAML friendly * @param filePath - Path to file * @return - File as Input Stream */ public File getConfigContent(File file) { if(!file.exists()) { return null; } return file; } /* * Get comments from file * @param file - File * @return - Comments number */ private int getCommentsNum(File file) { if(!file.exists()) { return 0; } try { int comments = 0; String currentLine; BufferedReader reader = new BufferedReader(new FileReader(file)); while((currentLine = reader.readLine()) != null) { if(currentLine.startsWith("#")) { comments++; } } reader.close(); return comments; } catch (IOException e) { e.printStackTrace(); return 0; } } /* * Get config content from file * @param filePath - Path to file * @return - readied file */ public File getConfigContent(String filePath) { return new File(filePath); } private String prepareConfigString(String configString) { int lastLine = 0; int headerLine = 0; String[] lines = configString.split("\n"); StringBuilder config = new StringBuilder(""); for(String line : lines) { if(line.startsWith(this.getPluginName() + "_COMMENT")) { String comment = "#" + line.trim().substring(line.indexOf(":") + 1); if(comment.startsWith("# +-")) { /* * If header line = 0 then it is * header start, if it's equal * to 1 it's the end of header */ if(headerLine == 0) { config.append(comment + "\n"); lastLine = 0; headerLine = 1; } else if(headerLine == 1) { config.append(comment + "\n\n"); lastLine = 0; headerLine = 0; } } else { /* * Last line = 0 - Comment * Last line = 1 - Normal path */ String normalComment; if(comment.startsWith("# ' ")) { normalComment = comment.substring(0, comment.length() - 1).replaceFirst("# ' ", "# "); } else { normalComment = comment; } if(lastLine == 0) { config.append(normalComment + "\n"); } else if(lastLine == 1) { config.append("\n" + normalComment + "\n"); } lastLine = 0; } } else { config.append(line + "\n"); lastLine = 1; } } return config.toString(); } /* * Saves configuration to file * @param configString - Config string * @param file - Config file */ public void saveConfig(String configString, File file) { String configuration = this.prepareConfigString(configString); try { BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(configuration); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public String getPluginName() { return plugin.getDescription().getName(); } /* * Copy resource from Input Stream to file * @param resource - Resource from .jar * @param file - File to write */ private void copyResource(InputStream resource, File file) { try { OutputStream out = new FileOutputStream(file); int lenght; byte[] buf = new byte[1024]; while((lenght = resource.read(buf)) > 0){ out.write(buf, 0, lenght); } out.close(); resource.close(); } catch (Exception e) { e.printStackTrace(); } } }
9242e456313d15c64ef4789869e13362ae65f1f2
5,739
java
Java
src/test/java/it/firegloves/mempoi/manager/FileManagerTest.java
zaplatynski/MemPOI
10366dab427e98a987e0616c050c22a81fefe5fa
[ "MIT" ]
null
null
null
src/test/java/it/firegloves/mempoi/manager/FileManagerTest.java
zaplatynski/MemPOI
10366dab427e98a987e0616c050c22a81fefe5fa
[ "MIT" ]
null
null
null
src/test/java/it/firegloves/mempoi/manager/FileManagerTest.java
zaplatynski/MemPOI
10366dab427e98a987e0616c050c22a81fefe5fa
[ "MIT" ]
null
null
null
31.707182
119
0.559331
1,002,453
/** * created by firegloves */ package it.firegloves.mempoi.manager; import it.firegloves.mempoi.config.WorkbookConfig; import it.firegloves.mempoi.exception.MempoiException; import it.firegloves.mempoi.testutil.PrivateAccessHelper; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertNotNull; public class FileManagerTest { private FileManager fileManager; private WorkbookConfig wbConfig; @Mock private Workbook wb; @Before public void prepare() { this.wbConfig = new WorkbookConfig().setWorkbook(new SXSSFWorkbook()); this.fileManager = new FileManager(this.wbConfig); } /****************************************************************************************************************** * writeFile *****************************************************************************************************************/ @Test public void writeFileTest() { File file = new File("temp.xlsx"); this.fileManager.createFinalFile(file); Assert.assertTrue("file generated", file.exists()); file.delete(); } @Test(expected = MempoiException.class) public void writeFileTest_nullWorkbook() { new FileManager(new WorkbookConfig()).createFinalFile(new File("/not_existing/temp.xlsx")); } @Test(expected = MempoiException.class) public void writeFileTest_invalidFilePath() throws Throwable { this.fileManager.createFinalFile(new File("/not_existing/temp.xlsx")); } @Test(expected = MempoiException.class) public void writeFileTest_invalidFilePathAndNullWorkbook() { this.fileManager.createFinalFile(new File("/not_existing/temp.xlsx")); } @Test(expected = MempoiException.class) public void writeFileTest_errorWriting() throws Throwable { try { MockitoAnnotations.initMocks(this); Mockito.doThrow(new RuntimeException()).when(wb).write(Mockito.any()); FileManager fileManager = new FileManager(new WorkbookConfig().setWorkbook(wb)); fileManager.createFinalFile(new File("temp.xlsx")); } catch (Exception e) { throw e.getCause(); } } /****************************************************************************************************************** * writeTempFile *****************************************************************************************************************/ @Test public void writeTempFile() { File file = this.fileManager.writeTempFile(); Assert.assertNotNull("file not null", file); Assert.assertTrue("file exists", file.exists()); } /****************************************************************************************************************** * writeToByteArray *****************************************************************************************************************/ @Test public void writeToByteArray() throws Exception { Method m = PrivateAccessHelper.getAccessibleMethod(FileManager.class, "writeToByteArray"); Object o = m.invoke(this.fileManager); assertNotNull("not null", o); assertThat("instance of byte[]", o, instanceOf(byte[].class)); byte[] bytes = (byte[]) o; assertThat("byte array not empty", bytes.length, greaterThan(0)); } @Test(expected = InvocationTargetException.class) public void writeToByteArrayNullWorkbook() throws Exception { FileManager fileManager = new FileManager(new WorkbookConfig()); Method m = PrivateAccessHelper.getAccessibleMethod(FileManager.class, "writeToByteArray"); m.invoke(fileManager); } /****************************************************************************************************************** * close workbook *****************************************************************************************************************/ @Test public void closeWorkbook() throws Exception { Method m = PrivateAccessHelper.getAccessibleMethod(FileManager.class, "closeWorkbook"); m.invoke(this.fileManager); } @Test(expected = MempoiException.class) public void closeWorkbookNullWorkbook() throws Throwable { FileManager fileManager = new FileManager(new WorkbookConfig()); Method m = PrivateAccessHelper.getAccessibleMethod(FileManager.class, "closeWorkbook"); try { m.invoke(fileManager); } catch (Exception e) { throw e.getCause(); } } @Test(expected = MempoiException.class) public void closeWorkbookErrorClosing() throws Throwable { MockitoAnnotations.initMocks(this); Mockito.doThrow(new RuntimeException()).when(wb).close(); FileManager fileManager = new FileManager(new WorkbookConfig().setWorkbook(wb)); Method m = PrivateAccessHelper.getAccessibleMethod(FileManager.class, "closeWorkbook"); try { m.invoke(fileManager); } catch (Exception e) { throw e.getCause(); } } }
9242e47a0883bb3ba3d75bc5f45197968cae3f36
19,752
java
Java
library/src/main/java/it/gmariotti/cardslib/library/view/listener/SwipeDismissListViewTouchListener.java
aminelaadhari/cardslib
7b058c6329a5643c6bae8b0ee09dc56441ac64c0
[ "Apache-2.0" ]
null
null
null
library/src/main/java/it/gmariotti/cardslib/library/view/listener/SwipeDismissListViewTouchListener.java
aminelaadhari/cardslib
7b058c6329a5643c6bae8b0ee09dc56441ac64c0
[ "Apache-2.0" ]
null
null
null
library/src/main/java/it/gmariotti/cardslib/library/view/listener/SwipeDismissListViewTouchListener.java
aminelaadhari/cardslib
7b058c6329a5643c6bae8b0ee09dc56441ac64c0
[ "Apache-2.0" ]
null
null
null
40.47541
124
0.571588
1,002,454
/* * ****************************************************************************** * Copyright (c) 2013 Roman Nurik, 2013-2014 Gabriele Mariotti. * * 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 it.gmariotti.cardslib.library.view.listener; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.animation.ValueAnimator; import com.nineoldandroids.view.ViewHelper; import static com.nineoldandroids.view.ViewPropertyAnimator.animate; import android.graphics.Rect; import android.os.Build; import android.os.SystemClock; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewPropertyAnimator; import android.widget.AbsListView; import android.widget.ListView; import java.util.ArrayList; import java.util.Collections; import java.util.List; import it.gmariotti.cardslib.library.internal.Card; import static com.nineoldandroids.view.ViewPropertyAnimator.animate; /** * It is based on Roman Nurik code. * See this link for original code https://github.com/romannurik/Android-SwipeToDismiss * </p> * It provides a SwipeDismissViewTouchListener for a CardList. * </p> * * A {@link View.OnTouchListener} that makes the list items in a {@link ListView} * dismissable. {@link ListView} is given special treatment because by default it handles touches * for its list items... i.e. it's in charge of drawing the pressed state (the list selector), * handling list item clicks, etc. * * <p>After creating the listener, the caller should also call * {@link ListView#setOnScrollListener(AbsListView.OnScrollListener)}, using a * {@link it.gmariotti.cardslib.library.view.listener.SwipeOnScrollListener}. * * If a scroll listener is already assigned, the caller should still pass scroll changes through to this listener. This will * ensure that this {@link SwipeDismissListViewTouchListener} is paused during list view * scrolling.</p> * * <p>Example usage:</p> * * <pre> * SwipeDismissListViewTouchListener touchListener = * new SwipeDismissListViewTouchListener( * listView, * new SwipeDismissListViewTouchListener.OnDismissCallback() { * public void onDismiss(ListView listView, int[] reverseSortedPositions) { * for (int position : reverseSortedPositions) { * adapter.remove(adapter.getItem(position)); * } * adapter.notifyDataSetChanged(); * } * }); * listView.setOnTouchListener(touchListener); * listView.setOnScrollListener(touchListener.makeScrollListener()); * </pre> * * <p>This class Requires API level 12 or later due to use of {@link * ViewPropertyAnimator}.</p> * */ public class SwipeDismissListViewTouchListener implements View.OnTouchListener { // Cached ViewConfiguration and system-wide constant values private int mSlop; private int mMinFlingVelocity; private int mMaxFlingVelocity; private long mAnimationTime; // Fixed properties private ListView mListView; private DismissCallbacks mCallbacks; private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero // Transient properties private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>(); private int mDismissAnimationRefCount = 0; private float mDownX; private float mDownY; private boolean mSwiping; private int mSwipingSlop; private VelocityTracker mVelocityTracker; private int mDownPosition; private View mDownView; private boolean mPaused; /** * The callback interface used by {@link SwipeDismissListViewTouchListener} to inform its client * about a successful dismissal of one or more list item positions. */ public interface DismissCallbacks { /** * Called to determine whether the given position can be dismissed. */ boolean canDismiss(int position,Card card); /** * Called when the user has indicated they she would like to dismiss one or more list item * positions. * * @param listView The originating {@link ListView}. * @param reverseSortedPositions An array of positions to dismiss, sorted in descending * order for convenience. */ void onDismiss(ListView listView, int[] reverseSortedPositions, boolean dismissRight); } /** * Constructs a new swipe-to-dismiss touch listener for the given list view. * * @param listView The list view whose items should be dismissable. * @param callbacks The callback to trigger when the user has indicated that she would like to * dismiss one or more list items. */ public SwipeDismissListViewTouchListener(ListView listView, DismissCallbacks callbacks) { ViewConfiguration vc = ViewConfiguration.get(listView.getContext()); mSlop = vc.getScaledTouchSlop(); mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16; mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); mAnimationTime = listView.getContext().getResources().getInteger( android.R.integer.config_shortAnimTime); mListView = listView; mCallbacks = callbacks; } /** * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures. * * @param enabled Whether or not to watch for gestures. */ public void setEnabled(boolean enabled) { mPaused = !enabled; } /** * Returns an {@link AbsListView.OnScrollListener} to be added to the {@link * ListView} using {@link ListView#setOnScrollListener(AbsListView.OnScrollListener)}. * If a scroll listener is already assigned, the caller should still pass scroll changes through * to this listener. This will ensure that this {@link SwipeDismissListViewTouchListener} is * paused during list view scrolling.</p> * * @see SwipeDismissListViewTouchListener */ /* public AbsListView.OnScrollListener makeScrollListener() { return new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int scrollState) { setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); } @Override public void onScroll(AbsListView absListView, int i, int i1, int i2) { } }; }*/ @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (mViewWidth < 2) { mViewWidth = mListView.getWidth(); } switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (mPaused) { return false; } if (mSwiping){ return true; } // TODO: ensure this is a finger, and set a flag // Find the child view that was touched (perform a hit test) Rect rect = new Rect(); int childCount = mListView.getChildCount(); int headerCount = mListView.getHeaderViewsCount(); int footerCount = mListView.getFooterViewsCount(); int[] listViewCoords = new int[2]; mListView.getLocationOnScreen(listViewCoords); int x = (int) motionEvent.getRawX() - listViewCoords[0]; int y = (int) motionEvent.getRawY() - listViewCoords[1]; View child=null; for (int i = headerCount; i < (childCount - footerCount); i++) { child = mListView.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { mDownView = child; break; } } if (mDownView != null) { mDownX = motionEvent.getRawX(); mDownY = motionEvent.getRawY(); mDownPosition = mListView.getPositionForView(mDownView); if (mCallbacks.canDismiss(mDownPosition,(Card) mListView.getAdapter().getItem(mDownPosition))) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(motionEvent); } else { mDownView = null; } } view.onTouchEvent(motionEvent); return true; //return false; } case MotionEvent.ACTION_UP: { if (mVelocityTracker == null) { break; } float deltaX = motionEvent.getRawX() - mDownX; mVelocityTracker.addMovement(motionEvent); mVelocityTracker.computeCurrentVelocity(1000); float velocityX = mVelocityTracker.getXVelocity(); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) { dismiss = true; dismissRight = deltaX > 0; } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX && mSwiping && isDirectionValid(mVelocityTracker.getXVelocity())) { // dismiss only if flinging in the same direction as dragging dismiss = (velocityX < 0) == (deltaX < 0); dismissRight = mVelocityTracker.getXVelocity() > 0; } if (dismiss && mDownPosition != ListView.INVALID_POSITION) { // dismiss dismiss(mDownView, mDownPosition, dismissRight); } else { // cancel animate(mDownView) .translationX(0) .alpha(1) .setDuration(mAnimationTime) .setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownY = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; if (mSwiping){ //To prevent onClick event with a fast swipe mSwiping = false; return true; } mSwiping = false; break; } case MotionEvent.ACTION_CANCEL: { if (mVelocityTracker == null) { break; } if (mDownView != null) { // cancel animate(mDownView) .translationX(0) .alpha(1) .setDuration(mAnimationTime) .setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownY = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_MOVE: { if (mVelocityTracker == null || mPaused) { break; } mVelocityTracker.addMovement(motionEvent); float deltaX = motionEvent.getRawX() - mDownX; float deltaY = motionEvent.getRawY() - mDownY; if (isDirectionValid(deltaX)) { if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) { mSwiping = true; mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop); mListView.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mListView.onTouchEvent(cancelEvent); view.onTouchEvent(cancelEvent); cancelEvent.recycle(); } } else { // If we swiped into wrong direction, act like this was the new // touch down point mDownX = motionEvent.getRawX(); deltaX = 0; } if (mSwiping) { ViewHelper.setTranslationX(mDownView, deltaX - mSwipingSlop); ViewHelper.setAlpha(mDownView, Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } break; } } return false; } /** * Checks whether the delta of a swipe indicates, that the swipe is in the * correct direction, regarding the direction set via * * @param deltaX The delta of x coordinate of the swipe. * @return Whether the delta of a swipe is in the right direction. */ private boolean isDirectionValid(float deltaX) { Card card = (Card) mListView.getAdapter().getItem(mDownPosition); int rtlSign = 1; // On API level 17 and above, check if we are in a Right-To-Left layout if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { if(mListView.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) { rtlSign = -1; } } // Check if swipe has been done in the corret direction switch(card.getSwipeDirection()) { default: case BOTH: return true; case START: return rtlSign * deltaX < 0; case END: return rtlSign * deltaX > 0; } } private void dismiss(final View view, final int position, final boolean dismissRight) { ++mDismissAnimationRefCount; if (view == null) { // No view, shortcut to calling onDismiss to let it deal with adapter // updates and all that. mCallbacks.onDismiss(mListView, new int[] { position }, dismissRight); return; } animate(view) .translationX(dismissRight ? mViewWidth : -mViewWidth) .alpha(0) .setDuration(mAnimationTime) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(view, position, dismissRight); } }); } class PendingDismissData implements Comparable<PendingDismissData> { public int position; public View view; public PendingDismissData(int position, View view) { this.position = position; this.view = view; } @Override public int compareTo(PendingDismissData other) { // Sort by descending position return other.position - position; } } private void performDismiss(final View dismissView, final int dismissPosition, final boolean dismissRight) { // Animate the dismissed list item to zero-height and fire the dismiss callback when // all dismissed list item animations have completed. This triggers layout on each animation // frame; in the future we may want to do something smarter and more performant. final ViewGroup.LayoutParams lp = dismissView.getLayoutParams(); final int originalHeight = dismissView.getHeight(); ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { --mDismissAnimationRefCount; if (mDismissAnimationRefCount == 0) { // No active animations, process all pending dismisses. // Sort by descending position Collections.sort(mPendingDismisses); int[] dismissPositions = new int[mPendingDismisses.size()]; for (int i = mPendingDismisses.size() - 1; i >= 0; i--) { dismissPositions[i] = mPendingDismisses.get(i).position; } mCallbacks.onDismiss(mListView, dismissPositions, dismissRight); // Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss // animation with a stale position mDownPosition = ListView.INVALID_POSITION; ViewGroup.LayoutParams lp; for (PendingDismissData pendingDismiss : mPendingDismisses) { // Reset view presentation ViewHelper.setAlpha(pendingDismiss.view, 1f); ViewHelper.setTranslationX(pendingDismiss.view, 0); lp = pendingDismiss.view.getLayoutParams(); lp.height = 0; pendingDismiss.view.setLayoutParams(lp); } // Send a cancel event long time = SystemClock.uptimeMillis(); MotionEvent cancelEvent = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0, 0, 0); mListView.dispatchTouchEvent(cancelEvent); mPendingDismisses.clear(); } } }); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { lp.height = (Integer) valueAnimator.getAnimatedValue(); dismissView.setLayoutParams(lp); } }); mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView)); animator.start(); } }
9242e4b818c4f1ec4cd3940298121937cdc998ca
1,470
java
Java
HackerRank/30 Days of Code/Day 22- Binary Search Trees/Solution.java
stefant29/interview-problems
f7195618905bb17e99e958df7acbd3153a1aec47
[ "MIT" ]
null
null
null
HackerRank/30 Days of Code/Day 22- Binary Search Trees/Solution.java
stefant29/interview-problems
f7195618905bb17e99e958df7acbd3153a1aec47
[ "MIT" ]
null
null
null
HackerRank/30 Days of Code/Day 22- Binary Search Trees/Solution.java
stefant29/interview-problems
f7195618905bb17e99e958df7acbd3153a1aec47
[ "MIT" ]
null
null
null
26.727273
76
0.516327
1,002,455
import java.util.*; import java.io.*; // https://www.hackerrank.com/challenges/30-binary-search-trees class Node{ Node left,right; int data; Node(int data){ this.data=data; left=right=null; } } class Solution{ /* wrapper for computing the height of a tree */ public static int getHeight(Node root){ return (root == null) ? 0 : Math.max(getHeightRec(root.right), getHeightRec(root.left)); } /* recursive method to compute the height of a tree */ public static int getHeightRec(Node root) { return (root == null) ? 0 : 1 + Math.max(getHeightRec(root.right), getHeightRec(root.left)); } public static Node insert(Node root,int data){ if(root==null){ return new Node(data); } else{ Node cur; if(data<=root.data){ cur=insert(root.left,data); root.left=cur; } else{ cur=insert(root.right,data); root.right=cur; } return root; } } public static void main(String args[]){ Scanner sc=new Scanner(System.in); int T=sc.nextInt(); Node root=null; while(T-->0){ int data=sc.nextInt(); root=insert(root,data); } int height=getHeight(root); System.out.println(height); } }
9242e4d489eead88bf431eb7fbd5e22cba98c1e6
1,925
java
Java
work/decompile-e0c6d16a/net/minecraft/world/level/block/BlockWorkbench.java
jacobo-mc/spigot_1.18
03d238eebaeab66357e75987e8fb4403e0c85960
[ "MIT" ]
null
null
null
work/decompile-e0c6d16a/net/minecraft/world/level/block/BlockWorkbench.java
jacobo-mc/spigot_1.18
03d238eebaeab66357e75987e8fb4403e0c85960
[ "MIT" ]
null
null
null
work/decompile-e0c6d16a/net/minecraft/world/level/block/BlockWorkbench.java
jacobo-mc/spigot_1.18
03d238eebaeab66357e75987e8fb4403e0c85960
[ "MIT" ]
null
null
null
42.777778
200
0.782338
1,002,456
package net.minecraft.world.level.block; import net.minecraft.core.BlockPosition; import net.minecraft.network.chat.ChatMessage; import net.minecraft.network.chat.IChatBaseComponent; import net.minecraft.stats.StatisticList; import net.minecraft.world.EnumHand; import net.minecraft.world.EnumInteractionResult; import net.minecraft.world.ITileInventory; import net.minecraft.world.TileInventory; import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.inventory.ContainerAccess; import net.minecraft.world.inventory.ContainerWorkbench; import net.minecraft.world.level.World; import net.minecraft.world.level.block.state.BlockBase; import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.phys.MovingObjectPositionBlock; public class BlockWorkbench extends Block { private static final IChatBaseComponent CONTAINER_TITLE = new ChatMessage("container.crafting"); protected BlockWorkbench(BlockBase.Info blockbase_info) { super(blockbase_info); } @Override public EnumInteractionResult use(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { if (world.isClientSide) { return EnumInteractionResult.SUCCESS; } else { entityhuman.openMenu(iblockdata.getMenuProvider(world, blockposition)); entityhuman.awardStat(StatisticList.INTERACT_WITH_CRAFTING_TABLE); return EnumInteractionResult.CONSUME; } } @Override public ITileInventory getMenuProvider(IBlockData iblockdata, World world, BlockPosition blockposition) { return new TileInventory((i, playerinventory, entityhuman) -> { return new ContainerWorkbench(i, playerinventory, ContainerAccess.create(world, blockposition)); }, BlockWorkbench.CONTAINER_TITLE); } }
9242e504607487112bec07becbe5ff0dc62d5efe
801
java
Java
mi-product/src/main/java/com/dlq/mall/product/service/SkuSaleAttrValueService.java
DLQ666/MI-Mall
33404769fcef007bd644024abc00f5f3790d0535
[ "Apache-2.0" ]
null
null
null
mi-product/src/main/java/com/dlq/mall/product/service/SkuSaleAttrValueService.java
DLQ666/MI-Mall
33404769fcef007bd644024abc00f5f3790d0535
[ "Apache-2.0" ]
null
null
null
mi-product/src/main/java/com/dlq/mall/product/service/SkuSaleAttrValueService.java
DLQ666/MI-Mall
33404769fcef007bd644024abc00f5f3790d0535
[ "Apache-2.0" ]
1
2020-11-24T14:19:46.000Z
2020-11-24T14:19:46.000Z
25.806452
83
0.78
1,002,457
package com.dlq.mall.product.service; import com.baomidou.mybatisplus.extension.service.IService; import com.dlq.common.utils.PageUtils; import com.dlq.mall.product.entity.SkuSaleAttrValueEntity; import com.dlq.mall.product.vo.sku.SkuItemSaleAttrVo; import java.util.List; import java.util.Map; /** * sku销售属性&值 * * @author dlq * @email [email protected] * @date 2020-10-07 18:50:32 */ public interface SkuSaleAttrValueService extends IService<SkuSaleAttrValueEntity> { PageUtils queryPage(Map<String, Object> params); List<SkuItemSaleAttrVo> getSaleAttrsBySpuId(Long spuId); List<String> getSkuSaleAttrValuesAsStringList(Long skuId); /*List<SkuItemSaleAttrVo> getSaleAttrsVersionBySpuId(Long spuId); List<SkuItemSaleAttrVo> getSaleAttrsColorBySpuId(Long spuId);*/ }
9242e52c2a04818321de8928c40e54da0a56c574
3,536
java
Java
maven/ogre-xlanguage/src/main/java/com/berniecode/ogre/enginelib/EntityDiff.java
BernieSumption/OGRE
1bee4fa8414e3c1aa41afcb8bf69c73990a592cc
[ "Unlicense" ]
1
2015-06-15T11:24:44.000Z
2015-06-15T11:24:44.000Z
maven/ogre-xlanguage/src/main/java/com/berniecode/ogre/enginelib/EntityDiff.java
BernieSumption/OGRE
1bee4fa8414e3c1aa41afcb8bf69c73990a592cc
[ "Unlicense" ]
null
null
null
maven/ogre-xlanguage/src/main/java/com/berniecode/ogre/enginelib/EntityDiff.java
BernieSumption/OGRE
1bee4fa8414e3c1aa41afcb8bf69c73990a592cc
[ "Unlicense" ]
null
null
null
38.434783
100
0.745758
1,002,458
/* * Copyright 2011 Bernie Sumption. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. THIS SOFTWARE IS PROVIDED ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package com.berniecode.ogre.enginelib; import com.berniecode.ogre.enginelib.platformhooks.OgreException; import com.berniecode.ogre.enginelib.platformhooks.ValueUtils; /** * Represents an update to a single {@link Entity} * * @author Bernie Sumption */ public class EntityDiff extends EntityValue implements PartialRawPropertyValueSet { private final boolean[] isChanged; public EntityDiff(EntityType entityType, long id, Object[] values, boolean[] isChanged) { super(entityType, id, values); this.isChanged = isChanged; } /** * @return An {@link EntityDiff} object that if applied to the entity <code>from</code> will * change its values to be equal to those of <code>to</code> */ public static EntityDiff build(RawPropertyValueSet from, RawPropertyValueSet to) { EntityType entityType = from.getEntityType(); if (entityType != to.getEntityType()) { throw new OgreException("Can't build an EntityDiff from " + from + " to " + to + " because their entityTypes are different"); } int propertyCount = entityType.getPropertyCount(); Object[] changedValues = new Object[propertyCount]; boolean[] changed = new boolean[propertyCount]; boolean anyChanged = false; for (int i = 0; i < propertyCount; i++) { Property property = entityType.getProperty(i); Object fromValue = from.getRawPropertyValue(property); Object toValue = to.getRawPropertyValue(property); if (!ValueUtils.valuesAreEquivalent(fromValue, toValue)) { changedValues[i] = toValue; changed[i] = true; anyChanged = true; } } if (!anyChanged) { return null; } return new EntityDiff(entityType, from.getEntityId(), changedValues, changed); } /** * @see PartialRawPropertyValueSet#getRawPropertyValue(Property) */ public Object getRawPropertyValue(Property property) { if (!hasUpdatedValue(property)) { throw new OgreException(this + " has no value for " + property); } return super.getRawPropertyValue(property); } /** * @see PartialRawPropertyValueSet#hasUpdatedValue(Property) */ public boolean hasUpdatedValue(Property property) { return isChanged[property.getPropertyIndex()]; } public String toString() { return "partial " + super.toString(); } }
9242e56531ffd85c77883a04a0adf229b51946df
1,200
java
Java
jpizza/src/main/java/lemon/jpizza/compiler/types/objects/MaybeType.java
Blurmit/jpizza
e92b2f4f98f45ffcfbeaf7e578ff0aabc483932a
[ "MIT" ]
null
null
null
jpizza/src/main/java/lemon/jpizza/compiler/types/objects/MaybeType.java
Blurmit/jpizza
e92b2f4f98f45ffcfbeaf7e578ff0aabc483932a
[ "MIT" ]
null
null
null
jpizza/src/main/java/lemon/jpizza/compiler/types/objects/MaybeType.java
Blurmit/jpizza
e92b2f4f98f45ffcfbeaf7e578ff0aabc483932a
[ "MIT" ]
null
null
null
25.531915
72
0.655833
1,002,459
package lemon.jpizza.compiler.types.objects; import lemon.jpizza.TokenType; import lemon.jpizza.compiler.types.Type; import lemon.jpizza.compiler.types.TypeCodes; import lemon.jpizza.compiler.types.primitives.PrimitiveType; public class MaybeType extends PrimitiveType { private final Type optionalType; public MaybeType(Type optionalType) { super("?" + optionalType.toString()); this.optionalType = optionalType; } @Override protected Type operation(TokenType operation, Type other) { return null; } @Override protected Type operation(TokenType operation) { return null; } @Override public int[] dump() { int[] subtype = optionalType.dump(); int[] result = new int[subtype.length + 1]; result[0] = TypeCodes.MAYBE; System.arraycopy(subtype, 0, result, 1, subtype.length); return result; } @Override public boolean equals(Object other) { if (other instanceof MaybeType) { return optionalType.equals(((MaybeType)other).optionalType); } return false; } public Type getOptionalType() { return optionalType; } }
9242e5acc738d150818d6a5539c704795855b3c9
1,398
java
Java
airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftBingAdsOAuthFlowTest.java
asamoal/airbyte
83b9b4fca8087cf3e0b4ba8728c00235b3735e1b
[ "MIT" ]
22
2020-08-27T00:47:20.000Z
2020-09-17T15:39:39.000Z
airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftBingAdsOAuthFlowTest.java
asamoal/airbyte
83b9b4fca8087cf3e0b4ba8728c00235b3735e1b
[ "MIT" ]
116
2020-08-27T01:11:27.000Z
2020-09-19T02:47:52.000Z
airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftBingAdsOAuthFlowTest.java
asamoal/airbyte
83b9b4fca8087cf3e0b4ba8728c00235b3735e1b
[ "MIT" ]
1
2020-09-15T06:10:01.000Z
2020-09-15T06:10:01.000Z
29.125
260
0.775393
1,002,460
/* * Copyright (c) 2022 Airbyte, Inc., all rights reserved. */ package io.airbyte.oauth.flows; import com.fasterxml.jackson.databind.JsonNode; import io.airbyte.commons.json.Jsons; import io.airbyte.oauth.BaseOAuthFlow; import java.util.Map; import org.junit.jupiter.api.Test; public class MicrosoftBingAdsOAuthFlowTest extends BaseOAuthFlowTest { @Override protected BaseOAuthFlow getOAuthFlow() { return new MicrosoftBingAdsOAuthFlow(getConfigRepository(), getHttpClient(), this::getConstantState); } @Override protected String getExpectedConsentUrl() { return "https://login.microsoftonline.com/test_tenant_id/oauth2/v2.0/authorize?client_id=test_client_id&response_type=code&redirect_uri=https%3A%2F%2Fairbyte.io&response_mode=query&state=state&scope=offline_access%20https://ads.microsoft.com/msads.manage"; } @Override protected JsonNode getInputOAuthConfiguration() { return Jsons.jsonNode(Map.of("tenant_id", "test_tenant_id")); } @Override protected JsonNode getUserInputFromConnectorConfigSpecification() { return getJsonSchema(Map.of("tenant_id", Map.of("type", "string"))); } @Test public void testEmptyInputCompleteDestinationOAuth() {} @Test public void testDeprecatedCompleteDestinationOAuth() {} @Test public void testDeprecatedCompleteSourceOAuth() {} @Test public void testEmptyInputCompleteSourceOAuth() {} }
9242e5dbe250a11af6d9b59756e94bace320b176
6,519
java
Java
mobile/IntelligentHouse/app/src/main/java/com/uol/xiaoyang/intelligenthouse/AudioCapture.java
muma378/intelligent_house
f1939fdb65fb694c8d9ab02b74310ad70b04a35f
[ "MIT" ]
null
null
null
mobile/IntelligentHouse/app/src/main/java/com/uol/xiaoyang/intelligenthouse/AudioCapture.java
muma378/intelligent_house
f1939fdb65fb694c8d9ab02b74310ad70b04a35f
[ "MIT" ]
null
null
null
mobile/IntelligentHouse/app/src/main/java/com/uol/xiaoyang/intelligenthouse/AudioCapture.java
muma378/intelligent_house
f1939fdb65fb694c8d9ab02b74310ad70b04a35f
[ "MIT" ]
null
null
null
30.605634
98
0.628164
1,002,461
package com.uol.xiaoyang.intelligenthouse; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.os.AsyncTask; import android.os.SystemClock; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.os.Environment; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Chronometer; import android.util.Log; import android.widget.LinearLayout; import android.util.Base64; import java.io.IOException; import java.io.File; import java.net.URLEncoder; import java.util.Date; import org.apache.commons.io.FileUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class AudioCapture extends ActionBarActivity { private final String TAG = "AudioCapture.java"; private final String STATUS_WORKING = "Recording..."; private final String STATUS_IDLE = "Tap to record"; private Chronometer chronometer; private Button button_record; private MediaRecorder media_recorder; private LinearLayout linear_layout_record; private boolean recording = false; private static String audio_file = null; private long record_duration = 0; public AudioCapture() { audio_file = Environment.getExternalStorageDirectory().getAbsolutePath(); audio_file += "/audiorecord.3gp"; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_audio_capture); chronometer = (Chronometer)findViewById(R.id.chronometer); button_record = (Button)findViewById(R.id.btn_record); linear_layout_record = (LinearLayout) findViewById(R.id.layout_add_record); } public void onRecord(View view){ if(recording == false){ startRecord(); }else { stopRecord(); } } public void startRecord(){ recording = true; //change text on button button_record.setText(STATUS_WORKING); //start timer chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.start(); //start recording media_recorder = new MediaRecorder(); media_recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); media_recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); media_recorder.setOutputFile(audio_file); media_recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try{ media_recorder.prepare(); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "prepare() failed " + e.toString()); } media_recorder.start(); } public void stopRecord(){ recording = false; button_record.setText(STATUS_IDLE); //stop timer chronometer.stop(); record_duration = SystemClock.elapsedRealtime() - chronometer.getBase(); //stop recording media_recorder.stop(); media_recorder.release(); media_recorder = null; //play it MediaPlayer mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(audio_file); mPlayer.prepare(); mPlayer.start(); } catch (IOException e) { Log.e(TAG, "prepare() failed"); } // change visibility button_record.setVisibility(View.GONE); linear_layout_record.setVisibility(View.VISIBLE); } //convert the record to base64, and sent it to the server public void onCommit(View view) { AsyncTaskPutRecord async_task = new AsyncTaskPutRecord(); async_task.execute(); onCancel(view); } public void onCancel(View view){ button_record.setVisibility(View.VISIBLE); linear_layout_record.setVisibility(View.GONE); } // send record to server public class AsyncTaskPutRecord extends AsyncTask<String, String, String> { final String TAG = "AsyncTaskPutRecord.java"; // set the url of the web service to call final String PutRecordSite = MainActivity.Host + "/record"; String put_url; boolean success = false; @Override protected void onPreExecute(){ String E ="UTF-8"; try { File file = new File(audio_file); byte[] bytes = FileUtils.readFileToByteArray(file); String record = Base64.encodeToString(bytes, 0); Date name = new Date(); String parameters = "/1"; parameters += "?data=" + URLEncoder.encode(record, E); parameters += "&name=" + URLEncoder.encode(name.toString(), E); parameters += "&duration=" + URLEncoder.encode(Long.toString(record_duration), E); put_url = PutRecordSite + parameters; } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "Error reading files " + e.toString()); } } @Override protected String doInBackground(String... arg0) { JsonParser jParser = new JsonParser(); JSONObject json = jParser.getJSONFromPut(put_url); try { if (json.getInt("status")==200){ success = true; } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String strFromDoInBg){ if (success){ // TODO: show dialog to alert success or fail }else{ } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_audio_capture, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
9242e79242e1fddf7a9f64d3c006cce688555c1e
1,220
java
Java
Search/src/main/java/org/neuromorpho/literature/search/service/jats/model/fulltext/localtor/OA.java
p-maraver/NeuroMorphoLiterature
f610ca64b5d468335a29d074b4fd3db1c332272d
[ "Apache-2.0" ]
null
null
null
Search/src/main/java/org/neuromorpho/literature/search/service/jats/model/fulltext/localtor/OA.java
p-maraver/NeuroMorphoLiterature
f610ca64b5d468335a29d074b4fd3db1c332272d
[ "Apache-2.0" ]
null
null
null
Search/src/main/java/org/neuromorpho/literature/search/service/jats/model/fulltext/localtor/OA.java
p-maraver/NeuroMorphoLiterature
f610ca64b5d468335a29d074b4fd3db1c332272d
[ "Apache-2.0" ]
null
null
null
27.727273
79
0.716393
1,002,462
/* * Copyright (c) 2015-2022, Patricia Maraver * * 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.neuromorpho.literature.search.service.jats.model.fulltext.localtor; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "OA") @XmlAccessorType(XmlAccessType.FIELD) public class OA { @XmlElement(name = "records") private Records records; public String getLink() { try { return this.records.getLink(); } catch (NullPointerException ex) { return null; } } }
9242e7cb39ce66f2a163d86a80a11adb9091c77f
422
java
Java
parser_core/src/main/java/org/miod/parser/node/MiodNodeType.java
exhu/miod
8dc45155266e120aa6cdc4d46ed510eef772d6cd
[ "MIT" ]
1
2015-11-08T06:21:42.000Z
2015-11-08T06:21:42.000Z
parser_core/src/main/java/org/miod/parser/node/MiodNodeType.java
exhu/miod
8dc45155266e120aa6cdc4d46ed510eef772d6cd
[ "MIT" ]
null
null
null
parser_core/src/main/java/org/miod/parser/node/MiodNodeType.java
exhu/miod
8dc45155266e120aa6cdc4d46ed510eef772d6cd
[ "MIT" ]
null
null
null
17.583333
56
0.670616
1,002,463
/* Copyright 2016 Yury Benesh see COPYING.txt */ package org.miod.parser.node; import org.miod.program.types.MiodType; /** * * @author yur */ public final class MiodNodeType extends MiodNodeData { public final MiodType typespec; public static MiodNodeType newTypespec(MiodType t) { return new MiodNodeType(t); } private MiodNodeType(MiodType t) { this.typespec = t; } }
9242e96ae4e536a16a765df23bee4aceeef5d5ad
127
java
Java
src/main/java/com/example/test/Other/CustomerStatus.java
angry-shark/my-starter-project
a5192a30a7fd0cc9f0254ec8f4dd3ab9fc90cc59
[ "Unlicense" ]
null
null
null
src/main/java/com/example/test/Other/CustomerStatus.java
angry-shark/my-starter-project
a5192a30a7fd0cc9f0254ec8f4dd3ab9fc90cc59
[ "Unlicense" ]
null
null
null
src/main/java/com/example/test/Other/CustomerStatus.java
angry-shark/my-starter-project
a5192a30a7fd0cc9f0254ec8f4dd3ab9fc90cc59
[ "Unlicense" ]
null
null
null
25.4
63
0.795276
1,002,464
package com.example.test.Other; public enum CustomerStatus { ImportedLead, NotContacted, Contacted, Customer, ClosedLost }
9242e9963b56ccbe51348f25e25303761bd1bac9
4,964
java
Java
connectors/amazon/translator-simpledb/src/main/java/org/teiid/translator/simpledb/SimpleDBQueryExecution.java
GavinRay97/teiid
f7ae9acdc372718e15aa9f5827b267dfd68db5a5
[ "Apache-2.0" ]
249
2015-01-04T12:32:56.000Z
2022-03-22T07:00:46.000Z
connectors/amazon/translator-simpledb/src/main/java/org/teiid/translator/simpledb/SimpleDBQueryExecution.java
GavinRay97/teiid
f7ae9acdc372718e15aa9f5827b267dfd68db5a5
[ "Apache-2.0" ]
312
2015-01-06T19:01:51.000Z
2022-03-10T17:49:37.000Z
connectors/amazon/translator-simpledb/src/main/java/org/teiid/translator/simpledb/SimpleDBQueryExecution.java
GavinRay97/teiid
f7ae9acdc372718e15aa9f5827b267dfd68db5a5
[ "Apache-2.0" ]
256
2015-01-06T18:14:39.000Z
2022-03-23T17:55:42.000Z
37.323308
129
0.685334
1,002,465
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * 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.teiid.translator.simpledb; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.teiid.language.Select; import org.teiid.metadata.RuntimeMetadata; import org.teiid.translator.DataNotAvailableException; import org.teiid.translator.ExecutionContext; import org.teiid.translator.ResultSetExecution; import org.teiid.translator.TranslatorException; import org.teiid.translator.simpledb.api.SimpleDBConnection; import org.teiid.translator.simpledb.api.SimpleDBDataTypeManager; import com.amazonaws.services.simpledb.model.Attribute; import com.amazonaws.services.simpledb.model.Item; import com.amazonaws.services.simpledb.model.SelectResult; public class SimpleDBQueryExecution implements ResultSetExecution { private static final int MAX_PAGE_SIZE = 2500; private Class<?>[] expectedColumnTypes; @SuppressWarnings("unused") private ExecutionContext executionContext; @SuppressWarnings("unused") private RuntimeMetadata metadata; protected SimpleDBConnection connection; private SimpleDBSQLVisitor visitor = new SimpleDBSQLVisitor(); private String nextToken; protected Iterator<Item> listIterator; public SimpleDBQueryExecution(final Select command, ExecutionContext executionContext, RuntimeMetadata metadata, final SimpleDBConnection connection) throws TranslatorException { this.executionContext = executionContext; this.metadata = metadata; this.connection = connection; if (command != null) { this.visitor.append(command); this.visitor.checkExceptions(); this.expectedColumnTypes = command.getColumnTypes(); } } @Override public void execute() throws TranslatorException { executeDirect(getSQL(), null); } protected String getSQL() { return this.visitor.toString() + " LIMIT " + Math.min(this.executionContext.getBatchSize(), MAX_PAGE_SIZE); //$NON-NLS-1$ } protected void executeDirect(String sql, String next) throws TranslatorException { SelectResult result = connection.performSelect(sql, next); this.nextToken = result.getNextToken(); this.listIterator = result.getItems().iterator(); } @Override public void close() { } @Override public void cancel() throws TranslatorException { } @Override public List<?> next() throws TranslatorException, DataNotAvailableException { if (this.listIterator.hasNext()) { return buildRow(this.listIterator.next()); } if (this.nextToken != null) { executeDirect(getSQL(), this.nextToken); if (this.listIterator.hasNext()) { return buildRow(this.listIterator.next()); } } return null; } protected List<?> buildRow(Item item) throws TranslatorException { Map<String, List<String>> valueMap = createAttributeMap(item.getAttributes()); List row = new ArrayList(); for (int i = 0; i < visitor.getProjectedColumns().size(); i++) { String columnName = visitor.getProjectedColumns().get(i); if (SimpleDBMetadataProcessor.isItemName(columnName)) { row.add(SimpleDBDataTypeManager.convertFromSimpleDBType(Arrays.asList(item.getName()), expectedColumnTypes[i])); continue; } row.add(SimpleDBDataTypeManager.convertFromSimpleDBType(valueMap.get(columnName), expectedColumnTypes[i])); } return row; } protected Map<String, List<String>> createAttributeMap(List<Attribute> attributes) { Map<String, List<String>> map = new TreeMap<String, List<String>>(); for (Attribute attribute : attributes) { if (map.get(attribute.getName()) == null) { List<String> list = new ArrayList<String>(); list.add(attribute.getValue()); map.put(attribute.getName(), list); } else { map.get(attribute.getName()).add(attribute.getValue()); } } return map; } }
9242eae8bbcb87fd6ca347ab881232fd5a229f0d
18,483
java
Java
pwra53a/src/main/java/com/leinardi/androidthings/driver/pwra53a/PwrA53A.java
leinardi/androidthings-kuman-sm9
de05b4c06b0e81e80bc5540143499982fd75ba77
[ "Apache-2.0" ]
7
2017-12-21T00:01:09.000Z
2021-09-07T09:13:53.000Z
pwra53a/src/main/java/com/leinardi/androidthings/driver/pwra53a/PwrA53A.java
leinardi/androidthings-kuman-sm9
de05b4c06b0e81e80bc5540143499982fd75ba77
[ "Apache-2.0" ]
3
2017-12-03T13:13:47.000Z
2018-10-25T17:46:17.000Z
pwra53a/src/main/java/com/leinardi/androidthings/driver/pwra53a/PwrA53A.java
leinardi/androidthings-kuman-sm9
de05b4c06b0e81e80bc5540143499982fd75ba77
[ "Apache-2.0" ]
2
2017-12-20T23:43:54.000Z
2018-11-28T14:08:41.000Z
39.07611
119
0.645079
1,002,466
/* * Copyright 2017 Roberto Leinardi. * * 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.leinardi.androidthings.driver.pwra53a; import android.util.Log; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.I2cDevice; import com.google.android.things.pio.PeripheralManagerService; import com.google.android.things.pio.Pwm; import com.leinardi.androidthings.pio.SoftPwm; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class PwrA53A implements AutoCloseable { private static final String TAG = PwrA53A.class.getSimpleName(); private static final int POWER_MIN = 0; private static final int POWER_MAX = 100; private static final int PWM_FREQUENCY = 100; private final String mI2cName; /** * Default I2C address for the sensor. */ private static final int DEFAULT_I2C_ADDRESS = 0x17; // Registers private static final int PWR_A53_A_REG_SERVO = 0xFF; private static final int PWR_A53_A_REG_VOLTAGE = 0x12; private static final int PWR_A53_A_REG_SPEED_COUNTER_1 = 0x13; private static final int PWR_A53_A_REG_SPEED_COUNTER_2 = 0x14; // Servos IDs public static final int SERVO_ID_1 = 1; public static final int SERVO_ID_2 = 2; public static final int SERVO_ID_3 = 3; public static final int SERVO_ID_4 = 4; public static final int SERVO_ID_5 = 5; public static final int SERVO_ID_6 = 6; public static final int SERVO_ID_7 = 7; // Vertical servo public static final int SERVO_ID_8 = 8; // Horizontal servo // GPIO LEDs private static final String PWR_A53_A_LED0 = "BCM10"; private static final String PWR_A53_A_LED1 = "BCM9"; private static final String PWR_A53_A_LED2 = "BCM25"; // PWM Motors private static final String PWR_A53_A_ENA_PWM = "PWM1"; private static final String PWR_A53_A_ENB_PWM = "PWM0"; // GPIO Motors private static final String PWR_A53_A_ENA_GPIO = "BCM13"; private static final String PWR_A53_A_ENB_GPIO = "BCM20"; private static final String PWR_A53_A_IN1 = "BCM19"; private static final String PWR_A53_A_IN2 = "BCM16"; private static final String PWR_A53_A_IN3 = "BCM21"; private static final String PWR_A53_A_IN4 = "BCM26"; // GPIO Servos private static final String PWR_A53_A_SER1 = "BCM11"; private static final String PWR_A53_A_SER2 = "BCM8"; private static final String PWR_A53_A_SER3 = "BCM7"; private static final String PWR_A53_A_SER4 = "BCM5"; private static final String PWR_A53_A_SER7 = "BCM6"; private static final String PWR_A53_A_SER8 = "BCM12"; // GPIO Ultrasound private static final String PWR_A53_A_ECHO = "BCM4"; private static final String PWR_A53_A_TRIG = "BCM17"; // GPIO Infrared private static final String PWR_A53_A_IR_R = "BCM18"; private static final String PWR_A53_A_IR_L = "BCM27"; private static final String PWR_A53_A_IR_M = "BCM22"; private static final String PWR_A53_A_IRF_R = "BCM23"; private static final String PWR_A53_A_IRF_L = "BCM24"; private I2cDevice mI2cDevice; private Pwm mPwmEnA; private Pwm mPwmEnB; private SoftPwm mPwmSwEnA; private SoftPwm mPwmSwEnB; private final Map<String, Gpio> mGpioMap; private boolean mUsePwm; /** * Create a new PWR.A53.A sensor driver connected on the given bus. * * @throws IOException */ public PwrA53A(String i2cName) throws IOException { mI2cName = i2cName; mGpioMap = new HashMap<>(); try { connect(); } catch (IOException | RuntimeException e) { try { close(); } catch (RuntimeException ignored) { } throw e; } } private void connect() throws IOException { PeripheralManagerService pioService = new PeripheralManagerService(); // Open devices mI2cDevice = pioService.openI2cDevice(mI2cName, DEFAULT_I2C_ADDRESS); mGpioMap.put(PWR_A53_A_LED0, pioService.openGpio(PWR_A53_A_LED0)); mGpioMap.put(PWR_A53_A_LED1, pioService.openGpio(PWR_A53_A_LED1)); mGpioMap.put(PWR_A53_A_LED2, pioService.openGpio(PWR_A53_A_LED2)); mGpioMap.put(PWR_A53_A_IR_R, pioService.openGpio(PWR_A53_A_IR_R)); mGpioMap.put(PWR_A53_A_IR_L, pioService.openGpio(PWR_A53_A_IR_L)); mGpioMap.put(PWR_A53_A_IR_M, pioService.openGpio(PWR_A53_A_IR_M)); mGpioMap.put(PWR_A53_A_IRF_R, pioService.openGpio(PWR_A53_A_IRF_R)); mGpioMap.put(PWR_A53_A_IRF_L, pioService.openGpio(PWR_A53_A_IRF_L)); mGpioMap.put(PWR_A53_A_TRIG, pioService.openGpio(PWR_A53_A_TRIG)); mGpioMap.put(PWR_A53_A_ECHO, pioService.openGpio(PWR_A53_A_ECHO)); mUsePwm = tryToOpenPwm(pioService); if (!mUsePwm) { mPwmSwEnA = new SoftPwm(); mPwmSwEnA.openSoftPwm(PWR_A53_A_ENA_GPIO); mPwmSwEnB = new SoftPwm(); mPwmSwEnB.openSoftPwm(PWR_A53_A_ENB_GPIO); } mGpioMap.put(PWR_A53_A_IN1, pioService.openGpio(PWR_A53_A_IN1)); mGpioMap.put(PWR_A53_A_IN2, pioService.openGpio(PWR_A53_A_IN2)); mGpioMap.put(PWR_A53_A_IN3, pioService.openGpio(PWR_A53_A_IN3)); mGpioMap.put(PWR_A53_A_IN4, pioService.openGpio(PWR_A53_A_IN4)); // Setup GPIO getGpio(PWR_A53_A_LED0).setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH); getGpio(PWR_A53_A_LED1).setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH); getGpio(PWR_A53_A_LED2).setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH); if (!mUsePwm) { mPwmSwEnA.setPwmFrequencyHz(PWM_FREQUENCY); mPwmSwEnB.setPwmFrequencyHz(PWM_FREQUENCY); setPwmThrottle(mPwmSwEnA, 0); setPwmThrottle(mPwmSwEnB, 0); } else { mPwmEnA.setPwmFrequencyHz(PWM_FREQUENCY); mPwmEnB.setPwmFrequencyHz(PWM_FREQUENCY); setPwmThrottle(mPwmEnA, 0); setPwmThrottle(mPwmEnB, 0); } getGpio(PWR_A53_A_IN1).setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW); getGpio(PWR_A53_A_IN2).setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW); getGpio(PWR_A53_A_IN3).setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW); getGpio(PWR_A53_A_IN4).setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW); getGpio(PWR_A53_A_IR_R).setDirection(Gpio.DIRECTION_IN); getGpio(PWR_A53_A_IR_L).setDirection(Gpio.DIRECTION_IN); getGpio(PWR_A53_A_IR_M).setDirection(Gpio.DIRECTION_IN); getGpio(PWR_A53_A_IRF_R).setDirection(Gpio.DIRECTION_IN); getGpio(PWR_A53_A_IRF_L).setDirection(Gpio.DIRECTION_IN); getGpio(PWR_A53_A_IR_R).setActiveType(Gpio.ACTIVE_HIGH); getGpio(PWR_A53_A_IR_L).setActiveType(Gpio.ACTIVE_HIGH); getGpio(PWR_A53_A_IR_M).setActiveType(Gpio.ACTIVE_HIGH); getGpio(PWR_A53_A_IRF_R).setActiveType(Gpio.ACTIVE_HIGH); getGpio(PWR_A53_A_IRF_L).setActiveType(Gpio.ACTIVE_HIGH); getGpio(PWR_A53_A_TRIG).setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW); getGpio(PWR_A53_A_ECHO).setDirection(Gpio.DIRECTION_IN); getGpio(PWR_A53_A_ECHO).setActiveType(Gpio.ACTIVE_HIGH); } /** * Tries to open the PWM devices. * Currently Android Things doesn't allow to set custom pins for the PWM and the PWR.A53.A * is expecting to get it on pin 20 and pin 13. Unfortunately Android uses pin 18 and 13. * If you want to use PWM with this board please star this issue: * https://issuetracker.google.com/issues/70115494 */ private boolean tryToOpenPwm(PeripheralManagerService pioService) { try { mPwmEnB = pioService.openPwm(PWR_A53_A_ENB_PWM); mPwmEnA = pioService.openPwm(PWR_A53_A_ENA_PWM); return true; } catch (IOException e) { Log.e(TAG, "Unable to open PWMs, falling back to SoftPwm", e); try { if (mPwmEnA != null) { mPwmEnA.close(); } if (mPwmEnB != null) { mPwmEnB.close(); } } catch (IOException ignored) { // NO-OP } } return false; } private void setPwmThrottle(Pwm pwm, int throttle) throws IOException { if (throttle < POWER_MIN || throttle > POWER_MAX) { throw new IllegalArgumentException("Throttle must be between 0 and 100. Throttle: " + throttle); } if (pwm == null) { throw new IllegalStateException("PWM Device not open"); } pwm.setPwmDutyCycle(throttle); pwm.setEnabled(throttle != 0); } public int getServoAngle(int servoId) throws IOException, IllegalStateException { return readRegByte(servoId) & 0xFF; } public void setServoAngle(int servoId, int angle) throws IOException, IllegalStateException { Log.d(TAG, "Set servoId " + servoId + " to angle " + angle); writeRegByte(PWR_A53_A_REG_SERVO, (byte) servoId); writeRegByte(angle, (byte) 255); } public void resetServo() throws IOException, IllegalStateException { writeRegByte(PWR_A53_A_REG_SERVO, (byte) 0); writeRegByte(1, (byte) 255); } public void saveServo() throws IOException, IllegalStateException { writeRegByte(PWR_A53_A_REG_SERVO, (byte) 17); writeRegByte(1, (byte) 255); } public int getVoltage() throws IOException, IllegalStateException { Log.d(TAG, "Get Voltage "); return readRegByte(PWR_A53_A_REG_VOLTAGE) & 0xFF; } public int getSpeedCounter1() throws IOException, IllegalStateException { return readRegByte(PWR_A53_A_REG_SPEED_COUNTER_1) & 0xFF; } public int getSpeedCounter2() throws IOException, IllegalStateException { return readRegByte(PWR_A53_A_REG_SPEED_COUNTER_2) & 0xFF; } /** * Update the value of the LED0 output. * * @param value true = on, false = off */ public void setLed0Value(boolean value) throws IOException, IllegalStateException { setLedValue(PWR_A53_A_LED0, value); } /** * Update the value of the LED1 output. * * @param value true = on, false = off */ public void setLed1Value(boolean value) throws IOException, IllegalStateException { setLedValue(PWR_A53_A_LED1, value); } /** * Update the value of the LED2 output. * * @param value true = on, false = off */ public void setLed2Value(boolean value) throws IOException, IllegalStateException { setLedValue(PWR_A53_A_LED2, value); } /** * Update the value of the LED output. */ private void setLedValue(String ledGpioName, boolean value) throws IOException, IllegalStateException { Log.d(TAG, "Set led " + ledGpioName + " to " + (value ? "ON" : "OFF")); getGpio(ledGpioName).setValue(value); } public void motorsForward(int power) throws IOException, IllegalStateException { setThrottleMotors(power, power); } public void motorsBackward(int power) throws IOException, IllegalStateException { setThrottleMotors(-power, -power); } public void motorsTurnLeft(int power) throws IOException, IllegalStateException { setThrottleMotors(power, -power); } public void motorsTurnRight(int power) throws IOException, IllegalStateException { setThrottleMotors(-power, power); } public void motorsStop() throws IOException, IllegalStateException { setThrottleMotors(POWER_MIN, POWER_MIN); } public void setThrottleMotor1(int throttle) throws IOException { boolean moveForward = throttle >= 0; boolean shouldStop = throttle == 0; if (!moveForward) { throttle = -throttle; } if (mUsePwm) { setPwmThrottle(mPwmEnA, throttle); } else { setPwmThrottle(mPwmSwEnA, throttle); } getGpio(PWR_A53_A_IN1).setValue(moveForward && !shouldStop); getGpio(PWR_A53_A_IN2).setValue(!moveForward); } public void setThrottleMotor2(int throttle) throws IOException { boolean moveForward = throttle >= 0; boolean shouldStop = throttle == 0; if (!moveForward) { throttle = -throttle; } if (mUsePwm) { setPwmThrottle(mPwmEnB, throttle); } else { setPwmThrottle(mPwmSwEnB, throttle); } getGpio(PWR_A53_A_IN3).setValue(moveForward && !shouldStop); getGpio(PWR_A53_A_IN4).setValue(!moveForward); } public void setThrottleMotors(int throttleMotor1, int throttleMotor2) throws IOException { Log.d(TAG, "throttleMotor1 = " + throttleMotor1); Log.d(TAG, "throttleMotor2 = " + throttleMotor2); setThrottleMotor1(throttleMotor1); setThrottleMotor2(throttleMotor2); } public void motorsMoveToDirection(int angle, int power) throws IOException { int throttleMotor1 = 0; int throttleMotor2 = 0; if (power != 0) { if (angle >= 150 && angle < 180) { throttleMotor1 = Math.round(scaleValue(angle, 150, 180, POWER_MIN, -POWER_MAX)); throttleMotor2 = Math.round(scaleValue(angle, 150, 180, POWER_MAX, POWER_MAX)); } else if (angle >= 90 && angle < 150) { throttleMotor1 = Math.round(scaleValue(angle, 90, 150, POWER_MAX, POWER_MIN)); throttleMotor2 = Math.round(scaleValue(angle, 90, 150, POWER_MAX, POWER_MAX)); } else if (angle >= 30 && angle < 90) { throttleMotor1 = Math.round(scaleValue(angle, 30, 90, POWER_MAX, POWER_MAX)); throttleMotor2 = Math.round(scaleValue(angle, 30, 90, POWER_MIN, POWER_MAX)); } else if (angle >= 0 && angle < 30) { throttleMotor1 = Math.round(scaleValue(angle, 0, 30, POWER_MAX, POWER_MAX)); throttleMotor2 = Math.round(scaleValue(angle, 0, 30, -POWER_MAX, POWER_MIN)); } else if (angle < 0 && angle >= -30) { throttleMotor1 = Math.round(scaleValue(angle, 0, -30, POWER_MAX, -POWER_MAX)); throttleMotor2 = Math.round(scaleValue(angle, 0, -30, -POWER_MAX, POWER_MIN)); } else if (angle < -30 && angle >= -90) { throttleMotor1 = Math.round(scaleValue(angle, -30, -90, -POWER_MAX, -POWER_MAX)); throttleMotor2 = Math.round(scaleValue(angle, -30, -90, POWER_MIN, -POWER_MAX)); } else if (angle < -90 && angle >= -150) { throttleMotor1 = Math.round(scaleValue(angle, -90, -150, -POWER_MAX, POWER_MIN)); throttleMotor2 = Math.round(scaleValue(angle, -90, -150, -POWER_MAX, -POWER_MAX)); } else if (angle < -150 && angle >= -180) { throttleMotor1 = Math.round(scaleValue(angle, -150, -180, POWER_MIN, -POWER_MAX)); throttleMotor2 = Math.round(scaleValue(angle, -150, -180, -POWER_MAX, POWER_MAX)); } throttleMotor1 = Math.round(throttleMotor1 / 100f * power); throttleMotor2 = Math.round(throttleMotor2 / 100f * power); } setThrottleMotors(throttleMotor1, throttleMotor2); } private float scaleValue(float x, float oldStartRange, float oldEndRange, float newStartRange, float newEndRange) { return (((newEndRange - newStartRange) * (x - oldStartRange)) / (oldEndRange - oldStartRange)) + newStartRange; } private I2cDevice getI2cDevice() throws IllegalStateException { if (mI2cDevice == null) { throw new IllegalStateException("I2C Device not open"); } return mI2cDevice; } private Gpio getGpio(String gpioName) throws IllegalStateException { Gpio gpio = mGpioMap.get(gpioName); if (gpio == null) { throw new IllegalStateException("GPIO Device not open"); } return gpio; } /** * Read a byte from a given register. * * @param reg The register to read from (0x00-0xFF). * @return */ private byte readRegByte(int reg) throws IOException { if (reg < 0 || reg > 0xFF) { throw new IllegalArgumentException("The register must be between 0x00-0xFF. Register:" + reg); } byte[] buffer = {(byte) (reg & 0xFF)}; getI2cDevice().write(buffer, 1); buffer[0] = 0; getI2cDevice().read(buffer, 1); return buffer[0]; } /** * Write a byte to a given register. * * @param reg The register to write to (0x00-0xFF). * @param data Value to write */ private void writeRegByte(int reg, byte data) throws IOException { if (reg < 0 || reg > 0xFF) { throw new IllegalArgumentException("The register must be between 0x00-0xFF. Register:" + reg); } byte[] buffer = {(byte) (reg & 0xFF), data}; getI2cDevice().write(buffer, buffer.length); } /** * Close the driver and the underlying device. */ @Override public void close() { try { mI2cDevice.close(); } catch (IOException e) { Log.w(TAG, "Unable to close PWM device", e); } if (mUsePwm) { try { mPwmEnA.close(); } catch (IOException e) { Log.w(TAG, "Unable to close PWM device", e); } try { mPwmEnB.close(); } catch (IOException e) { Log.w(TAG, "Unable to close PWM device", e); } } for (Gpio gpio : mGpioMap.values()) { try { gpio.close(); } catch (IOException e) { Log.w(TAG, "Unable to close GPIO device", e); } } mI2cDevice = null; mGpioMap.clear(); } }
9242ebbe82d5f3c61abd5fde2ea2a80c290c0adf
882
java
Java
research/gaia/gremlin/compiler/gremlin-server-plugin/src/main/java/com/alibaba/graphscope/gaia/plan/meta/StepPropertiesMeta.java
tianliplus/GraphScope
0226e00c106d5959d6fdc1637fe1646b16b26136
[ "Apache-2.0" ]
1
2021-05-19T08:11:47.000Z
2021-05-19T08:11:47.000Z
research/gaia/gremlin/compiler/gremlin-server-plugin/src/main/java/com/alibaba/graphscope/gaia/plan/meta/StepPropertiesMeta.java
LDA111222/GraphScope
b485408919af470be1c4a267571a81fd08cca9cf
[ "Apache-2.0" ]
null
null
null
research/gaia/gremlin/compiler/gremlin-server-plugin/src/main/java/com/alibaba/graphscope/gaia/plan/meta/StepPropertiesMeta.java
LDA111222/GraphScope
b485408919af470be1c4a267571a81fd08cca9cf
[ "Apache-2.0" ]
null
null
null
22.615385
82
0.6678
1,002,467
package com.alibaba.graphscope.gaia.plan.meta; import com.alibaba.graphscope.gaia.plan.meta.object.StepId; import org.apache.tinkerpop.gremlin.process.traversal.Step; import java.util.List; public class StepPropertiesMeta { private List<String> properties; private StepId stepId; private Step step; public StepPropertiesMeta(List<String> properties, StepId stepId, Step step) { this.properties = properties; this.stepId = stepId; this.step = step; } public List<String> getProperties() { return properties; } public StepId getStepId() { return stepId; } public Step getStep() { return step; } public void addProperties(List<String> properties) { this.properties.addAll(properties); } public void setStepId(StepId stepId) { this.stepId = stepId; } }
9242ebf3320133a9509abba693db3810ff8951c4
3,727
java
Java
src/main/java/net/tiny/ws/rs/Response.java
combivators/tiny-rest
62002715988d4275f12d3628e7c11a0ff11fbcfe
[ "Apache-2.0" ]
null
null
null
src/main/java/net/tiny/ws/rs/Response.java
combivators/tiny-rest
62002715988d4275f12d3628e7c11a0ff11fbcfe
[ "Apache-2.0" ]
2
2020-01-11T09:12:55.000Z
2020-01-31T18:22:34.000Z
src/main/java/net/tiny/ws/rs/Response.java
combivators/tiny-rest
62002715988d4275f12d3628e7c11a0ff11fbcfe
[ "Apache-2.0" ]
null
null
null
27.813433
83
0.542528
1,002,468
package net.tiny.ws.rs; import java.io.IOException; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import net.tiny.config.JsonParser; import net.tiny.ws.HttpDateFormat; public final class Response { private final static String SERVER_NAME = "tiny/1.0.0"; private final Builder builder; private Response(Builder builder) { this.builder= builder; } public String json() { return builder.json(); } public void send(HttpExchange he) throws IOException { final String response = builder.join(he.getResponseHeaders()).json(); final byte[] rawResponse = response.getBytes(StandardCharsets.UTF_8); he.sendResponseHeaders(builder.status, rawResponse.length); he.getResponseBody().write(rawResponse); } public static Builder ok() { return new Builder(); } public static Builder status(int c) { return new Builder().status(c); } public static class Builder { int status = HttpURLConnection.HTTP_OK; Object entity; Map<String, List<String>> headers = new LinkedHashMap<>(); public Builder() { headers.put("Server", Arrays.asList(SERVER_NAME)); } public Builder status(int c) { status = c; return this; } public Builder entity(Object e) { entity = e; return this; } public Builder server(String s) { headers.put("Server", Arrays.asList(s)); return this; } public Builder cookie(String... cookies) { StringBuilder sb = new StringBuilder(); for (String c : cookies) { if (sb.length() > 0) { sb.append("; "); } sb.append(c); } return header("Set-Cookie", sb.toString()); } public Builder cache(long maxAge) { if (maxAge > 0L) { return header("Cache-Control", "max-age=" + maxAge); } else { return header("Cache-Control", "no-cache"); } } public Builder lastModified(Date date) { return header("Last-Modified", HttpDateFormat.format(date)); } public Builder header(String name, String value) { List<String> values = headers.get(name); if (null == values) { values = new ArrayList<>(); values.add(value); headers.put(name, values); } else if (!values.contains(value)){ values.add(value); } return this; } public Builder join(Headers headers) { for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) { for (String value : entry.getValue()) { headers.add(entry.getKey(), value); } } headers.add("Content-Type", "application/json; charset=utf-8"); return this; } public String json() { if (null != entity) { if (entity instanceof String) { return (String)entity; } else { return JsonParser.marshal(entity); } } return ""; } public Response build() { return new Response(this); } } }
9242ef2e17c3c6f856ad1cea3621819db16189c3
1,926
java
Java
know/know-webservice/src/main/java/com/pc/server/Server1Impl.java
hopepretty/konw
f4e4c49553cd86813104d4bb4a5a8d91ff04f04a
[ "Apache-2.0" ]
null
null
null
know/know-webservice/src/main/java/com/pc/server/Server1Impl.java
hopepretty/konw
f4e4c49553cd86813104d4bb4a5a8d91ff04f04a
[ "Apache-2.0" ]
null
null
null
know/know-webservice/src/main/java/com/pc/server/Server1Impl.java
hopepretty/konw
f4e4c49553cd86813104d4bb4a5a8d91ff04f04a
[ "Apache-2.0" ]
null
null
null
28.746269
131
0.698858
1,002,469
package com.pc.server; import org.springframework.stereotype.Component; import javax.jws.WebService; /** * WebService涉及到的有这些 "四解三类 ", 即四个注解,三个类 * @WebMethod * @WebService * @WebResult * @WebParam * SpringBus * Endpoint * EndpointImpl * * 一般我们都会写一个接口,然后再写一个实现接口的实现类,但是这不是强制性的 * @WebService 注解表明是一个webservice服务。 * name:对外发布的服务名, 对应于<wsdl:portType name="ServerServiceDemo"></wsdl:portType> * targetNamespace:命名空间,一般是接口的包名倒序, 实现类与接口类的这个配置一定要一致这种错误 * Exception in thread "main" org.apache.cxf.common.i18n.UncheckedException: No operation was found with the name xxxx * 对应于targetNamespace="http://server.webservice.example.com" * endpointInterface:服务接口全路径(如果是没有接口,直接写实现类的,该属性不用配置), 指定做SEI(Service EndPoint Interface)服务端点接口 * serviceName:对应于<wsdl:service name="ServerServiceDemoImplService"></wsdl:service> * portName:对应于<wsdl:port binding="tns:ServerServiceDemoImplServiceSoapBinding" name="ServerServiceDemoPort"></wsdl:port> * * @WebMethod 表示暴露的服务方法, 这里有接口ServerServiceDemo存在,在接口方法已加上@WebMethod, 所以在实现类中不用再加上,否则就要加上 * operationName: 接口的方法名 * action: 没发现又什么用处 * exclude: 默认是false, 用于阻止将某一继承方法公开为web服务 * * @WebResult 表示方法的返回值 * name:返回值的名称 * partName: * targetNamespace: * header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中 * * @WebParam * name:接口的参数 * partName: * targetNamespace: * header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中 * model:WebParam.Mode.IN/OUT/INOUT * * @author pc * @Date 2020/12/9 */ @Component @WebService(name = "Server1", targetNamespace = "http://server.pc.com", endpointInterface = "com.pc.server.Server1") public class Server1Impl implements Server1 { /** * 对外提供的接口服务 * * @param data * @return */ @Override public String service1(String data) { if(null == data || "".equals(data.trim())){ return "传入的参数为空"; } return "调用成功"; } }
9242f15f17cd2ab0a8594749fd7c187ce56e6dcf
615
java
Java
java后台代码/qshop-mp/src/main/java/co/lq/mp/handler/NullHandler.java
arraycto/qshop_bbc
ba9e51ae1a8aa4b73ffbbcfc600dba348fac314b
[ "Apache-2.0" ]
5
2020-09-07T02:33:29.000Z
2021-06-17T13:30:44.000Z
java后台代码/qshop-mp/src/main/java/co/lq/mp/handler/NullHandler.java
2227422/qshop_bbc
ba9e51ae1a8aa4b73ffbbcfc600dba348fac314b
[ "Apache-2.0" ]
null
null
null
java后台代码/qshop-mp/src/main/java/co/lq/mp/handler/NullHandler.java
2227422/qshop_bbc
ba9e51ae1a8aa4b73ffbbcfc600dba348fac314b
[ "Apache-2.0" ]
11
2020-09-07T02:33:30.000Z
2021-11-15T14:06:10.000Z
27.954545
115
0.752846
1,002,471
package co.lq.mp.handler; import java.util.Map; import org.springframework.stereotype.Component; import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; @Component public class NullHandler extends AbstractHandler { @Override public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) { return null; } }
9242f1d6a704a3d5c0cdd97ff5906733a3e2aaca
585
java
Java
hello-world-rest-api/src/main/java/com/rest/webservices/restfulwebservices/environment/InstanceInformationService.java
sdannarapu/docker-kubernetes-google-cloud
b4a3d57c0b1c00cbb7095c4630cb0b59d556e77b
[ "MIT" ]
1
2020-01-21T04:51:51.000Z
2020-01-21T04:51:51.000Z
hello-world-rest-api/src/main/java/com/rest/webservices/restfulwebservices/environment/InstanceInformationService.java
sdannarapu/docker-kubernetes-google-cloud
b4a3d57c0b1c00cbb7095c4630cb0b59d556e77b
[ "MIT" ]
null
null
null
hello-world-rest-api/src/main/java/com/rest/webservices/restfulwebservices/environment/InstanceInformationService.java
sdannarapu/docker-kubernetes-google-cloud
b4a3d57c0b1c00cbb7095c4630cb0b59d556e77b
[ "MIT" ]
null
null
null
27.857143
65
0.782906
1,002,472
package com.rest.webservices.restfulwebservices.environment; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @Service public class InstanceInformationService { private static final String HOST_NAME = "HOSTNAME"; private static final String DEFAULT_ENV_INSTANCE_GUID = "LOCAL"; // @Value(${ENVIRONMENT_VARIABLE_NAME:DEFAULT_VALUE}) @Value("${" + HOST_NAME + ":" + DEFAULT_ENV_INSTANCE_GUID + "}") private String hostName; public String retrieveInstanceInfo() { return hostName.substring(hostName.length()-5); } }
9242f237ba991ed6dca31618e9c72a05b4e46ad6
3,721
java
Java
distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/task/ODefaultRemoteTaskFactoryV3.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
3,651
2015-01-02T23:58:10.000Z
2022-03-31T21:12:12.000Z
distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/task/ODefaultRemoteTaskFactoryV3.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
6,890
2015-01-01T09:41:48.000Z
2022-03-29T08:39:49.000Z
distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/task/ODefaultRemoteTaskFactoryV3.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
923
2015-01-01T20:40:08.000Z
2022-03-21T07:26:56.000Z
31.268908
87
0.693362
1,002,473
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.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. * * * * For more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.server.distributed.impl.task; import com.orientechnologies.orient.server.distributed.ORemoteTaskFactory; import com.orientechnologies.orient.server.distributed.operation.NodeOperationTask; import com.orientechnologies.orient.server.distributed.task.ORemoteTask; /** * Factory of remote tasks. * * <p> * * <ul> * <li>V2 (11/09/2017) * </ul> * * @author Luigi Dell'Aquila (l.dellaquila--at--orientdb.com) */ public class ODefaultRemoteTaskFactoryV3 implements ORemoteTaskFactory { @Override public ORemoteTask createTask(final int code) { switch (code) { case OSQLCommandTask.FACTORYID: // 5 return new OSQLCommandTask(); case OScriptTask.FACTORYID: // 6 return new OScriptTask(); case OStopServerTask.FACTORYID: // 9 return new OStopServerTask(); case ORestartServerTask.FACTORYID: // 10 return new ORestartServerTask(); case OSyncClusterTask.FACTORYID: // 12 return new OSyncClusterTask(); case OSyncDatabaseTask.FACTORYID: // 14 return new OSyncDatabaseTask(); case OCopyDatabaseChunkTask.FACTORYID: // 15 return new OCopyDatabaseChunkTask(); case OGossipTask.FACTORYID: // 16 return new OGossipTask(); case ODropDatabaseTask.FACTORYID: // 23 return new ODropDatabaseTask(); case OUpdateDatabaseConfigurationTask.FACTORYID: // 24 return new OUpdateDatabaseConfigurationTask(); case ORequestDatabaseConfigurationTask.FACTORYID: // 27 return new ORequestDatabaseConfigurationTask(); case OUnreachableServerLocalTask.FACTORYID: // 28 throw new IllegalArgumentException( "Task with code " + code + " is not supported in remote configuration"); case OEnterpriseStatsTask.FACTORYID: // 29 return new OEnterpriseStatsTask(); // --- here starts V2 ---- case ORunQueryExecutionPlanTask.FACTORYID: // 40 return new ORunQueryExecutionPlanTask(); case OFetchQueryPageTask.FACTORYID: // 41 return new OFetchQueryPageTask(); case OCloseQueryTask.FACTORYID: // 42 return new OCloseQueryTask(); case OTransactionPhase1Task.FACTORYID: // 43 return new OTransactionPhase1Task(); case OTransactionPhase2Task.FACTORYID: // 44 return new OTransactionPhase2Task(); case NodeOperationTask.FACTORYID: // 55 return new NodeOperationTask(); case ONewSQLCommandTask.FACTORYID: // 56 return new ONewSQLCommandTask(); case OSyncDatabaseNewDeltaTask.FACTORYID: // 57 return new OSyncDatabaseNewDeltaTask(); case OUpdateDatabaseSequenceStatusTask.FACTORYID: // 58 return new OUpdateDatabaseSequenceStatusTask(); } throw new IllegalArgumentException("Task with code " + code + " is not supported"); } @Override public int getProtocolVersion() { return 3; } }
9242f2398f91b8a07bef8d0e8094852b2aeabf34
1,197
java
Java
core/src/main/java/com/payu/ratel/RetryPolicy.java
PayU-Tech/Ratel
e855c8c71aeaa04326a127c00ad20333f25d23fc
[ "Apache-2.0" ]
23
2015-03-09T07:38:47.000Z
2017-05-30T07:58:11.000Z
core/src/main/java/com/payu/ratel/RetryPolicy.java
PayU-Tech/Ratel
e855c8c71aeaa04326a127c00ad20333f25d23fc
[ "Apache-2.0" ]
40
2015-03-10T13:19:04.000Z
2018-10-05T07:53:50.000Z
core/src/main/java/com/payu/ratel/RetryPolicy.java
PayU-Tech/Ratel
e855c8c71aeaa04326a127c00ad20333f25d23fc
[ "Apache-2.0" ]
26
2015-03-10T11:19:42.000Z
2018-10-04T12:58:41.000Z
32.351351
119
0.760234
1,002,474
/* * Copyright 2015 PayU * * 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.payu.ratel; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RetryPolicy { Class<? extends Throwable>[] exception() default {Exception.class}; long waitingTime() default 5000; int retryCount() default 5; }
9242f2538dd546db3b6db768ec6c5eabae49c720
39,780
java
Java
docroot/WEB-INF/src/com/marcelmika/lims/persistence/generated/service/persistence/SettingsFinderImpl.java
marcelmika/lims
fb7600e3fb8852fe47b0fd5846996bdb7f1c9ed6
[ "MIT" ]
4
2015-05-04T21:52:42.000Z
2018-09-23T22:59:23.000Z
docroot/WEB-INF/src/com/marcelmika/lims/persistence/generated/service/persistence/SettingsFinderImpl.java
marcelmika/lims
fb7600e3fb8852fe47b0fd5846996bdb7f1c9ed6
[ "MIT" ]
26
2015-01-08T22:59:19.000Z
2016-07-06T09:59:58.000Z
docroot/WEB-INF/src/com/marcelmika/lims/persistence/generated/service/persistence/SettingsFinderImpl.java
marcelmika/lims
fb7600e3fb8852fe47b0fd5846996bdb7f1c9ed6
[ "MIT" ]
9
2015-02-27T14:05:40.000Z
2021-04-25T08:55:54.000Z
42.591006
115
0.59188
1,002,475
package com.marcelmika.lims.persistence.generated.service.persistence; import com.liferay.portal.kernel.dao.orm.*; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.StringUtil; import com.liferay.portal.service.persistence.impl.BasePersistenceImpl; import com.liferay.util.dao.orm.CustomSQLUtil; import com.marcelmika.lims.persistence.generated.model.Settings; import java.util.List; /** * @author Ing. Marcel Mika * @link http://marcelmika.com * Date: 8/4/14 * Time: 10:19 AM */ public class SettingsFinderImpl extends BasePersistenceImpl<Settings> implements SettingsFinder { // Log private static Log log = LogFactoryUtil.getLog(SettingsFinderImpl.class); // Find users SQL private static final String FIND_ALL_USERS = SettingsFinder.class.getName() + ".findAllUsers"; private static final String FIND_BY_SITES_GROUPS = SettingsFinder.class.getName() + ".findBySitesGroups"; private static final String FIND_BY_SOCIAL_GROUPS = SettingsFinder.class.getName() + ".findBySocialGroups"; private static final String FIND_BY_USER_GROUPS = SettingsFinder.class.getName() + ".findByUserGroups"; // Search users SQL private static final String SEARCH_ALL_USERS = SettingsFinder.class.getName() + ".searchAllUsers"; private static final String SEARCH_BY_SITES_GROUPS = SettingsFinder.class.getName() + ".searchBySitesGroups"; private static final String SEARCH_BY_SOCIAL_GROUPS = SettingsFinder.class.getName() + ".searchBySocialGroups"; private static final String SEARCH_BY_USER_GROUPS = SettingsFinder.class.getName() + ".searchByUserGroups"; // Search columns count private static final Integer SEARCH_COLUMN_COUNT = 3; // Placeholders private static final String PLACEHOLDER_DEFAULT_USER = "[$DEFAULT_USER$]"; private static final String PLACEHOLDER_DEACTIVATED_USER = "[$DEACTIVATED_USER$]"; private static final String PLACEHOLDER_USERS_GROUPS_JOIN = "[$USERS_GROUPS_JOIN$]"; private static final String PLACEHOLDER_USERS_GROUPS_WHERE = "[$USERS_GROUPS_WHERE$]"; private static final String PLACEHOLDER_SOCIAL_RELATION_TYPES = "[$SOCIAL_RELATION_TYPES$]"; /** * Finds all users except the one given in the parameter and their settings * * @param userId of excluded user * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param start value of the list * @param end value of the list * @return List of objects where each object contains user info */ @Override @SuppressWarnings("unchecked") // Cast List<Object[]> is unchecked public List<Object[]> findAllGroups(Long userId, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, int start, int end) throws Exception { Session session = null; try { // Open database session session = openSession(); // Generate SQL String sql = getFindAllUsersSQL(ignoreDefaultUser, ignoreDeactivatedUser); // Create query from sql SQLQuery query = session.createSQLQuery(sql); // Now we need to map types to columns query.addScalar("userId", Type.LONG); query.addScalar("screenName", Type.STRING); query.addScalar("firstName", Type.STRING); query.addScalar("middleName", Type.STRING); query.addScalar("lastName", Type.STRING); query.addScalar("presence", Type.STRING); query.addScalar("presenceUpdatedAt", Type.LONG); // Add parameters to query QueryPos queryPos = QueryPos.getInstance(query); queryPos.add(userId); // Return the result return (List<Object[]>) QueryUtil.list(query, getDialect(), start, end); } finally { // Session needs to be closed if something goes wrong closeSession(session); } } /** * Returns all groups where the user participates * * @param userId of excluded user * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param excludedSites list of names of sites which should be excluded * @param start value of the list * @param end value of the list * @return List of objects where each object contains group name and user info * @throws Exception */ @Override @SuppressWarnings("unchecked") // Cast List<Object[]> is unchecked public List<Object[]> findSitesGroups(Long userId, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedSites, int start, int end) throws Exception { Session session = null; try { // Open database session session = openSession(); // Generate SQL String sql = getFindBySitesGroupsSQL(ignoreDefaultUser, ignoreDeactivatedUser, excludedSites); // Create query from sql SQLQuery query = session.createSQLQuery(sql); // Now we need to map types to columns query.addScalar("groupName", Type.STRING); query.addScalar("userId", Type.LONG); query.addScalar("screenName", Type.STRING); query.addScalar("firstName", Type.STRING); query.addScalar("middleName", Type.STRING); query.addScalar("lastName", Type.STRING); query.addScalar("presence", Type.STRING); query.addScalar("presenceUpdatedAt", Type.LONG); // Add parameters to query QueryPos queryPos = QueryPos.getInstance(query); queryPos.add(userId); if (excludedSites.length > 0) { queryPos.add(excludedSites); } queryPos.add(userId); // Return the result return (List<Object[]>) QueryUtil.list(query, getDialect(), start, end); } finally { // Session needs to be closed if something goes wrong closeSession(session); } } /** * Returns all user's social relations * * @param userId of the user whose social relations are we looking for * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param relationTypes an array of relation type codes that we are looking for * @param start value of the list * @param end value of the list * @return List objects where each object contains relation type and user info * @throws Exception */ @Override @SuppressWarnings("unchecked") // Cast List<Object[]> is unchecked public List<Object[]> findSocialGroups(Long userId, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, int[] relationTypes, int start, int end) throws Exception { Session session = null; try { // Open database session session = openSession(); // Generate SQL String sql = getFindSocialGroupsSQL(ignoreDefaultUser, ignoreDeactivatedUser, relationTypes); // Create query from sql SQLQuery query = session.createSQLQuery(sql); // Now we need to map types to columns query.addScalar("relationType", Type.INTEGER); query.addScalar("userId", Type.LONG); query.addScalar("screenName", Type.STRING); query.addScalar("firstName", Type.STRING); query.addScalar("middleName", Type.STRING); query.addScalar("lastName", Type.STRING); query.addScalar("presence", Type.STRING); query.addScalar("presenceUpdatedAt", Type.LONG); // Add parameters to query QueryPos queryPos = QueryPos.getInstance(query); queryPos.add(userId); if (relationTypes.length > 0) { queryPos.add(relationTypes); } queryPos.add(userId); // Return the result return (List<Object[]>) QueryUtil.list(query, getDialect(), start, end); } finally { // Session needs to be closed if something goes wrong closeSession(session); } } /** * Returns all user groups where the user belongs * * @param userId of the user whose social relations are we looking for * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param excludedGroups list of names of groups which should be excluded * @param start value of the list * @param end value of the list * @return List objects where each object contains group name and user info * @throws Exception */ @SuppressWarnings("unchecked") // Cast List<Object[]> is unchecked public List<Object[]> findUserGroups(Long userId, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedGroups, int start, int end) throws Exception { Session session = null; try { // Open database session session = openSession(); // Generate SQL String sql = getFindByUserGroupsSQL(ignoreDefaultUser, ignoreDeactivatedUser, excludedGroups); // Create query from sql SQLQuery query = session.createSQLQuery(sql); // Now we need to map types to columns query.addScalar("groupName", Type.STRING); query.addScalar("userId", Type.LONG); query.addScalar("screenName", Type.STRING); query.addScalar("firstName", Type.STRING); query.addScalar("middleName", Type.STRING); query.addScalar("lastName", Type.STRING); query.addScalar("presence", Type.STRING); query.addScalar("presenceUpdatedAt", Type.LONG); // Add parameters to query QueryPos queryPos = QueryPos.getInstance(query); queryPos.add(userId); if (excludedGroups.length > 0) { queryPos.add(excludedGroups); } queryPos.add(userId); // Return the result return (List<Object[]>) QueryUtil.list(query, getDialect(), start, end); } finally { // Session needs to be closed if something goes wrong closeSession(session); } } /** * Finds all users based on the search query except the one given in the parameter and their settings. * * @param userId of excluded user * @param searchQuery search string * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param start value of the list * @param end value of the list * @return List of objects where each object contains user info */ @Override @SuppressWarnings("unchecked") // Cast List<Object[]> is unchecked public List<Object[]> searchSitesBuddies(Long userId, String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedSites, int start, int end) throws Exception { Session session = null; try { // Open database session session = openSession(); // Generate SQL String sql = getSearchSitesBuddiesSQL( searchQuery, ignoreDefaultUser, ignoreDeactivatedUser, excludedSites ); // Create query from sql SQLQuery query = session.createSQLQuery(sql); // Now we need to map types to columns query.addScalar("userId", Type.LONG); query.addScalar("screenName", Type.STRING); query.addScalar("firstName", Type.STRING); query.addScalar("middleName", Type.STRING); query.addScalar("lastName", Type.STRING); query.addScalar("presence", Type.STRING); query.addScalar("presenceUpdatedAt", Type.LONG); // Add parameters to query QueryPos queryPos = QueryPos.getInstance(query); queryPos.add(userId); if (excludedSites.length > 0) { queryPos.add(excludedSites); } queryPos.add(userId); // Search query needs to be lowered String lowerCaseSearchQuery = searchQuery.toLowerCase(); // Create the like statement for search query String likeStatement = "%" + lowerCaseSearchQuery + "%"; // There are 3 possible columns we are about to search // (first name, middle name, last name, screen name, email address) for (int i = 0; i < SEARCH_COLUMN_COUNT; i++) { queryPos.add(likeStatement); queryPos.add(lowerCaseSearchQuery); } // Return the result return (List<Object[]>) QueryUtil.list(query, getDialect(), start, end); } finally { // Session needs to be closed if something goes wrong closeSession(session); } } /** * Finds all users based on the search query except the one given in the parameter and their settings. * * @param userId of excluded user * @param searchQuery search string * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param start value of the list * @param end value of the list * @return List of objects where each object contains user info */ @Override @SuppressWarnings("unchecked") // Cast List<Object[]> is unchecked public List<Object[]> searchAllBuddies(Long userId, String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, int start, int end) throws Exception { Session session = null; try { // Open database session session = openSession(); // Generate SQL String sql = getSearchAllUsersSQL(searchQuery, ignoreDefaultUser, ignoreDeactivatedUser); // Create query from sql SQLQuery query = session.createSQLQuery(sql); // Now we need to map types to columns query.addScalar("userId", Type.LONG); query.addScalar("screenName", Type.STRING); query.addScalar("firstName", Type.STRING); query.addScalar("middleName", Type.STRING); query.addScalar("lastName", Type.STRING); query.addScalar("presence", Type.STRING); query.addScalar("presenceUpdatedAt", Type.LONG); // Add parameters to query QueryPos queryPos = QueryPos.getInstance(query); queryPos.add(userId); // Search query needs to be lowered String lowerCaseSearchQuery = searchQuery.toLowerCase(); // Create the like statement for search query String likeStatement = "%" + lowerCaseSearchQuery + "%"; // There are 3 possible columns we are about to search // (first name, middle name, last name, screen name, email address) for (int i = 0; i < SEARCH_COLUMN_COUNT; i++) { queryPos.add(likeStatement); queryPos.add(lowerCaseSearchQuery); } // Return the result return (List<Object[]>) QueryUtil.list(query, getDialect(), start, end); } finally { // Session needs to be closed if something goes wrong closeSession(session); } } /** * Returns all user's social relations based on the search query * * @param userId of the user whose social relations are we looking for * @param searchQuery search query string * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param relationTypes an array of relation type codes that we are looking for * @param start value of the list * @param end value of the list * @return List of objects where each object contains user info * @throws Exception */ @Override @SuppressWarnings("unchecked") // Cast List<Object[]> is unchecked public List<Object[]> searchSocialBuddies(Long userId, String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, int[] relationTypes, int start, int end) throws Exception { Session session = null; try { // Open database session session = openSession(); // Generate SQL String sql = getSearchSocialBuddiesSQL( searchQuery, ignoreDefaultUser, ignoreDeactivatedUser, relationTypes ); // Create query from sql SQLQuery query = session.createSQLQuery(sql); // Now we need to map types to columns query.addScalar("userId", Type.LONG); query.addScalar("screenName", Type.STRING); query.addScalar("firstName", Type.STRING); query.addScalar("middleName", Type.STRING); query.addScalar("lastName", Type.STRING); query.addScalar("presence", Type.STRING); query.addScalar("presenceUpdatedAt", Type.LONG); // Add parameters to query QueryPos queryPos = QueryPos.getInstance(query); queryPos.add(userId); if (relationTypes.length > 0) { queryPos.add(relationTypes); } queryPos.add(userId); // Search query needs to be lowered String lowerCaseSearchQuery = searchQuery.toLowerCase(); // Create the like statement for search query String likeStatement = "%" + lowerCaseSearchQuery + "%"; // There are 3 possible columns we are about to search // (first name, middle name, last name, screen name, email address) for (int i = 0; i < SEARCH_COLUMN_COUNT; i++) { queryPos.add(likeStatement); queryPos.add(lowerCaseSearchQuery); } // Return the result return (List<Object[]>) QueryUtil.list(query, getDialect(), start, end); } finally { // Session needs to be closed if something goes wrong closeSession(session); } } /** * Returns a list of buddies. This list is made of all buddies based on the search query that are * in the same user group as the user. * * @param userId which should be excluded from the list * @param searchQuery search query string * @param ignoreDefaultUser boolean set to true if the default user should be excluded * @param ignoreDeactivatedUser boolean set to true if the deactivated user should be excluded * @param excludedGroups names of groups that should be excluded from the list of buddies * @param start of the list * @param end of the list * @return a list of buddies * @throws Exception */ @Override @SuppressWarnings("unchecked") // Cast List<Object[]> is unchecked public List<Object[]> searchUserGroupsBuddies(Long userId, String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedGroups, int start, int end) throws Exception { Session session = null; try { // Open database session session = openSession(); // Generate SQL String sql = getSearchUserGroupsSQL( searchQuery, ignoreDefaultUser, ignoreDeactivatedUser, excludedGroups ); // Create query from sql SQLQuery query = session.createSQLQuery(sql); // Now we need to map types to columns query.addScalar("userId", Type.LONG); query.addScalar("screenName", Type.STRING); query.addScalar("firstName", Type.STRING); query.addScalar("middleName", Type.STRING); query.addScalar("lastName", Type.STRING); query.addScalar("presence", Type.STRING); query.addScalar("presenceUpdatedAt", Type.LONG); // Add parameters to query QueryPos queryPos = QueryPos.getInstance(query); queryPos.add(userId); if (excludedGroups.length > 0) { queryPos.add(excludedGroups); } queryPos.add(userId); // Search query needs to be lowered String lowerCaseSearchQuery = searchQuery.toLowerCase(); // Create the like statement for search query String likeStatement = "%" + lowerCaseSearchQuery + "%"; // There are 3 possible columns we are about to search // (first name, middle name, last name, screen name, email address) for (int i = 0; i < SEARCH_COLUMN_COUNT; i++) { queryPos.add(likeStatement); queryPos.add(lowerCaseSearchQuery); } // Return the result return (List<Object[]>) QueryUtil.list(query, getDialect(), start, end); } finally { // Session needs to be closed if something goes wrong closeSession(session); } } /** * Generates SQL for find all users query * * @param ignoreDefaultUser determines if the default user should be ignored * @param ignoreDeactivatedUser determines if the deactivated user should be ignored * @return SQL string for find all users query */ private String getFindAllUsersSQL(boolean ignoreDefaultUser, boolean ignoreDeactivatedUser) { // Get custom query sql (check /src/custom-sql/default.xml) String sql = CustomSQLUtil.get(FIND_ALL_USERS); // Add ignored users queries if needed sql = addIgnoreDefaultUserToSql(sql, ignoreDefaultUser); sql = addIgnoreDeactivatedUserToSql(sql, ignoreDeactivatedUser); return sql; } /** * Generates SQL for search all users query * * @param searchQuery search keyword * @param ignoreDefaultUser determines if the default user should be ignored * @param ignoreDeactivatedUser determines if the deactivated user should be ignored * @return SQL string for search all users query */ private String getSearchAllUsersSQL(String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser) { // Get custom query sql (check /src/custom-sql/default.xml) String sql = CustomSQLUtil.get(SEARCH_ALL_USERS); // Replace and_or_null operator, false means that this is a conjunction // https://www.liferay.com/community/wiki/-/wiki/Main/Custom+queries+in+Liferay sql = CustomSQLUtil.replaceAndOperator(sql, false); // Add ignored users queries if needed sql = addIgnoreDefaultUserToSql(sql, ignoreDefaultUser); sql = addIgnoreDeactivatedUserToSql(sql, ignoreDeactivatedUser); sql = addSearchParametersToSql(sql, searchQuery); return sql; } /** * Generates SQL for search sites buddies query * * @param searchQuery search keyword * @param ignoreDefaultUser determines if the default user should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param excludedSites name of sites that should be excluded from the query * @return SQL string for search sites query */ private String getSearchSitesBuddiesSQL(String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedSites) { // Get custom sql (check /src/custom-sql/default.xml) String sql = CustomSQLUtil.get(SEARCH_BY_SITES_GROUPS); // Replace and_or_null operator, false means that this is a conjunction // https://www.liferay.com/community/wiki/-/wiki/Main/Custom+queries+in+Liferay sql = CustomSQLUtil.replaceAndOperator(sql, false); // Add ignored users queries if needed sql = addIgnoreDefaultUserToSql(sql, ignoreDefaultUser); sql = addIgnoreDeactivatedUserToSql(sql, ignoreDeactivatedUser); sql = addSearchParametersToSql(sql, searchQuery); sql = addExcludedSitesToSQL(sql, excludedSites); return sql; } /** * Generates SQL for search by social buddies query * * @param searchQuery search keyword * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param types relation types that should be counted in * @return SQL string for find by sites groups query */ private String getSearchSocialBuddiesSQL(String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, int[] types) { // Get custom sql (check /src/custom-sql/default.xml) String sql = CustomSQLUtil.get(SEARCH_BY_SOCIAL_GROUPS); // Replace and_or_null operator, false means that this is a conjunction // https://www.liferay.com/community/wiki/-/wiki/Main/Custom+queries+in+Liferay sql = CustomSQLUtil.replaceAndOperator(sql, false); // Add ignored users queries if needed sql = addIgnoreDefaultUserToSql(sql, ignoreDefaultUser); sql = addIgnoreDeactivatedUserToSql(sql, ignoreDeactivatedUser); sql = addSearchParametersToSql(sql, searchQuery); sql = addSocialRelationTypesToSQL(sql, types); return sql; } /** * Generates SQL for find by sites groups query * * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param excludedSites names of groups that should be excluded from the query * @return SQL string for find by sites groups query */ private String getFindBySitesGroupsSQL(boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedSites) { // Get custom query sql (check /src/custom-sql/default.xml) String sql = CustomSQLUtil.get(FIND_BY_SITES_GROUPS); // Add ignore default user query if needed sql = addIgnoreDefaultUserToSql(sql, ignoreDefaultUser); sql = addIgnoreDeactivatedUserToSql(sql, ignoreDeactivatedUser); sql = addExcludedSitesToSQL(sql, excludedSites); return sql; } /** * Generates SQL for find by social groups query * * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param types relation types that should be counted in * @return SQL string for find by social groups query */ private String getFindSocialGroupsSQL(boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, int[] types) { // Get custom query sql (check /src/custom-sql/default.xml) String sql = CustomSQLUtil.get(FIND_BY_SOCIAL_GROUPS); // Add ignore user queries if needed sql = addIgnoreDefaultUserToSql(sql, ignoreDefaultUser); sql = addIgnoreDeactivatedUserToSql(sql, ignoreDeactivatedUser); sql = addSocialRelationTypesToSQL(sql, types); return sql; } /** * Generates SQL for find by user groups query * * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param excludedGroups names of groups that should be excluded from the query * @return SQL string for find by sites groups query */ private String getFindByUserGroupsSQL(boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedGroups) { // Get custom query sql (check /src/custom-sql/default.xml) String sql = CustomSQLUtil.get(FIND_BY_USER_GROUPS); // Add ignore user queries if needed sql = addIgnoreDefaultUserToSql(sql, ignoreDefaultUser); sql = addIgnoreDeactivatedUserToSql(sql, ignoreDeactivatedUser); sql = addExcludedUserGroupsToSQL(sql, excludedGroups); return sql; } /** * Generates SQL for find by user groups query * * @param searchQuery search query string * @param ignoreDefaultUser true if default users should be ignored * @param ignoreDeactivatedUser true if deactivated users should be ignored * @param excludedGroups names of groups that should be excluded from the query * @return SQL string for search by sites groups query */ private String getSearchUserGroupsSQL(String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedGroups) { // Get custom query sql (check /src/custom-sql/default.xml) String sql = CustomSQLUtil.get(SEARCH_BY_USER_GROUPS); // Replace and_or_null operator, false means that this is a conjunction // https://www.liferay.com/community/wiki/-/wiki/Main/Custom+queries+in+Liferay sql = CustomSQLUtil.replaceAndOperator(sql, false); // Add ignore user queries if needed sql = addIgnoreDefaultUserToSql(sql, ignoreDefaultUser); sql = addIgnoreDeactivatedUserToSql(sql, ignoreDeactivatedUser); sql = addSearchParametersToSql(sql, searchQuery); sql = addExcludedUserGroupsToSQL(sql, excludedGroups); return sql; } /** * Takes sql string from parameter and replaces default user placeholder * if set to true in ignoreDefaultUser parameter * * @param sql String * @param ignoreDefaultUser boolean * @return updated sql string */ private String addIgnoreDefaultUserToSql(String sql, boolean ignoreDefaultUser) { // Add ignore default user query if needed if (ignoreDefaultUser) { return StringUtil.replace(sql, PLACEHOLDER_DEFAULT_USER, "AND (User_.defaultUser != [$TRUE$])"); } else { return StringUtil.replace(sql, PLACEHOLDER_DEFAULT_USER, StringPool.BLANK); } } /** * Takes sql string from parameter and replaces default user placeholder * if set to true in ignoreDefaultUser parameter * * @param sql String * @param ignoreDeactivatedUser boolean * @return updated sql string */ private String addIgnoreDeactivatedUserToSql(String sql, boolean ignoreDeactivatedUser) { // Add ignore default user query if needed if (ignoreDeactivatedUser) { return StringUtil.replace(sql, PLACEHOLDER_DEACTIVATED_USER, "AND (User_.status = 0)"); } else { return StringUtil.replace(sql, PLACEHOLDER_DEACTIVATED_USER, StringPool.BLANK); } } /** * Takes sql string from parameter and replaces excluded sites placeholder with excludedSites * as array taken from the parameter * * @param sql String * @param excludedSites String[] * @return updated sql string */ private String addExcludedSitesToSQL(String sql, String[] excludedSites) { // If no excluded groups are set clear placeholders and return custom sql if (excludedSites.length == 0) { return StringUtil.replace(sql, new String[]{PLACEHOLDER_USERS_GROUPS_JOIN, PLACEHOLDER_USERS_GROUPS_WHERE}, new String[]{StringPool.BLANK, StringPool.BLANK}); } // Otherwise, we need to build a query which will excluded proper sites StringBundler sb = new StringBundler(excludedSites.length * 2 - 1); for (int i = 0; i < excludedSites.length; i++) { // Add question mark so we can add parameters sb.append(StringPool.QUESTION); // Add comma if not at the end if ((i + 1) < excludedSites.length) { sb.append(StringPool.COMMA); } } return StringUtil.replace(sql, new String[]{PLACEHOLDER_USERS_GROUPS_JOIN, PLACEHOLDER_USERS_GROUPS_WHERE}, new String[]{ "INNER JOIN Group_ ON Group_.groupId = Users_Groups.groupId", "AND Group_.name NOT IN (" + sb.toString() + ")" }); } /** * Takes sql string from parameter and replaces relation types placeholder with types taken * from the parameter * * @param sql String * @param types int[] * @return updated sql string */ private String addSocialRelationTypesToSQL(String sql, int[] types) { // We need to build a query which will add all relation types StringBundler sb = new StringBundler(types.length * 2 - 1); for (int i = 0; i < types.length; i++) { // Add question mark so we can add parameters sb.append(StringPool.QUESTION); // Add comma if not at the end if ((i + 1) < types.length) { sb.append(StringPool.COMMA); } } return StringUtil.replace(sql, PLACEHOLDER_SOCIAL_RELATION_TYPES, "SocialRelation.type_ IN (" + sb.toString() + ")"); } /** * Takes sql string from parameter and replaces excluded groups placeholder with excludedGroups * as array taken from the parameter * * @param sql String * @param excludedGroups String[] * @return updated sql string */ private String addExcludedUserGroupsToSQL(String sql, String[] excludedGroups) { // If no excluded groups are set clear placeholders and return custom sql if (excludedGroups.length == 0) { return StringUtil.replace(sql, new String[]{PLACEHOLDER_USERS_GROUPS_JOIN, PLACEHOLDER_USERS_GROUPS_WHERE}, new String[]{StringPool.BLANK, StringPool.BLANK}); } // Otherwise, we need to build a query which will excluded proper sites StringBundler sb = new StringBundler(excludedGroups.length * 2 - 1); for (int i = 0; i < excludedGroups.length; i++) { // Add question mark so we can add parameters sb.append(StringPool.QUESTION); // Add comma if not at the end if ((i + 1) < excludedGroups.length) { sb.append(StringPool.COMMA); } } return StringUtil.replace(sql, new String[]{PLACEHOLDER_USERS_GROUPS_JOIN, PLACEHOLDER_USERS_GROUPS_WHERE}, new String[]{ "INNER JOIN UserGroup ON UserGroup.userGroupId = Users_UserGroups.userGroupId", "AND UserGroup.name NOT IN (" + sb.toString() + ")" }); } /** * Takes sql string from parameter and replaces placeholders with search query * * @param sql String * @param searchQuery String * @return updates sql string */ private String addSearchParametersToSql(String sql, String searchQuery) { // Search query needs to be in a lower case since we are lower the columns as well String lowerCaseSearchQuery = searchQuery.toLowerCase(); // Replace sql = CustomSQLUtil.replaceKeywords( sql, "lower(User_.firstName)", StringPool.LIKE, false, new String[]{lowerCaseSearchQuery}); sql = CustomSQLUtil.replaceKeywords( sql, "lower(User_.middleName)", StringPool.LIKE, false, new String[]{lowerCaseSearchQuery}); sql = CustomSQLUtil.replaceKeywords( sql, "lower(User_.lastName)", StringPool.LIKE, false, new String[]{lowerCaseSearchQuery}); sql = CustomSQLUtil.replaceKeywords( sql, "lower(User_.screenName)", StringPool.LIKE, false, new String[]{lowerCaseSearchQuery}); sql = CustomSQLUtil.replaceKeywords( sql, "lower(User_.emailAddress)", StringPool.LIKE, true, new String[]{lowerCaseSearchQuery}); return sql; } }
9242f269fd3826e31ec6fc5e908d3cf5c7a00e96
1,915
java
Java
kafka/src/main/java/org/apache/rocketmq/kafka/protocol/response/AlterClientQuotasResponse.java
zhiweiqiang/rocketmq
f7c16dc05fb5d48b073407ddd0688584bff17137
[ "Apache-2.0" ]
null
null
null
kafka/src/main/java/org/apache/rocketmq/kafka/protocol/response/AlterClientQuotasResponse.java
zhiweiqiang/rocketmq
f7c16dc05fb5d48b073407ddd0688584bff17137
[ "Apache-2.0" ]
null
null
null
kafka/src/main/java/org/apache/rocketmq/kafka/protocol/response/AlterClientQuotasResponse.java
zhiweiqiang/rocketmq
f7c16dc05fb5d48b073407ddd0688584bff17137
[ "Apache-2.0" ]
1
2021-09-16T10:23:20.000Z
2021-09-16T10:23:20.000Z
24.551282
71
0.641253
1,002,476
package org.apache.rocketmq.kafka.protocol.response; import org.apache.rocketmq.kafka.exception.KafkaCode; import org.apache.rocketmq.kafka.protocol.header.ResponseHeader; import org.apache.rocketmq.remoting.exception.RemotingCommandException; import java.util.List; public class AlterClientQuotasResponse extends ResponseHeader { private List<EntryResponse> entries; public List<EntryResponse> getEntries() { return entries; } public void setEntries(List<EntryResponse> entries) { this.entries = entries; } @Override public void checkFields() throws RemotingCommandException { } public static final class EntryResponse { private KafkaCode errorCode; private String errorMessage; private List<EntityResponse> entities; public KafkaCode getErrorCode() { return errorCode; } public void setErrorCode(KafkaCode errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public List<EntityResponse> getEntities() { return entities; } public void setEntities(List<EntityResponse> entities) { this.entities = entities; } } public static final class EntityResponse { private String entityType; private String entityName; public String getEntityType() { return entityType; } public void setEntityType(String entityType) { this.entityType = entityType; } public String getEntityName() { return entityName; } public void setEntityName(String entityName) { this.entityName = entityName; } } }
9242f3986cab2ffdf30172f3bd93d4939a051605
414
java
Java
src/main/java/com/lee/spider/Main.java
KisetsuLee/spider
1baa1e0a9746ef450dfebb98571d8d6aa7c83d84
[ "MIT" ]
1
2020-03-09T11:01:36.000Z
2020-03-09T11:01:36.000Z
src/main/java/com/lee/spider/Main.java
KisetsuLee/spider
1baa1e0a9746ef450dfebb98571d8d6aa7c83d84
[ "MIT" ]
1
2022-01-21T23:39:13.000Z
2022-01-21T23:39:13.000Z
src/main/java/com/lee/spider/Main.java
KisetsuLee/spider
1baa1e0a9746ef450dfebb98571d8d6aa7c83d84
[ "MIT" ]
null
null
null
20.7
73
0.608696
1,002,477
package com.lee.spider; import com.lee.spider.dao.SpiderDAO; import com.lee.spider.dao.SpiderDAOImpl; /** * Description: * User: Lzj * Date: 2020-03-10 * Time: 15:53 */ public class Main { public static void main(String[] args) { SpiderDAO spiderDAO = new SpiderDAOImpl("db/mybatis/config.xml"); for (int i = 0; i < 8; i++) { new Spider(spiderDAO).start(); } } }