blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
606881dee5688e47521367e9220a9c86a6bf6cb2
782831d070d5233db071fde183a45244de3b4106
/src/newtimes/preproduction/process/AbleToEditLockinStyle.java
7c6af15cefd9c918537e42c322306b6492be0898
[]
no_license
leetungchi/AS_newtimesApp
d71c83f2488d57305b835f7196db77bbdb57bd91
359168c78c293f900a393847b04f8caf812a2eef
refs/heads/master
2020-03-23T21:38:21.763324
2018-07-24T07:56:07
2018-07-24T07:56:07
142,121,479
0
0
null
null
null
null
UTF-8
Java
false
false
291
java
package newtimes.preproduction.process; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: </p> * @author not attributable * @version 1.0 */ public interface AbleToEditLockinStyle { public void toEditLockinStyle()throws Exception; }
[ "lee@User-PC" ]
lee@User-PC
8069635f0105f6212b1a7de37730f72e0e5ff2a2
679847a965581810776852303f3355dceadea274
/ADP/src/main/java/com/ADP/configurations/SwaggerConfig.java
2e111fec66e63e22c2a9aaefa363cd62fd9b70e4
[]
no_license
chuongnguyen-karrostech/ADP-TC
22f134ea9883d29576d61c4c1fe49782de56bb7f
5e788974020b130df710772a698d6ac79b7ac353
refs/heads/master
2022-07-06T22:10:26.681613
2020-05-18T08:41:20
2020-05-18T08:41:20
232,721,120
0
0
null
null
null
null
UTF-8
Java
false
false
1,476
java
package com.ADP.configurations; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import static springfox.documentation.builders.PathSelectors.regex; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket productApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.ADP.controller")) .paths(PathSelectors.any()) .build() .apiInfo(metaData()); //PathSelectors.any(); } private ApiInfo metaData() { ApiInfo apiInfo = new ApiInfo( "Driver Portal Rest API", "Spring Boot for Driver Portal Rest API", "1.0", "Terms of service", new Contact("Minh Vo", "www.edulog.com", "[email protected]"), "Apache License Version 2.0", "https://www.apache.org/licenses/LICENSE-2.0"); return apiInfo; } }
4f88a63240dc75290e8b3791b3e2925fe74b1c9f
1c5e8605c1a4821bc2a759da670add762d0a94a2
/src/dahua/fdc/aimcost/app/CostSplitEntryControllerLocal.java
d32c26947520e4a941632b8088b3b9c89c32d241
[]
no_license
shxr/NJG
8195cfebfbda1e000c30081399c5fbafc61bb7be
1b60a4a7458da48991de4c2d04407c26ccf2f277
refs/heads/master
2020-12-24T06:51:18.392426
2016-04-25T03:09:27
2016-04-25T03:09:27
19,804,797
0
3
null
null
null
null
UTF-8
Java
false
false
162
java
package com.kingdee.eas.fdc.aimcost.app; import javax.ejb.*; public interface CostSplitEntryControllerLocal extends EJBLocalObject, CostSplitEntryController { }
9218b7c821d39bfebad03a320bcd08ede0ea7026
29048e134321357261bafe2f32f80c591bbb12fe
/src/ali/software/Clients.java
551ea87120d1e42ded6ab2a98b9b8d62852e25fb
[]
no_license
Leuzi/CarnicasSidiAndroid
1d803a61ae94aacf2a05bb56975e3c5a29986f17
b89561b359af0362eaff9d381519332ea75c4882
refs/heads/master
2016-09-05T10:17:36.230725
2015-04-24T19:40:51
2015-04-24T19:40:51
32,416,541
0
0
null
null
null
null
UTF-8
Java
false
false
8,646
java
package ali.software; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import ali.clases.DBHandler; import ali.clases.GlobalStatic; import ali.clases.LineaFactura; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.util.Pair; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Spinner; public class Clients extends Activity { //Declaración del botón Atras //Declaración del ListView list private Button back; private ListView list; private Button todosButton; private Button lastButton; private Button bestButton; private Spinner selection; private ArrayList<Pair<String,String>> last; private ArrayList<Pair<String,String>> names; private ArrayList<Pair<String,String>> best; //Cuando se crea public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.clientlist); //Asociar al layout //Asociar elementos con su correspondiente elemento en la IU back = (Button) findViewById(R.id.backButton); todosButton = (Button) findViewById(R.id.TodosButton); lastButton = (Button) findViewById(R.id.UltimosButton); bestButton = (Button) findViewById(R.id.Mejores); list = (ListView) findViewById(R.id.listClient); list.setDivider(null); //Recolectar datos globales final GlobalStatic data = (GlobalStatic) getApplication(); //ArrayList con los nombres de los clientes names = data.getNameClients(); DBHandler BD = new DBHandler(this); last = BD.getLastClients(); best = BD.getBestClients(null,null); selection = (Spinner) findViewById(R.id.selectDate); //Creamos el adaptador ArrayAdapter<CharSequence> adaptadorfechas = ArrayAdapter.createFromResource(this,R.array.optionsDate,android.R.layout.simple_spinner_item); //Añadimos el layout para el menú adaptadorfechas.setDropDownViewResource(android.R.layout.simple_spinner_item); //Le indicamos al spinner el adaptador a usar selection.setAdapter(adaptadorfechas); selection.setSelection(0); //Si estamos creando/editando clientes if(data.seleccionandoClientesAnual == false && data.seleccionandoClientesDiaria==false&& data.seleccionandoClientesDiaria2==false){ //Añadir un elemento "Nuevo cliente" Resources res = getResources(); String text = String.format(res.getString(R.string.newClient)); names.add(0,new Pair<String,String>(text,""));// last.add(0,new Pair<String,String>(text,"")); best.add(0,new Pair<String,String>(text,"")); } ItemAdapter adapter = new ItemAdapter(this, names); selection.setVisibility(View.INVISIBLE); //Establecer el adaptador list.setAdapter(adapter); todosButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ItemAdapter adapter = new ItemAdapter(getApplicationContext(), names); //Establecer el adaptador list.setAdapter(adapter); // TODO Auto-generated method stub selection.setVisibility(View.INVISIBLE); } }); lastButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ItemAdapter adapter = new ItemAdapter(getApplicationContext(), last); //Establecer el adaptador list.setAdapter(adapter); // TODO Auto-generated method stub selection.setVisibility(View.INVISIBLE); } }); bestButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ItemAdapter adapter = new ItemAdapter(getApplicationContext(), best); //Establecer el adaptador list.setAdapter(adapter); // TODO Auto-generated method stub selection.setVisibility(View.VISIBLE); } }); //Al pulsar back back.setOnClickListener(new View.OnClickListener() { //Ir a el menu principal @Override public void onClick(View v) { // TODO Auto-generated method stub GlobalStatic data = (GlobalStatic) getApplicationContext(); data.seleccionandoClientesDiaria2=false; Intent intent = null; if(data.seleccionandoClientesDiaria){ intent = new Intent(Clients.this,BillForm.class); } else{ intent = new Intent(Clients.this,AliActivity.class); } startActivity(intent); } }); selection.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { // TODO Auto-generated method stub java.util.Date inicio; java.util.Date fin; fin = Calendar.getInstance().getTime(); inicio = Calendar.getInstance().getTime(); Calendar cal = Calendar.getInstance(); switch (position) { case 0://Todas inicio = null; fin = null; break; case 1: //Hoy inicio.setHours(0); inicio.setMinutes(0); inicio.setSeconds(1); break; case 2: //Ayer cal.add(Calendar.DATE, -1); inicio = cal.getTime(); fin = cal.getTime(); inicio.setHours(0); inicio.setMinutes(0); inicio.setSeconds(1); fin.setHours(23); fin.setMinutes(59); fin.setSeconds(59); break; case 3: //Ultima semana cal.add(Calendar.DATE, -7); inicio = cal.getTime(); inicio.setHours(0); inicio.setMinutes(0); inicio.setSeconds(1); break; case 4: //Ultimo mes cal.add(Calendar.MONTH, -1); inicio = cal.getTime(); inicio.setHours(0); inicio.setMinutes(0); inicio.setSeconds(1); break; case 5: //Tres meses cal.add(Calendar.MONTH, -3); inicio = cal.getTime(); inicio.setHours(0); inicio.setMinutes(0); inicio.setSeconds(1); break; case 6: //Ultimo año cal.add(Calendar.YEAR, -1); inicio = cal.getTime(); inicio.setHours(0); inicio.setMinutes(0); inicio.setSeconds(1); break; default: break; } DBHandler BD = new DBHandler(getApplicationContext()); best = BD.getBestClients(inicio,fin); ItemAdapter adaptador = new ItemAdapter(getApplicationContext(),best); list.setAdapter(adaptador); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view,int position, long id) { //Obtener el nombre clickado @SuppressWarnings("unchecked") Pair<String,String> clientes = (Pair<String,String>) list.getItemAtPosition(position); String clientName =clientes.first; Resources res = getResources(); String text = String.format(res.getString(R.string.newClient)); //Si no se ha pulsado el boton "Nuevo Cliente" if(!clientName.equals(text)){ //Seleccionar ese cliente data.cliente = data.getCliente(clientName); } else{ data.cliente=null; } Intent intent = null; //Si estamos seleccionando un cliente para una //Factura anual/mensual if(data.seleccionandoClientesAnual){ intent = new Intent(Clients.this,AnualDateSelection.class); } //Si estamos seleccionando un cliente para una facura diaria //Vamos a las facturas diarias else if(data.seleccionandoClientesDiaria){ intent = new Intent(Clients.this,BillForm.class); Iterator<LineaFactura> it =data.factura.getLines().iterator(); while(it.hasNext()){ LineaFactura linea = it.next(); if(data.cliente.getPrecios().containsKey(linea.getName())){ Object obj = data.cliente.getPrecios().get(linea.getName()); double prize = (Double) obj; linea.setPrize(prize); } } } else if(data.seleccionandoClientesDiaria2){ data.seleccionandoClientesDiaria2=false; intent = new Intent(Clients.this,DiarySelection.class); } else{//Ir al formulario de clientes intent = new Intent(Clients.this,ClientsForm.class); } //Damos la entrada a la correspondiente actividad startActivity(intent); } }); } }
853904d6cd0d10206c9329097b656e5e3e77d6ed
da81cd26cd80372fa0cb89a1a15d6a634cb01d62
/app/src/main/java/kr/contentsstudio/myfirstandroidapp/com/listview/MyAdapter.java
cab607195138fc8dd2b0dd5c5bd0ae99e5f6a01a
[]
no_license
hyleekr9580/MyAndroid01
fefd08b9a196e018ab2355f4ec5ed3536cc88d81
4cb76a8cd4a493358dc72b2c7a56c7a659977977
refs/heads/master
2016-08-10T22:47:42.652475
2016-04-13T07:27:44
2016-04-13T07:27:44
51,041,297
0
0
null
null
null
null
UTF-8
Java
false
false
4,128
java
package kr.contentsstudio.myfirstandroidapp.com.listview; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import kr.contentsstudio.myfirstandroidapp.R; public class MyAdapter extends BaseAdapter { private final LayoutInflater minflater; private Context mContext; private List<Myitem> mData; //생성자를 만들고 context를 무조검 받아야 한다. public MyAdapter(Context context, List<Myitem> data) { mContext = context; mData = data; minflater = LayoutInflater.from(mContext); } // 어뎁터가 가지고 있는 아이템의 개수를 지정하는 곳이다. @Override public int getCount() { return mData.size(); } // position 번째 있는 아이템을 리턴 해주는 메소드 @Override public Object getItem(int position) { return mData.get(position); } // position 번째 아이템의 ID를 리턴 @Override public long getItemId(int position) { return position; } // 가장중요한 부분 // 아이템 한개의 view를 완성하는 곳 //position(위치) / convertView(한칸의뷰) / parent(부모 리스트뷰) //getView는 소비가 너무 많다. inflater, findViewById, 등 뷰홀더패턴을 사용하면 소비를 줄일 수 있다. @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHoler holder; //최초의 뷰가 생겼을때 아무것도 없다. null로 들어 온다 null인지 아닌지 확인 if (convertView == null) { holder = new ViewHoler(); //최초 로드 할때 convertView는 아무것도 없다. // xml 로드 해야 한다. findviewbyid는 없다. //context를 이용해서 가지고 와야 한다. // 레이아웃을 가지고 오게 하는 객체 //LayoutInflater.from(mContext) //LayoutInflater inflater = LayoutInflater.from(mContext); //findviewbyid 와 같은 역활을 한다. convertView = minflater.inflate(R.layout.item_list, parent, false); ImageView imageView = (ImageView) convertView.findViewById(R.id.title_img); TextView title = (TextView) convertView.findViewById(R.id.title_text); TextView description = (TextView) convertView.findViewById(R.id.title_itemtext); holder.imageView = imageView; holder.title = title; holder.description = description; //이상한 짓ㅅ을 한다... //setTag,,,getTag를 잘 알 고 있어라~~ 사용할때가 있다.~~~ convertView.setTag(holder); } else { //재활용할때 사용한다... 필요는 없다. holder = (ViewHoler) convertView.getTag(); } //둘중 하나 사용해도 된다. Myitem item = mData.get(position); //Myitem item2 = (Myitem) getItem(position); //꽂아 줄꺼다~~~~ convertView에서 들고 온다. 텍스트 타이틀 //데이터 연결하기 할꺼다~~~ ( 데이터 설정) //구글 페이지.... holder 사용했고 스레드를 이용해서 백그라운드에서 로딩 하면서 사용 하고 있다. holder.imageView.setImageResource(item.getImageRes()); holder.title.setText(item.getTitle()); holder.description.setText(item.getDescription()); if (position % 2 == 0) { convertView.setBackgroundColor(Color.BLUE); } else { convertView.setBackgroundColor(Color.RED); } //완성품은 리턴 return convertView; } //뷰홀더패턴 //내부클래스는 static 으로 사용한다고 생각하라. private static class ViewHoler { ImageView imageView; TextView title; TextView description; } }
[ "hoyoung lee" ]
hoyoung lee
18648376238ba640f74892d7c0abf60a1013d619
9df248b92f3478b34266991c0dc985c25ea4cfbe
/Mule_TechInFusion/samplepoc_1/src/main/java/com/esper/event/object/TopSellingItem.java
caa99ca02ac9caa55d5276572cca826647ea813f
[]
no_license
BharatHimesh/ShopNext-2.0
444325e2c25999265abbd8d30076aaab40584d54
1f3e780ce3bb28c87d1370037c949705c48096df
refs/heads/master
2021-01-16T21:48:54.413084
2015-01-07T12:46:33
2015-01-07T12:46:33
28,857,085
1
0
null
2015-01-06T09:51:49
2015-01-06T09:51:49
null
UTF-8
Java
false
false
1,051
java
package com.esper.event.object; import org.codehaus.jackson.annotate.JsonAutoDetect; @JsonAutoDetect public class TopSellingItem implements Comparable<TopSellingItem> { private String itemId; private String itemName; private long totalSalesQty; private String segmentName; public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public long getTotalSalesQty() { return totalSalesQty; } public void setTotalSalesQty(long totalSalesQty) { this.totalSalesQty = totalSalesQty; } public int compareTo(TopSellingItem input) { if(totalSalesQty==input.getTotalSalesQty()) { return 0; } else if(totalSalesQty<input.getTotalSalesQty()) { return 1; } else { return -1; } } public String getSegmentName() { return segmentName; } public void setSegmentName(String segmentName) { this.segmentName = segmentName; } }
cfbb4946e06373616f2389869fb793271784058d
a75f4b88ee8bf0a9a596bdf10ac51be2cc5aa5f7
/app/src/main/java/deliveryapp/saalventure/madrasmarket/Fragment/Order_history.java
2623b2c0d69f04f0c4a7beab8cd193aefe40932d
[]
no_license
chandu-v/madras-market-delivery-app
653dda00c92cc581d67f71ed46e8e6424da0a16a
33d6245d41bfeb6d2030b2663409917c2f54635c
refs/heads/master
2023-04-13T19:29:54.920154
2020-08-26T09:58:52
2020-08-26T09:58:52
286,186,823
0
0
null
null
null
null
UTF-8
Java
false
false
20,910
java
package deliveryapp.saalventure.madrasmarket.Fragment; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.Toast; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.android.volley.AuthFailureError; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import deliveryapp.saalventure.madrasmarket.Adapter.Delivered_historyAdapter; import deliveryapp.saalventure.madrasmarket.Adapter.Delivered_monthly_adapter; import deliveryapp.saalventure.madrasmarket.Adapter.Delivered_weekly_adapter; import deliveryapp.saalventure.madrasmarket.AppController; import deliveryapp.saalventure.madrasmarket.Config.BaseURL; import deliveryapp.saalventure.madrasmarket.Model.Daily_model; import deliveryapp.saalventure.madrasmarket.Model.Monthly_model; import deliveryapp.saalventure.madrasmarket.Model.My_order_model; import deliveryapp.saalventure.madrasmarket.Model.Weekly_model; import deliveryapp.saalventure.madrasmarket.R; import deliveryapp.saalventure.madrasmarket.util.CustomVolleyJsonArrayRequest; import deliveryapp.saalventure.madrasmarket.util.Session_management; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.android.volley.VolleyLog.TAG; /** * A simple {@link Fragment} subclass. */ public class Order_history extends Fragment { RecyclerView rc_today, rc_weekly, rc_monthlky; List<Weekly_model> weekly_modelist = new ArrayList<>(); List<Monthly_model> monthly_modelList = new ArrayList<>(); Delivered_weekly_adapter delivered_weekly_adapter; Session_management sessionManagement; String get_id; String currentdate; LinearLayout daily_layout, weekly_layout, monthly_layout; Delivered_monthly_adapter delivered_monthly_adapter; Delivered_historyAdapter delivered_dailyAdapter; private ProgressDialog progressDialog; private List<Daily_model> daily_modellist = new ArrayList<>(); public Order_history() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_order_history, container, false); progressDialog = new ProgressDialog(container.getContext()); progressDialog.setMessage("Please wait while we fetching your Deliverd Orders History.."); progressDialog.setCancelable(false); rc_today = view.findViewById(R.id.rc_daily); rc_weekly = view.findViewById(R.id.rc_weekly); rc_monthlky = view.findViewById(R.id.rc_monthly); daily_layout = view.findViewById(R.id.daily_layout); monthly_layout = view.findViewById(R.id.monthly_layout); weekly_layout = view.findViewById(R.id.weekly_layout); sessionManagement = new Session_management(getActivity()); get_id = sessionManagement.getUserDetails().get(BaseURL.KEY_ID); rc_today.setLayoutManager(new LinearLayoutManager(getActivity())); rc_weekly.setLayoutManager(new LinearLayoutManager(getActivity())); rc_monthlky.setLayoutManager(new LinearLayoutManager(getActivity())); getorder_history(); // weekly_history(); // monthly_history(); return view; } private void getorder_history() { progressDialog.show(); String tag_json_obj = "json_socity_req"; HashMap<String, String> param = new HashMap<>(); param.put("dboy_id", get_id); JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, "https://madrasmarketplaceapi.azurewebsites.net/order_master/getAllOrdersByStatusId/2/"+get_id, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { if (response.length()==0) { daily_layout.setVisibility(View.GONE); // Toast.makeText(requireActivity(), "No Today's Order Found!", Toast.LENGTH_SHORT).show(); } else { for(int i = 0 ; i < response.length() ; i++){ JSONArray jsonObjects = response.getJSONArray(i); String saleid = jsonObjects.get(0).toString(); String placedon = jsonObjects.get(11).toString().split("T")[0]; // String timefrom = obj.getString("time_slot"); String timefrom = jsonObjects.get(11).toString().split("T")[1].split("\\+")[0]; // String timeto=obj.getString("delivery_time_from"); //String item = obj.getString("total_items"); String ammount = jsonObjects.get(3).toString(); String status = jsonObjects.get(2).toString(); String user_address = jsonObjects.get(4).toString()+","+jsonObjects.get(5).toString()+","+jsonObjects.get(6).toString(); // String store_Address = obj.getString("store_address"); // String house = obj.getString("house_no"); String rename = jsonObjects.get(8).toString(); String renumber = jsonObjects.get(7).toString(); String store_name = ""; String total_items = jsonObjects.get(12).toString()==null?"0":jsonObjects.get(12).toString(); // String store_lat = obj.getString("store_lat"); // String store_lng = obj.getString("store_lng"); // String user_lat = obj.getString("user_lat"); // String user_lng = obj.getString("user_lng"); // String dboy_lat = obj.getString("dboy_lat"); // String dboy_lng = obj.getString("dboy_lng"); Daily_model my_order_model = new Daily_model(); // My_order_model my_order_model = new My_order_model(); // my_order_model.setSocityname(society); my_order_model.setHouse(user_address); my_order_model.setRecivername(rename); my_order_model.setRecivermobile(renumber); my_order_model.setDelivery_time_from(timefrom); my_order_model.setSale_id(saleid); my_order_model.setOn_date(placedon); my_order_model.setTotal_amount(ammount); my_order_model.setStatus(status); my_order_model.setStore_name(store_name); my_order_model.setTotal_items(total_items); // my_order_model.setLat(store_lat); // my_order_model.setLng(store_lng); // my_order_model.setUserLat(user_lat); // my_order_model.setUserLong(user_lng); // my_order_model.setDbLat(dboy_lat); // my_order_model.setDbuserLong(dboy_lng); // my_order_model.setTotal_items(item); // my_order_model.setDelivery_time_to(timefrom); daily_modellist.add(my_order_model); delivered_dailyAdapter = new Delivered_historyAdapter(daily_modellist); rc_today.setAdapter(delivered_dailyAdapter); delivered_dailyAdapter.notifyDataSetChanged(); } } } catch (Exception e) { e.printStackTrace(); }finally { progressDialog.dismiss(); // refresh_layout.setRefreshing(false); } } }, error -> { error.printStackTrace(); }); RequestQueue requestQueue = Volley.newRequestQueue(requireContext()); requestQueue.getCache().clear(); jsonArrayRequest.setRetryPolicy(new RetryPolicy() { @Override public int getCurrentTimeout() { return 60000; } @Override public int getCurrentRetryCount() { return 2; } @Override public void retry(VolleyError error) throws VolleyError { } }); requestQueue.add(jsonArrayRequest); Map<String, String> params = new HashMap<String, String>(); params.put("dboy_id", get_id); // params.put("filter","1"); CustomVolleyJsonArrayRequest jsonObjReq = new CustomVolleyJsonArrayRequest(Request.Method.POST, BaseURL.historyOrders, params, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("fghjk", response.toString()); try { for (int i = 0; i < response.length(); i++) { JSONObject obj = response.getJSONObject(i); String saleid = obj.getString("cart_id"); String placedon = obj.getString("delivery_date"); String timefrom = obj.getString("time_slot"); // String timeto = obj.getString("delivery_time_to"); // String item = obj.getString("total_items"); String ammount = obj.getString("remaining_price"); String status = obj.getString("order_status"); String lat = obj.getString("user_lat"); String lng = obj.getString("user_lng"); String house = obj.getString("user_address"); String rename = obj.getString("user_name"); String renumber = obj.getString("user_phone"); String storename = obj.getString("store_name"); Daily_model my_order_model = new Daily_model(); my_order_model.setStore_name(storename); my_order_model.setLat(lat); my_order_model.setLng(lng); my_order_model.setHouse(house); my_order_model.setRecivername(rename); my_order_model.setRecivermobile(renumber); my_order_model.setDelivery_time_from(timefrom); my_order_model.setSale_id(saleid); my_order_model.setOn_date(placedon); // my_order_model.setDelivery_time_to(timeto); my_order_model.setTotal_amount(ammount); my_order_model.setStatus(status); // my_order_model.setTotal_items(item); daily_modellist.add(my_order_model); delivered_dailyAdapter = new Delivered_historyAdapter(daily_modellist); rc_today.setAdapter(delivered_dailyAdapter); delivered_dailyAdapter.notifyDataSetChanged(); } if (daily_modellist.isEmpty()) { daily_layout.setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } finally { progressDialog.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> param = new HashMap<>(); param.put("dboy_id", get_id); return param; } }; // RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); // requestQueue.getCache().clear(); // requestQueue.add(jsonObjReq); } private void weekly_history() { String tag_json_obj = "json_socity_req"; Map<String, String> params = new HashMap<String, String>(); params.put("d_id", get_id); // params.put("filter","2"); CustomVolleyJsonArrayRequest jsonObjReq = new CustomVolleyJsonArrayRequest(Request.Method.POST, BaseURL.todayOrder, params, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { for (int i = 0; i < response.length(); i++) { JSONObject obj = response.getJSONObject(i); String saleid = obj.getString("sale_id"); String placedon = obj.getString("on_date"); String timefrom = obj.getString("delivery_time_from"); String timeto = obj.getString("delivery_time_to"); String item = obj.getString("total_items"); String ammount = obj.getString("total_amount"); String status = obj.getString("status"); String lat = obj.getString("lat"); String lng = obj.getString("lng"); String house = obj.getString("house_no"); String rename = obj.getString("receiver_name"); String renumber = obj.getString("receiver_mobile"); String storename = obj.getString("store_name"); Weekly_model my_order_model = new Weekly_model(); my_order_model.setStore_name(storename); my_order_model.setLat(lat); my_order_model.setLng(lng); my_order_model.setHouse(house); my_order_model.setRecivername(rename); my_order_model.setRecivermobile(renumber); my_order_model.setDelivery_time_from(timefrom); my_order_model.setSale_id(saleid); my_order_model.setOn_date(placedon); my_order_model.setDelivery_time_to(timeto); my_order_model.setTotal_amount(ammount); my_order_model.setStatus(status); my_order_model.setTotal_items(item); weekly_modelist.add(my_order_model); delivered_weekly_adapter = new Delivered_weekly_adapter(weekly_modelist); rc_weekly.setAdapter(delivered_weekly_adapter); delivered_weekly_adapter.notifyDataSetChanged(); } if (weekly_modelist.isEmpty()) { weekly_layout.setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); if (error instanceof TimeoutError || error instanceof NoConnectionError) { Toast.makeText(getActivity(), getResources().getString(R.string.connection_time_out), Toast.LENGTH_SHORT).show(); } } }); AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); } private void monthly_history() { String tag_json_obj = "json_socity_req"; Map<String, String> params = new HashMap<String, String>(); params.put("d_id", get_id); // params.put("filter","3"); CustomVolleyJsonArrayRequest jsonObjReq = new CustomVolleyJsonArrayRequest(Request.Method.POST, BaseURL.todayOrder, params, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { for (int i = 0; i < response.length(); i++) { JSONObject obj = response.getJSONObject(i); String saleid = obj.getString("sale_id"); String placedon = obj.getString("on_date"); String timefrom = obj.getString("delivery_time_from"); String timeto = obj.getString("delivery_time_to"); String item = obj.getString("total_items"); String ammount = obj.getString("total_amount"); String status = obj.getString("status"); String lat = obj.getString("lat"); String lng = obj.getString("lng"); String house = obj.getString("house_no"); String rename = obj.getString("receiver_name"); String renumber = obj.getString("receiver_mobile"); String storename = obj.getString("store_name"); Monthly_model my_order_model = new Monthly_model(); my_order_model.setStore_name(storename); my_order_model.setLat(lat); my_order_model.setLng(lng); my_order_model.setHouse(house); my_order_model.setRecivername(rename); my_order_model.setRecivermobile(renumber); my_order_model.setDelivery_time_from(timefrom); my_order_model.setSale_id(saleid); my_order_model.setOn_date(placedon); my_order_model.setDelivery_time_to(timeto); my_order_model.setTotal_amount(ammount); my_order_model.setStatus(status); my_order_model.setTotal_items(item); monthly_modelList.add(my_order_model); delivered_monthly_adapter = new Delivered_monthly_adapter(monthly_modelList); rc_monthlky.setAdapter(delivered_monthly_adapter); delivered_monthly_adapter.notifyDataSetChanged(); } if (monthly_modelList.isEmpty()) { monthly_layout.setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); if (error instanceof TimeoutError || error instanceof NoConnectionError) { Toast.makeText(getActivity(), getResources().getString(R.string.connection_time_out), Toast.LENGTH_SHORT).show(); } } }); AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); } }
ddf0e8d2523540ab51d58980013ca00e363263ab
9d84c5706bc0a3fb883a640df9487ab442e6bf70
/src/com/sang/AnnotationDemoApp.java
e200af178d15fac9edb48563339d447a233a42af
[]
no_license
LeSangDeveloper/springdemo-annotation-nomaven
33e7cc9c1fd1ee5789b45e6380397f4b242bfde3
05a59ac09a59166f7ddc3d574ae16bcbd10dde62
refs/heads/main
2023-05-03T22:23:07.524869
2021-05-19T01:02:39
2021-05-19T01:02:39
368,572,810
0
0
null
null
null
null
UTF-8
Java
false
false
493
java
package com.sang; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AnnotationDemoApp { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Coach theCoach = context.getBean("tennisCoach", Coach.class); System.out.println(theCoach.getDailyWorkout()); System.out.println(theCoach.getDailyFortune()); } }
0d648195eb314bbcc2af3836612294b65409a00f
d8aee20a3ac5637e9d8465b799f67571b4e68337
/yiKangServer/yiKangServer/src/main/java/com/yikang/app/yikangserver/ui/BaseActivity.java
68ffe7f88b80439aefe25029eb82a9966ccd76af
[]
no_license
yikangmc/yikangAndriod
3ed79d586b82fbd8de56cbcb9ac26870f316dba5
048a39e4a288de2cf8b5cf0705a6e57cb5d73ae6
refs/heads/master
2021-07-14T21:25:08.001578
2016-09-27T02:10:05
2016-09-27T02:10:05
59,449,433
0
0
null
null
null
null
UTF-8
Java
false
false
3,193
java
package com.yikang.app.yikangserver.ui; import android.annotation.TargetApi; import android.app.Activity; import android.app.Dialog; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.view.View; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.TextView; import com.yikang.app.yikangserver.R; import com.yikang.app.yikangserver.interfaces.UINetwork; import com.yikang.app.yikangserver.view.CustomWatingDialog; /** * 基础的Activity,其他activity继承它 * */ public abstract class BaseActivity extends Activity implements UINetwork { @TargetApi(19) protected void initContent() { if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { getWindow().addFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); initStatusBar(getResources().getColor(R.color.statue_bar_color)); } setContentView(); findViews(); getData(); initViewContent(); } @TargetApi(19) protected void initStatusBar(int color) { if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { SystemBarTintManager mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setTintColor(color); } } /** * 初始化Views */ protected abstract void findViews(); /** * &#x521d;&#x59cb;&#x5316;contentView */ protected abstract void setContentView(); /** * 获取数据, */ protected abstract void getData( ); /** * 展示内容 */ protected abstract void initViewContent(); /** * 初始化titlebar,BaseActivity中此方法做了两件事 1.将左上角返回按钮设置点击后返回 2.设置标题为参数title * * 如果子类有不同的布局,或者要做更多的事情,请重写这个方法 * * @param title 要设置的标题 */ protected void initTitleBar(String title) { TextView tvTitle = (TextView) findViewById(R.id.tv_title_text); if (tvTitle != null) // 由于设计上的问题,并不是所有的Activity布局中都有统一的titleBar tvTitle.setText(title); // ImageView ivSetting=(ImageView)findViewById(R.id.iv_title_right) ; ImageButton btBack = (ImageButton) findViewById(R.id.ibtn_title_back); if (btBack != null) // 设置返回监听 btBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private Dialog waitingDialog; public void showWaitingUI() { showWaitingUI(getString(R.string.waiting_loading)); } /** * 显示等待的dialog */ public void showWaitingUI(String message) { if (waitingDialog == null) { waitingDialog = createDialog(message); } if (!waitingDialog.isShowing()) waitingDialog.show(); } /** * dismiss 等待的dialog */ public void hideWaitingUI() { if (waitingDialog != null && waitingDialog.isShowing()) { waitingDialog.dismiss(); } } /** * 创建一个dialog,同过复写这个方法可以创建其他样式的dialog */ protected Dialog createDialog(String message) { return new CustomWatingDialog(this, message); } @Override protected void onStop() { super.onStop(); hideWaitingUI(); } }
c36d4bd7b3bb6f1ee84b53a7dce1bb36c8f93a2d
0a12bd827c3c48add9f5f400763a87ea69631faf
/aop/src/main/java/bboss/org/jgroups/demos/MemcachedServer.java
861ead3f45738609ffce2fa3e6d7bda95a15ccc6
[]
no_license
sqidea/bboss
76c64dea2e0ecd2c8d4b7269021e37f58a5b4071
d889e252d2bbf57681072fcd250a9e4da42f5938
refs/heads/master
2021-01-18T18:50:21.077011
2013-10-15T15:31:53
2013-10-15T15:31:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,170
java
package bboss.org.jgroups.demos; import java.lang.management.ManagementFactory; import java.net.InetAddress; import javax.management.MBeanServer; import bboss.org.jgroups.blocks.Cache; import bboss.org.jgroups.blocks.MemcachedConnector; import bboss.org.jgroups.blocks.PartitionedHashMap; import bboss.org.jgroups.jmx.JmxConfigurator; /** Server process which listens for memcached requests and forwards them to an instance of PartitionedHashMap. * Uses MemcachedConnector and PartitionedHashMap. * @author Bela Ban * @version $Id: MemcachedServer.java,v 1.7 2008/09/03 12:38:49 belaban Exp $ */ public class MemcachedServer { private MemcachedConnector connector; private PartitionedHashMap<String, byte[]> cache; private static final String BASENAME="memcached"; private void start(String props, InetAddress bind_addr, int port, int min_threads, int max_threads, long rpc_timeout, long caching_time, boolean migrate_data, boolean use_l1_cache, int l1_max_entries, long l1_reaping_interval, int l2_max_entries, long l2_reaping_interval) throws Exception { MBeanServer server=ManagementFactory.getPlatformMBeanServer(); connector=new MemcachedConnector(bind_addr, port, null); connector.setThreadPoolCoreThreads(min_threads); connector.setThreadPoolMaxThreads(max_threads); JmxConfigurator.register(connector, server, BASENAME + ":name=connector"); cache=new PartitionedHashMap(props, "memcached-cluster"); cache.setCallTimeout(rpc_timeout); cache.setCachingTime(caching_time); cache.setMigrateData(migrate_data); JmxConfigurator.register(cache, server, BASENAME + ":name=cache"); JmxConfigurator.register(cache.getL2Cache(), server, BASENAME + ":name=l2-cache"); if(use_l1_cache) { Cache<String,byte[]> l1_cache=new Cache<String,byte[]>(); cache.setL1Cache(l1_cache); if(l1_reaping_interval > 0) l1_cache.enableReaping(l1_reaping_interval); if(l1_max_entries > 0) l1_cache.setMaxNumberOfEntries(l1_max_entries); JmxConfigurator.register(cache.getL1Cache(), server, BASENAME + ":name=l1-cache"); } if(l2_max_entries > 0 || l2_reaping_interval > 0) { Cache<String,byte[]> l2_cache=cache.getL2Cache(); if(l2_max_entries > 0) l2_cache.setMaxNumberOfEntries(l2_max_entries); if(l2_reaping_interval > 0) l2_cache.enableReaping(l2_reaping_interval); } connector.setCache(cache); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { cache.stop(); try {connector.stop();} catch(Exception e) {} } }); cache.start(); connector.start(); } public static void main(String[] args) throws Exception { InetAddress bind_addr=null; int port=11211; String props="udp.xml"; int min_threads=1, max_threads=500; long rpc_timeout=1500L, caching_time=30000L; boolean migrate_data=true, use_l1_cache=true; int l1_max_entries=5000, l2_max_entries=-1; long l1_reaping_interval=-1, l2_reaping_interval=30000L; for(int i=0; i < args.length; i++) { if(args[i].equals("-bind_addr")) { bind_addr=InetAddress.getByName(args[++i]); continue; } if(args[i].equals("-port") || args[i].equals("-p")) { port=Integer.parseInt(args[++i]); continue; } if(args[i].equals("-props")) { props=args[++i]; continue; } if(args[i].equals("-min_threads")) { min_threads=Integer.parseInt(args[++i]); continue; } if(args[i].equals("-max_threads")) { max_threads=Integer.parseInt(args[++i]); continue; } if(args[i].equals("-rpc_timeout")) { rpc_timeout=Long.parseLong(args[++i]); continue; } if(args[i].equals("-caching_time")) { caching_time=Long.parseLong(args[++i]); continue; } if(args[i].equals("-migrate_data")) { migrate_data=Boolean.parseBoolean(args[++i]); continue; } if(args[i].equals("-use_l1_cache")) { use_l1_cache=Boolean.parseBoolean(args[++i]); continue; } if(args[i].equals("-l1_max_entries")) { l1_max_entries=Integer.parseInt(args[++i]); continue; } if(args[i].equals("-l1_reaping_interval")) { l1_reaping_interval=Long.parseLong(args[++i]); continue; } if(args[i].equals("-l2_max_entries")) { l2_max_entries=Integer.parseInt(args[++i]); continue; } if(args[i].equals("-l2_reaping_interval")) { l2_reaping_interval=Long.parseLong(args[++i]); continue; } help(); return; } new MemcachedServer().start(props, bind_addr, port, min_threads, max_threads, rpc_timeout, caching_time, migrate_data, use_l1_cache, l1_max_entries, l1_reaping_interval, l2_max_entries, l2_reaping_interval); } private static void help() { System.out.println("MemcachedServer [-help] [-bind_addr <address>] [-port <port>] [-props <props>] " + "[-min_threads <min>] [-max_threads <max>] [-rpc_timeout <ms>] [-caching_time <ms>] " + "[-migrate_data <true|false>] [-use_l1_cache <true|false>] " + "[-l1_max_entries <num>] [-l1_reaping_interval <ms>] " + "[-l2_max_entries <num>] [-l2_reaping_interval <ms>] "); } }
1cd33a9eb86f59d0a90f19d7952e07f8dcc4dc49
75d66933c180933400d6524bb8a1109484690f7b
/src/main/java/dash/dashmode/blockentity/StackHolderBlockEntity.java
bda0ba76c1edcd7366bf5fc93d67515a75395e4c
[ "MIT" ]
permissive
Oshi41/RandomContent
4f42c0588e54b82589bcf79f9fb1ad84ec3e2cb3
e577e7d6fabc869570964b7006b6bf921d94ac49
refs/heads/master
2023-01-24T10:05:46.806993
2020-12-04T15:51:27
2020-12-04T15:51:27
299,348,099
1
0
null
null
null
null
UTF-8
Java
false
false
3,936
java
package dash.dashmode.blockentity; import dash.dashmode.registry.DashBlockEntities; import net.fabricmc.fabric.api.event.player.AttackBlockCallback; import net.fabricmc.fabric.api.event.player.UseBlockCallback; import net.minecraft.block.Block; import net.minecraft.block.entity.LockableContainerBlockEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.Inventories; import net.minecraft.item.ItemStack; import net.minecraft.screen.ScreenHandler; import net.minecraft.text.Text; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.collection.DefaultedList; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.World; public class StackHolderBlockEntity extends LockableContainerBlockEntity implements UseBlockCallback, AttackBlockCallback { private final DefaultedList<ItemStack> slots; public StackHolderBlockEntity() { super(DashBlockEntities.StackHolder); slots = DefaultedList.ofSize(1, ItemStack.EMPTY); } @Override public ActionResult interact(PlayerEntity player, World world, Hand hand, BlockPos pos, Direction direction) { ItemStack holding = getStack(0); if (holding.isEmpty()) return ActionResult.PASS; if (!player.inventory.insertStack(holding)) { Block.dropStack(world, pos.add(world.random.nextFloat(), world.random.nextFloat(), world.random.nextFloat()), holding); } setStack(0, ItemStack.EMPTY); markDirty(); return ActionResult.CONSUME; } @Override public ActionResult interact(PlayerEntity player, World world, Hand hand, BlockHitResult hitResult) { final ItemStack playerStack = player.getStackInHand(hand); final ItemStack holding = getStack(0); if (playerStack.isEmpty() && holding.isEmpty()) return ActionResult.PASS; if (holding.isEmpty() && isValid(0, playerStack)) { setStack(0, playerStack.copy()); playerStack.decrement(1); markDirty(); return ActionResult.CONSUME; } return interact(player, world, hand, pos.add(world.random.nextFloat(), world.random.nextFloat(), world.random.nextFloat()), player.getHorizontalFacing()); } @Override protected Text getContainerName() { return null; } @Override protected ScreenHandler createScreenHandler(int syncId, PlayerInventory playerInventory) { return null; } @Override public int size() { return slots.size(); } @Override public boolean isEmpty() { return size() == 0 || slots.stream().allMatch(ItemStack::isEmpty); } @Override public ItemStack getStack(int slot) { return slots.get(slot); } @Override public ItemStack removeStack(int slot, int amount) { return Inventories.splitStack(slots, slot, amount); } @Override public ItemStack removeStack(int slot) { return Inventories.removeStack(slots, slot); } @Override public void setStack(int slot, ItemStack stack) { slots.set(slot, stack); if (stack.getCount() > this.getMaxCountPerStack()) { stack.setCount(this.getMaxCountPerStack()); } } @Override public boolean canPlayerUse(PlayerEntity player) { if (this.world.getBlockEntity(this.pos) != this) { return false; } else { return player.squaredDistanceTo((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, (double) this.pos.getZ() + 0.5D) <= 64.0D; } } @Override public void clear() { slots.clear(); } @Override public int getMaxCountPerStack() { return 1; } }
1fa3cdd25cf3e4cf899bc1875d84556c2c5fd6d8
64b2e9951584dd6a5c3d7ed97b43d52f60981806
/src/main/java/me/jonathansmith/progression/local/runtime/Client.java
38953672df13c52733daa0dc61578a97c92c4f39
[]
no_license
JonathanCSmith/Progression
b098530e0cece13da089a871948f2ab8ae41a1b2
2254fe85ee6d967cad16acc5cba626a0be0f01f1
refs/heads/master
2020-05-02T12:36:25.816586
2019-04-02T12:45:25
2019-04-02T12:45:25
177,962,322
0
0
null
null
null
null
UTF-8
Java
false
false
2,117
java
package me.jonathansmith.progression.local.runtime; import me.jonathansmith.progression.Progression; import me.jonathansmith.progression.api.engine.Task; import me.jonathansmith.progression.api.network.CommunicationManager; import me.jonathansmith.progression.api.properties.ConfigurationProperties; import me.jonathansmith.progression.api.runtime.ClientRuntime; import me.jonathansmith.progression.common.runtime.CommonRuntime; import me.jonathansmith.progression.common.user_interface.UserInterfaceRuntime; import java.util.List; public class Client extends CommonRuntime implements ClientRuntime { private final Progression progression; private final UserInterfaceRuntime userInterface; private final CommunicationManager communicationsManager; public Client(Progression progression, UserInterfaceRuntime userInterface, CommunicationManager communicationManager) { super(); this.progression = progression; this.userInterface = userInterface; this.communicationsManager = communicationManager; } @Override public void init(ConfigurationProperties configurationProperties) { super.init(configurationProperties); this.userInterface.init(); this.userInterface.start(); // Handle whether we need to boot a server } @Override protected int runTasks() { this.doPreLoopTasks(); List<Task> tasks = this.getOrderedTaskList(); if (tasks.isEmpty()) { return 10; } for (Task task : tasks) { task.executeTask(this); } this.doPostLoopTasks(); return 0; } @Override public void command(String command) { this.userInterface.output("Echo: " + command); } private void doPreLoopTasks() { List<Task> tasks = this.userInterface.gatherInputs(); this.communicationsManager.setUpdates(tasks); } private List<Task> getOrderedTaskList() { return this.communicationsManager.getUpdates(); } private void doPostLoopTasks() { // Render return; } }
36a98a17dae00cda38bffdbb33ff16cf3707032f
b7a1bade5bf347f2601ebdb7eda3e954895e6455
/java02t/src/step07/ex12/Student.java
2b4db70d9e44149b8d85641dfe3ff82e7992d1a7
[]
no_license
Jeongjiho/Java76
a1429f12ffc2a5c557289760eb3164adba39c6eb
5c98d47a341776bc7b54b28907356b3007b46592
refs/heads/master
2016-08-12T20:29:57.698964
2016-02-22T14:59:27
2016-02-22T14:59:27
56,924,651
1
0
null
2016-04-23T14:54:31
2016-04-23T14:54:31
null
UTF-8
Java
false
false
267
java
package step07.ex12; public class Student extends User { boolean working; String company; String position; int grade; public Student(String id, String pwd, String email, boolean working) { super(id, pwd, email); this.working = working; } }
744ecd9e4c9c9300759879d48be1d576010dfb13
aa884fedc7576a70e2dbcd0f2635cd5b71fa3812
/src/com/devdojo/lambdas/test/LambdaTest.java
8ad81e936f41e3b2fb51ed2b123dd5029d7440fa
[]
no_license
heroumcaslu/maratona-java
650b45a8caac8475282190c933101e2ca25f4f0e
ca69c14cf5d5f7a15e0cdfd761dcf4322e116077
refs/heads/master
2023-02-05T07:07:36.104985
2020-12-22T11:30:54
2020-12-22T11:30:54
245,874,324
0
0
null
null
null
null
UTF-8
Java
false
false
1,195
java
package com.devdojo.lambdas.test; import java.util.function.Predicate; import com.devdojo.lambdas.Carro; import com.devdojo.lambdas.interfaces.CarroPredicate; public class LambdaTest { // Foi criado para diminuir a verbosidade // anonima - função - passada - concisa // Só é possivel utilizar com interface funcionaljjj // Parametro -> corpo // (Carro carro) -> carro.getCor().equals("verde"); // (String s) -> s.length(); // (int a, int b)-> sout(a+b) public static void main(String[] args) { // TODO Auto-generated method stub CarroPredicate carroPredicate = new CarroPredicate() { @Override public boolean test(Carro carro) { // TODO Auto-generated method stub return carro.getCor().equals("verde"); } }; //Com lambda CarroPredicate carroPredicate2 = (Carro carro) -> carro.getCor().equals("verde"); //Predicate<Carro> carroPredicate3 = (Carro carro) -> carro.getCor().equals("verde"); System.out.println(carroPredicate.test(new Carro("verde", 2012))); System.out.println(carroPredicate2.test(new Carro("verde", 2012))); Runnable runnable = () -> System.out.println("Dentro do runa"); new Thread(runnable).run(); } }
3f13110eb2b47d32a63937fb23033d24fd0d7927
2ae28773963604b3cbee6626959dd262c1cc3a6e
/base/build-system/integration-test/application/src/test/java/com/android/build/gradle/integration/library/LibMinifyJarDepTest.java
7424a1608604445cf2e50c838f0a8a48267d1150
[ "Apache-2.0" ]
permissive
qiangxu1996/vmtrace
c95985e76253f140467e20f67d38022b2623e94e
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
refs/heads/master
2022-04-18T22:32:39.132937
2020-04-18T23:01:55
2020-04-18T23:01:55
255,410,085
1
2
null
null
null
null
UTF-8
Java
false
false
2,125
java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.integration.library; import com.android.build.gradle.integration.common.fixture.GradleTestProject; import com.android.build.gradle.integration.common.runner.FilterableParameterized; import com.android.build.gradle.internal.scope.CodeShrinker; import com.android.build.gradle.options.OptionalBooleanOption; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** Assemble tests for libMinifyJarDep. */ @RunWith(FilterableParameterized.class) public class LibMinifyJarDepTest { @Parameterized.Parameters(name = "codeShrinker = {0}") public static CodeShrinker[] getShrinkers() { return new CodeShrinker[] {CodeShrinker.PROGUARD, CodeShrinker.R8}; } @Parameterized.Parameter public CodeShrinker codeShrinker; @Rule public GradleTestProject project = GradleTestProject.builder().fromTestProject("libMinifyJarDep").create(); @Before public void setUp() throws IOException, InterruptedException { project.executor() .with(OptionalBooleanOption.ENABLE_R8, codeShrinker == CodeShrinker.R8) .run("clean", "assembleDebug", "assembleAndroidTest"); } @After public void cleanUp() { project = null; } @Test public void lint() throws IOException, InterruptedException { project.execute("lint"); } }
5d9aacc5d2808a908960e2d5d3fed78fc9dd4e9f
f89828a5cf1fd69c7418fc2da2525f3cfb42fd35
/src/main/java/com/smartkitchen/SmartList/client/SmartListClient.java
1625fcb2705b29e75b9a0a0314773b5f10fe9d2b
[]
no_license
Kehvv/SmartKitchen
2925e89897d5355e5b0272cc8a55afb8ac218d1e
ef7fe62f6a518cbae0d192dc3b210c974d55cc0e
refs/heads/master
2022-04-17T09:09:45.080552
2020-04-12T22:36:29
2020-04-12T22:36:29
253,320,826
0
0
null
null
null
null
UTF-8
Java
false
false
3,142
java
package com.smartkitchen.SmartList.client; import com.proto.smartlist.*; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; public class SmartListClient { public static void main(String[] args) { System.out.println("Smart Kitchen List client running!"); SmartListClient main = new SmartListClient(); main.run(); } private void run(){ ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50052) .usePlaintext() .build(); SmartListServiceGrpc.SmartListServiceBlockingStub smartlistClient = SmartListServiceGrpc.newBlockingStub(channel); Smartlist smartlist = Smartlist.newBuilder() .setItem("Milk") .setBarcode(1000) .setPrice(1.50) .build(); CreateSmartListResponse createResponse = smartlistClient.createSmartList( CreateSmartListRequest.newBuilder() .setSmartlist(smartlist) .build() ); System.out.println("Received Create Smart List Item Response:"); System.out.println(createResponse.toString()); String smartlistId = createResponse.getSmartlist().getId(); System.out.println("Item Found: Reading Smart Item..."); ReadSmartListResponse readSmartListResponse = smartlistClient.readSmartList(ReadSmartListRequest.newBuilder() .setItemId(smartlistId) .build()); System.out.println(readSmartListResponse.toString()); // ERROR HANDLING - Trigger notfound errror // System.out.println("Attempting to read id which does not exist:"); // ReadSmartListResponse readSmartListResponseNotFound = smartlistClient.readSmartList(ReadSmartListRequest.newBuilder() // .setItemId("5e936b9f53f24235dc75e2e6") // .build()); Smartlist newSmartlist = Smartlist.newBuilder() .setId(smartlistId) .setItem("CHANGED ITEM") .setBarcode(1001) .setPrice(1.55) .build(); System.out.println("Updating item..."); UpdateSmartListResponse updateSmartListResponse= smartlistClient.updateSmartList(UpdateSmartListRequest.newBuilder() .setSmartlist(newSmartlist) .build()); System.out.println("Item Updated!"); System.out.println(updateSmartListResponse.toString()); System.out.println("Deleting Smart Item"); DeleteSmartListResponse deleteSmartListResponse = smartlistClient.deleteSmartList( DeleteSmartListRequest.newBuilder() .setSmartlistId(smartlistId) .build() ); System.out.println("Smart Item Deleted!"); System.out.println("Reading Smart Item..."); //Should return notfound! ReadSmartListResponse readSmartListResponseAfterDelete = smartlistClient.readSmartList(ReadSmartListRequest.newBuilder() .setItemId(smartlistId) .build()); } }
2078d9c531bdb55fb3a6b4ec314dfa2be5ef95f9
e20fe39d38fbf907a70cd21e1aba6e788bb3e2a0
/submarine/src/main/java/abra97/submarine/model/Torpedo.java
a60a4a6b7438dcfb802a56e8cc3e1908dd7d5abe
[]
no_license
soos4/submarine
506df8bf9ccb66a144e35d97d0dd81676476161e
aeb562fbe1d926ab6285454d0f69cc83856202f4
refs/heads/master
2021-01-11T10:20:21.558655
2016-11-09T22:53:53
2016-11-09T22:53:53
72,307,402
0
0
null
null
null
null
UTF-8
Java
false
false
1,489
java
package abra97.submarine.model; import org.json.JSONObject; import org.json.JSONTokener; public class Torpedo extends Entity { private final int roundsMoved; public static int RANGE; public static int SPEED; public static int HIT_PENALTY; public static int DESTROY_SCORE; public static int HIT_SCORE; public static int DAMAGE; public static int EXPLOSION_RADIUS; public Torpedo(int id, Point position, Team owner, double velocity, Direction angle, int roundsMoved) { super(ObjectType.TORPEDO, id, position, owner, velocity, angle); this.roundsMoved = roundsMoved; } public Torpedo(int id, Point position, Team owner, double velocity, Direction angle) { this(id, position, owner, velocity, angle, 0); } public static void initialize(String json) { JSONTokener tokener = new JSONTokener(json); JSONObject root = new JSONObject(tokener).getJSONObject("game").getJSONObject("mapConfiguration"); DAMAGE = root.getInt("torpedoDamage"); DESTROY_SCORE = root.getInt("torpedoDestroyScore"); EXPLOSION_RADIUS = root.getInt("torpedoExplosionRadius"); HIT_PENALTY = root.getInt("torpedoHitPenalty"); HIT_SCORE = root.getInt("torpedoHitScore"); RANGE = root.getInt("torpedoRange"); SPEED = root.getInt("torpedoSpeed"); } @Override public String toString() { return "Torpedo [roundsMoved=" + roundsMoved + ", base=" + super.toString() + "]"; } public int getRoundsMoved() { return roundsMoved; } }
16bbe23e892b7811ae91fdeab6f8f296579294b4
5763a243540a5a0a40f518b419777e907d0edabc
/first/lexiograph.java
5a7e77aa667d18d27e40d588c142613aae3ecd29
[]
no_license
rhf0410/Leetcode
152f0fc0841b885e30293ec1229d3836244bb838
ee731c57fe4d5148d15f52aa0c0d090a4ea5a2b7
refs/heads/master
2021-08-17T23:39:04.557427
2020-03-30T01:16:43
2020-03-30T01:16:43
144,392,042
1
0
null
null
null
null
UTF-8
Java
false
false
1,013
java
package com.example.first; import java.beans.Visibility; import java.util.ArrayList; import java.util.Arrays; public class lexiograph { public ArrayList<String> permutation(String str){ if(str == null) return null; ArrayList<String>results = new ArrayList<String>(); char [] chs = str.toCharArray(); boolean [] visit = new boolean [chs.length]; for(int i=0;i<visit.length;i++){ visit[i] = false; } String result = new String(""); recursion(chs, 0, result, results); return results; } private void recursion(char [] chs, int i, String result, ArrayList<String>results){ if(i == chs.length){ results.add(String.valueOf(chs)); return; } for(int j=i;j<chs.length;j++){ swap(chs, i, j); recursion(chs, i+1,result, results); swap(chs, i, j); } } private void swap(char [] chs, int i, int j){ char ch = chs[i]; chs[i] = chs[j]; chs[j] = ch; } }
9ff4a8383a1b48b9ceda46f78f6f98dd0ffcc165
9507b4ca808de4a48a929bc41bcfda77b67175b2
/src/main/java/data/DataExtractor.java
1527e498beb6464e5fb47b75fa37469c26b1815e
[]
no_license
HChomette/parismetro
8dfb0d569e74ec4fc9f807fa69872f3be111bf62
44c5a6c74a4aec402acbc600732532ecd56f4f4d
refs/heads/master
2022-06-20T02:53:35.014217
2019-06-10T18:49:09
2019-06-10T18:49:09
190,477,451
0
0
null
2020-10-13T13:48:14
2019-06-05T22:28:56
Java
UTF-8
Java
false
false
3,799
java
package data; import com.google.gson.Gson; import com.google.gson.internal.LinkedTreeMap; import graph.Graph; import graph.UnweightedGraph; import graph.WeightedGraph; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; public class DataExtractor { private static final int MAX_METRO = 14; //Number of metro lines public static UnweightedGraph createUnweightedGraph(File file){ UnweightedGraph res = new UnweightedGraph(); createGraphFromJSON(file, false, res); return res; } public static WeightedGraph createWeightedGraph(File file){ WeightedGraph res = new WeightedGraph(); createGraphFromJSON(file, true, res); return res; } //Not very elegant, but allows us to not repeat code //Relies on casting graph to either UnweightedGraph or WeightedGraph //We rely a lot on casting for the JSON products, because there are a lot of different sub-objects private static void createGraphFromJSON(File file, boolean weighted, Graph graph) { BufferedReader br; try { br = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e){ e.printStackTrace(); return; } Gson gson = new Gson(); LinkedTreeMap<String, Object> json = gson.fromJson(br, LinkedTreeMap.class); //Global json LinkedTreeMap<String, LinkedTreeMap> lignesJson = (LinkedTreeMap)json.get("lignes"); LinkedTreeMap<String, LinkedTreeMap> stationsJson = (LinkedTreeMap)json.get("stations"); ArrayList<ArrayList> lignes = new ArrayList<>(); //ArrayList of ArrayLists containing every line with every station for(int i = 1; i <= MAX_METRO; i++){ ArrayList<ArrayList> arrets = (ArrayList)lignesJson.get(Integer.toString(i)).get("arrets"); lignes.add(arrets.get(0)); } LinkedTreeMap precedent = new LinkedTreeMap(); //We keep the precedent station to create the edge for(int i = 0; i < lignes.size(); i++) { for(int j = 0; j < lignes.get(i).size(); j++){ int currentNb = Integer.parseInt((String)lignes.get(i).get(j)); LinkedTreeMap currentStation = stationsJson.get(Integer.toString(currentNb)); String currentName = (String)currentStation.get("nom"); if(!graph.containsVertex(currentName)){ //If station doesn't exist already, we add it graph.addVertex(currentName); } if(j > 0){ //We create the edge with the precedent station, so not for the first one if(weighted){ double distance = calculateDistance(Double.parseDouble((String)currentStation.get("lat")), Double.parseDouble((String)currentStation.get("lng")), Double.parseDouble((String)precedent.get("lat")), Double.parseDouble((String)precedent.get("lng"))); ((WeightedGraph)graph).addEdge(currentName, (String)precedent.get("nom"), distance); } else { ((UnweightedGraph)graph).addEdge(currentName, (String)precedent.get("nom")); } } precedent = currentStation; } } } /** * Calculate distance between two points */ private static double calculateDistance(double xA, double yA, double xB, double yB){ int deglen = 110250; double deltaX = xA - xB; double deltaY = (yA - yB) * Math.cos(xB); return deglen * Math.sqrt(deltaX * deltaX + deltaY * deltaY); } }
97fa5f27b16af55e43d576fbebec959d0fc456f4
342879e1d32d074bd77479b4e170b1481b85ca21
/src_user/com/wk/entity/Account.java
f4f6a18107309229c0a93a2395538ee9e0c1c1a4
[]
no_license
jihadwk/SqlTest
183370033a40f18115b998254aaf6c7ce2e07504
53248cdec56c7e0595a40ff45f5180f4492c3817
refs/heads/master
2021-01-11T00:14:09.850588
2016-10-11T08:45:09
2016-10-11T08:45:09
70,573,969
0
0
null
null
null
null
UTF-8
Java
false
false
640
java
package com.wk.entity; public class Account { private String username; private String password; private Integer access; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAccess() { return access; } public void setAccess(Integer access) { this.access = access; } @Override public String toString() { return "Account [username=" + username + ", password=" + password + ", access=" + access + "]"; } }
999ce0cc17e1e475a75d76e0b2f1e19cc1559f40
3de58e879ab675a93cf2a0861c6a420559aab902
/app/src/main/java/com/example/shikhar/myapp/util/SystemUiHiderBase.java
e961978374934ea11c3f81d7c5731f0d861286b9
[]
no_license
meekumishra/myapp
62410c533c9702d6b1995475fa7894c2557887d9
fbe291a87f3966960228fdfb5d3766efb6081658
refs/heads/master
2016-09-16T15:18:29.114037
2015-03-11T17:33:42
2015-03-11T17:33:42
32,031,612
0
0
null
null
null
null
UTF-8
Java
false
false
2,020
java
package com.example.shikhar.myapp.util; import android.app.Activity; import android.view.View; import android.view.WindowManager; /** * A base implementation of {@link SystemUiHider}. Uses APIs available in all * API levels to show and hide the status bar. */ public class SystemUiHiderBase extends SystemUiHider { /** * Whether or not the system UI is currently visible. This is a cached value * from calls to {@link #hide()} and {@link #show()}. */ private boolean mVisible = true; /** * Constructor not intended to be called by clients. Use * {@link SystemUiHider#getInstance} to obtain an instance. */ protected SystemUiHiderBase(Activity activity, View anchorView, int flags) { super(activity, anchorView, flags); } @Override public void setup() { if ((mFlags & FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES) == 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } } @Override public boolean isVisible() { return mVisible; } @Override public void hide() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(false); mVisible = false; } @Override public void show() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags( 0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(true); mVisible = true; } }
199c2f9014c2ee4f2c7d56e10908d7512a5d936c
e27abf5cfe620a6862212814720b06cccb237477
/Semestre5/ProgrammationConception_TP3/src/main/java/l3info/Vector.java
be7b2ce23755b5de6ab36ceb6172a8916288fbe4
[]
no_license
quentinfougereau/Licence3-Projets-et-TP
128f89fd52c3d2d03b1cfc317dee8adbc92d5c97
6fcad659d817880ffc1a10d9882036106e9f4e8e
refs/heads/master
2020-05-09T14:07:29.937554
2019-04-13T14:33:58
2019-04-13T14:33:58
181,182,243
2
1
null
null
null
null
UTF-8
Java
false
false
4,428
java
package l3info; import java.util.Arrays; /** * La classe Vector implémente un tableau générique * de taille dynamique. Les éléments du vecteur sont stockés dans un tableau. * La taille de ce tableau est au minimum doublée à chaque fois qu'il est * nécessaire de le faire grossir. */ public class Vector<T> { /** * Tableau permettant de stocker les éléments du vecteur. * Seuls les size premiers éléments font partie du vecteur. * La taille de ce tableau est égale à la capacité du vecteur, c'est-à-dire, * au nombre d'éléments maximum que le vecteur peut contenir sans * avoir besoin d'allouer un nouveau tableau. */ private T[] elements; /** * Nombre d'éléments présents dans le vecteur. */ private int size; /** * Construit un vecteur de capacité initiale initialCapacity. * * @param initialCapacity Capacité initiale du vecteur */ public Vector(int initialCapacity) { elements = (T[]) new Object[initialCapacity]; size = 0; } /** * Construit un vecteur de capacité initiale 10 */ public Vector() { this(10); } /** * Augmente la capacité du vecteur si nécessaire de façon * à permettre le stockage d'au moins <code>minCapacity</code> * éléments. S'il est nécessaire d'augmenter la capacité du vecteur, * elle est au minimum doublée. * * @param minCapacity Capacité minimale à assurer */ public void ensureCapacity(int minCapacity) { int oldCapacity = elements.length; if (oldCapacity >= minCapacity) return; int newCapacity = Math.max(oldCapacity * 2, minCapacity); elements = Arrays.copyOf(elements, newCapacity); } /** * S'assure que la capacité du vecteur est assez grande pour * accueillir la nouvelle taille et remplace l'ancienne taille * par la nouvelle. * * @throws ArrayIndexOutOfBoundsException si l'index est en dehors des bornes, c'est à dire, index < 0 || index >= size * * @param newSize Nouvelle taille du vecteur */ public void resize(int newSize) { if (newSize < 0) throw new ArrayIndexOutOfBoundsException("Size " + newSize + " must be positive"); ensureCapacity(newSize); this.size = newSize; } /** * Retourne la capacité du vecteur. * * @return Capacité du vecteur. */ public int capacity() { return elements.length; } /** * Retourne la taille du vecteur * * @return Taille du vecteur */ public int size() { return size; } /** * Retourne un booléen * Vrai si la taille du vecteur vaut 0, Faux sinon * * @return true ou false */ public boolean isEmpty() { return size == 0; } /** * Redimensionne la taille du vecteur * Ajoute un nouvel élément au tableau d'éléments du vecteur * * @param element Elément du vecteur */ public void add(T element) { resize(size + 1); elements[size - 1] = element; } /** * Modifie un élément du vecteur à la position index * * @throws ArrayIndexOutOfBoundsException si l'index est en dehors des bornes, c'est à dire, index < 0 || index >= size * * @param index Position de l'élément dans le tableau d'éléments du vecteur * @param element Nouvel élément du vecteur */ public void set(int index, T element) { if (index >= 0 && index < size) elements[index] = element; else { throw new ArrayIndexOutOfBoundsException("Index " + index + " is out of range [0, " + (size-1) + "]"); } } /** * Retourne un élément du vecteur à la position index * * @throws ArrayIndexOutOfBoundsException si l'index est en dehors des bornes, c'est à dire, index < 0 || index >= size * * @param index Position de l'élément dans le tableau d'éléments du vecteur * @return Element du vecteur à la position index ou null si cet élément n'existe pas */ public T get(int index) { if (index >= 0 && index < size) { return elements[index]; } else { throw new ArrayIndexOutOfBoundsException("Index " + index + " is out of range [0, " + (size-1) + "]"); } } }
a7ca0eff44162d05cc0bd9a2cdf0baf2fa79c8aa
bead7e02593f971fdf270a8b721a7b53a67ec375
/flinkDemoProject/src/main/java/com/dutchtulipbulb/flinkDemoProject/ViewsSessionWindow.java
1d606c26e51a225d91aa8b2c63bfc37f4e622dd3
[]
no_license
tanviagr/flink
07a9704559dd07a2802ae8e2ef0559d4ad911425
310b180b2a556d1acc2b5ee1e7682f04932a061f
refs/heads/master
2023-01-14T01:43:06.096312
2020-11-23T14:29:34
2020-11-23T14:29:34
314,556,684
0
0
null
null
null
null
UTF-8
Java
false
false
1,752
java
package com.dutchtulipbulb.flinkDemoProject; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows; import org.apache.flink.streaming.api.windowing.time.Time; public class ViewsSessionWindow { /*try to see within session which page a user spends most time on*/ public static void main (String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<String> dataStream = StreamUtil.getDataStream(env, params); if (dataStream == null) { System.exit(1); return; } /* input entity - <user ID, page, time spent> */ DataStream<Tuple3<String, String, Double>> outStream = dataStream. map (new RowSplitter()) .keyBy(0, 1) .window(ProcessingTimeSessionWindows.withGap(Time.seconds(10))) .max(2); //filters only the max from the keyed stream outStream.print(); env.execute("Session Window"); } public static class RowSplitter implements MapFunction <String, Tuple3<String, String, Double>> { /** * */ private static final long serialVersionUID = 1L; public Tuple3<String, String, Double> map(String value) throws Exception { String[] fields = value.split(","); return new Tuple3<String, String, Double>( fields[0], //user ID fields[1], //page ID Double.parseDouble(fields[2])); //viewing time in minutes } } }
bfe9b223f3c1743cafbccb5354e7123d93ac43e0
85f77b05a931fd37cce2909419aeba5ac0a8af07
/P1-Poo/src/p1/poo/Mundo.java
cb46348b22205b03406885b07dcb2eb8308a6bd1
[]
no_license
batazoli/Projeto-POO-JAVA
356fb69a7293da00dd578574011153bbc98deb69
3670e3431e709a2803ef657a650acd4ff05f910c
refs/heads/master
2020-04-02T21:22:00.703483
2018-10-26T07:44:31
2018-10-26T07:44:31
154,796,581
1
0
null
null
null
null
UTF-8
Java
false
false
18,850
java
/* * 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 p1.poo; import java.io.IOException; import java.util.ArrayList; import java.util.Random; /** * * @author Vagner Batazoli * @version 1.0 * @since 2018-10-10 */ public class Mundo { public Mundo() throws InterruptedException, IOException { boolean loop = true; Random random = new Random(); ArrayList<Caminhao> caminhoes = new ArrayList(); ArrayList<Carro> carros = new ArrayList(); ArrayList<Moto> motos = new ArrayList(); ArrayList<Bike> Bikes = new ArrayList(); int contVelBike = 0; //Adiciona primeiros veiculos em suas ArrayLists e "seto" valores aleatorios para iniciar no mapa for (int i = 0; i < 10; i++) { caminhoes.add(new Caminhao((random.nextInt(28) + 1), (random.nextInt(58) + 1), (random.nextInt(4) + 1))); carros.add(new Carro((random.nextInt(28) + 1), (random.nextInt(58) + 1), (random.nextInt(4) + 1))); motos.add(new Moto((random.nextInt(28) + 1), (random.nextInt(58) + 1), (random.nextInt(4) + 1))); Bikes.add(new Bike((random.nextInt(28) + 1), (random.nextInt(58) + 1), (random.nextInt(4) + 1))); } //Loop para manter td funcionando while (loop == true) { //as cores que usarei para os objetos final String ANSI_RESET = "\u001B[0m"; //fundo colorido final String ANSI_RED_BACKGROUND = "\u001B[41m"; final String ANSI_GREEN_BACKGROUND = "\u001B[42m"; final String ANSI_YELLOW_BACKGROUND = "\u001B[43m"; final String ANSI_BLUE_BACKGROUND = "\u001B[44m"; final String ANSI_PURPLE_BACKGROUND = "\u001B[45m"; final String ANSI_CYAN_BACKGROUND = "\u001B[46m"; final String ANSI_WHITE_BACKGROUND = "\u001B[47m"; //letra colorida final String ANSI_RED = "\u001B[31m"; final String ANSI_GREEN = "\u001B[32m"; final String ANSI_YELLOW = "\u001B[33m"; final String ANSI_BLUE = "\u001B[34m"; /* uso uma técnica mto comum para "jogos" que eh mapear tudo em um vetor onde 1 = parede 0 = espaço vazio 22 = fábricas */ int[][] mapa2 = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 22, 22, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},}; for (int i = 0;i < caminhoes.size();i++) { mapa2[caminhoes.get(i).getLinha()][caminhoes.get(i).getColuna()] += caminhoes.get(i).getTAMANHO(); } for (int i = 0;i < carros.size();i++) { mapa2[carros.get(i).getLinha()][carros.get(i).getColuna()] += carros.get(i).getTAMANHO(); } for (int i = 0;i < motos.size();i++) { mapa2[motos.get(i).getLinha()][motos.get(i).getColuna()] += motos.get(i).getTAMANHO(); } for (int i = 0;i < Bikes.size();i++) { mapa2[Bikes.get(i).getLinha()][Bikes.get(i).getColuna()] += Bikes.get(i).getTAMANHO(); } //Verificações de todas as colisões possíveis, desde as do veiculo com veículo como de veículo com Fábrica for (int i = 0; i < 30; i++) { for (int j = 0; j < 60; j++) { //Todas as possíveis colisões com o caminhão separadas por Grau Hierarquico: Fábrica, Bike, Moto, Carro e o Pŕopio caminhão //Colisão de caminhao com fabrica if (mapa2[i][j] == 34) { mapa2[i][j] = 12; caminhoes.add(new Caminhao((random.nextInt(28) + 1), (random.nextInt(58) + 1), (random.nextInt(4) + 1))); } //Colisão caminhão com bike if (mapa2[i][j] == 14) { mapa2[i][j] = caminhoes.get(0).getTAMANHO(); for (int k = 0; k < Bikes.size(); k++) { if (Bikes.get(k).getLinha() == i && Bikes.get(k).getColuna() == j) { Bikes.remove(k); } } } //Colisão caminhao com moto if (mapa2[i][j] == 15) { mapa2[i][j] = caminhoes.get(0).getTAMANHO(); for (int k = 0; k < motos.size(); k++) { if (motos.get(k).getLinha() == i && motos.get(k).getColuna() == j) { motos.remove(k); } } } //Colisão caminhão com carro if (mapa2[i][j] == 20) { mapa2[i][j] = caminhoes.get(0).getTAMANHO(); for (int k = 0; k < carros.size(); k++) { if (carros.get(k).getLinha() == i && carros.get(k).getColuna() == j) { carros.remove(k); } } } //Colisao caminhao com caminhão if (mapa2[i][j] == 24) { mapa2[i][j] = 0; for (int k = 0; k < caminhoes.size(); k++) { if (caminhoes.get(k).getLinha() == i && caminhoes.get(k).getColuna() == j) { caminhoes.remove(k); } } } //Todas as possíveis colisões com o carro separadas por Grau Hierarquico: Fábrica, Bike, Moto e o própio Carro(menos colisão com caminhão(não ter porque ter duas verificações iguais)) //Colisão carro com fabrica if (mapa2[i][j] == 30) { mapa2[i][j] = 8; carros.add(new Carro((random.nextInt(28) + 1), (random.nextInt(58) + 1), (random.nextInt(4) + 1))); } //Colisão de carro com bike if (mapa2[i][j] == 10) { mapa2[i][j] = carros.get(0).getTAMANHO(); for (int k = 0; k < Bikes.size(); k++) { if (Bikes.get(k).getLinha() == i && Bikes.get(k).getColuna() == j) { Bikes.remove(k); } } } //Colisão carro com moto if (mapa2[i][j] == 11) { mapa2[i][j] = carros.get(0).getTAMANHO(); for (int k = 0; k < motos.size(); k++) { if (motos.get(k).getLinha() == i && motos.get(k).getColuna() == j) { motos.remove(k); } } } //Colisao de carro com carro if (mapa2[i][j] == 16) { mapa2[i][j] = 0; for (int k = 0; k < carros.size(); k++) { if (carros.get(k).getLinha() == i && carros.get(k).getColuna() == j) { carros.remove(k); } } } //Todas as possíveis colisões com a moto separadas por Grau Hierarquico: Fábrica, Bike a própia Moto (menos colisão com caminhão e carro(não ter porque ter duas verificações iguais)) //Colisão moto com fabrica if (mapa2[i][j] == 25) { mapa2[i][j] = 3; motos.add(new Moto((random.nextInt(28) + 1), (random.nextInt(58) + 1), (random.nextInt(4) + 1))); } //Colisão moto com Bike if (mapa2[i][j] == 5) { mapa2[i][j] = motos.get(0).getTAMANHO(); for (int k = 0; k < Bikes.size(); k++) { if (Bikes.get(k).getLinha() == i && Bikes.get(k).getColuna() == j) { Bikes.remove(k); } } } //Colisao de moto com moto if (mapa2[i][j] == 6) { mapa2[i][j] = 0; for (int k = 0; k < motos.size(); k++) { if (motos.get(k).getLinha() == i && motos.get(k).getColuna() == j) { motos.remove(k); } } } //Todas as possíveis colisões com a bike separadas por Grau Hierarquico: Fábrica e depois Bike (menos colisão com caminhão, carro e moto(não ter porque ter duas verificações iguais)) //Colisão de bike com fabrica if (mapa2[i][j] == 24) { mapa2[i][j] = 2; Bikes.add(new Bike((random.nextInt(28) + 1), (random.nextInt(58) + 1), (random.nextInt(4) + 1))); } //Colisão de bike com bike if (mapa2[i][j] == 4) { mapa2[i][j] = 0; for (int k = 0; k < Bikes.size(); k++) { if (Bikes.get(k).getLinha() == i && Bikes.get(k).getColuna() == j) { Bikes.remove(k); } } } } } //Mostra Mapa for (int i = 0;i < 30; i++) { for (int j = 0; j < 60; j++) { } } //for para "printar" o mapa e os objetos for (int i = 0;i < 30; i++) { System.out.println(""); for (int j = 0; j < 60; j++) { if(mapa2[i][j] == 0){ System.out.print(ANSI_CYAN_BACKGROUND + " " + ANSI_RESET); } else if (mapa2[i][j] == 1) { System.out.print(ANSI_PURPLE_BACKGROUND + " " + ANSI_RESET); } else if (mapa2[i][j] == 2) { System.out.print(ANSI_GREEN_BACKGROUND + " " + ANSI_RESET); } else if (mapa2[i][j] == 3) { System.out.print(ANSI_BLUE_BACKGROUND + " " + ANSI_RESET); } else if (mapa2[i][j] == 8) { System.out.print(ANSI_YELLOW_BACKGROUND + " " + ANSI_RESET); } else if (mapa2[i][j] == 12) { System.out.print(ANSI_RED_BACKGROUND + " " + ANSI_RESET); } else if (mapa2[i][j] == 22) { System.out.print(ANSI_WHITE_BACKGROUND + " " + ANSI_RESET); } } } //Mostra os contadores por hierarquia: mais "fraco" para o mais "forte" //Para um melhor entendimento colori as letras diretamente relacionado ao mapa para melhor vizualização System.out.println(""); System.out.println(ANSI_GREEN + "Bikes: " + ANSI_RESET + Bikes.size()); System.out.println(ANSI_BLUE + "Motos: " + ANSI_RESET + motos.size()); System.out.println(ANSI_YELLOW + "Carros: " + ANSI_RESET + carros.size()); System.out.println(ANSI_RED + "Caminhoes: " + ANSI_RESET + caminhoes.size()); for (int i = 0;i < caminhoes.size();i++) { caminhoes.get(i).move(); } for (int i = 0;i < carros.size();i++) { carros.get(i).move(); carros.get(i).move(); } for (int i = 0;i < motos.size();i++) { motos.get(i).move(); motos.get(i).move(); motos.get(i).move(); } for (int i = 0;i < Bikes.size();i++) { if (contVelBike % 2 == 0) { Bikes.get(i).move(); } } contVelBike++; clearConsole(); Thread.sleep(1000); } } private static void clearConsole() { //uso do try/catch para o programa não parar try { String os = System.getProperty("os.name"); if (os.contains("Windows")) { Runtime.getRuntime().exec("cls"); } else { Runtime.getRuntime().exec("clear"); } } catch (Exception exception) { } } }
6bdaeca6a9eebaceb17c580af24ba5c522b92bb7
f06e7b7c02c28ca6e70e28cba2f645adde24c4fd
/QuizApp/app/src/main/java/com/example/esha/quizapp/TestQuestionActivity.java
086cd8f5effd33fe2be6c855730f3997bdbfd6a7
[]
no_license
SATHYASAGAR/AndroidQuizApp
7465af0e509ba4102c78869bcd746eefbf03b068
18f29275c173af034349202b4a9be254737ed332
refs/heads/master
2022-03-30T14:56:59.423698
2020-01-25T23:15:59
2020-01-25T23:15:59
113,654,535
1
1
null
null
null
null
UTF-8
Java
false
false
8,104
java
package com.example.esha.quizapp; import android.content.Intent; import android.os.CountDownTimer; import android.support.annotation.NonNull; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.Toast; import com.firebase.client.Firebase; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; public class TestQuestionActivity extends AppCompatActivity { String TAG = "finalProject"; private ExpandableListView listView; private ExpandableListAdapter listAdapter; private List<String> listDataHeader; private List<String> listDataHeadertest; private HashMap<String, List<String>> listHash; FirebaseDatabase database = FirebaseDatabase.getInstance(); final DatabaseReference databaseReference = database.getReference(); FirebaseAuth authInstance; ArrayList<ArrayList<String>> question1; ArrayList<String> choices; ArrayList<ArrayList<String>> allChoices; String testNumber; String className; String currentUser; int testScoreResult; private HashMap<String, String> questionAnswerHash; private HashMap<String, String> questionAnswerSelectedHash; Integer testScore = 0; Integer i = 0; Button submitButton; Button timerButton; Boolean allAnswersSelected = false; CountDownTimer countDownTimer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_question); Intent intent = getIntent(); testNumber = intent.getStringExtra("testName"); className = intent.getStringExtra("className"); authInstance = FirebaseAuth.getInstance(); currentUser = authInstance.getCurrentUser().getDisplayName(); submitButton = (Button) this.findViewById(R.id.submitButtonID); timerButton = (Button) this.findViewById(R.id.timerButton); question1 = new ArrayList<ArrayList<String>>(); listView = (ExpandableListView) findViewById(R.id.lvExp); allChoices = new ArrayList<>(); initData(); setCountDownTimer(); countDownTimer.start(); listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition)); parent.setItemChecked(index, true); questionAnswerSelectedHash.put(listDataHeader.get(groupPosition), listHash.get(listDataHeader.get(groupPosition)).get(childPosition)); return true; } }); submitButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { countDownTimer.cancel(); score(); } }); } public void setCountDownTimer() { countDownTimer = new CountDownTimer(900000, 1000) { public void onTick(long millisUntilFinished) { long millis = millisUntilFinished; String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); timerButton.setText(hms); } public void onFinish() { timerButton.setText("Done!"); score(); } }; } private void score() { calculateScore(questionAnswerHash, questionAnswerSelectedHash); if (allAnswersSelected) { for (Map.Entry<String, String> entry : questionAnswerHash.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); } for (Map.Entry<String, String> entry : questionAnswerSelectedHash.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); } Intent go = new Intent(this, StudentProfileActivity.class); go.putExtra("testScore", testScore); testScoreResult = testScore; testScore = 0; Calendar c2 = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy"); final String dateToday = sdf.format(c2.getTime()); AvailableTest testDetails = new AvailableTest(); testDetails.setDateScheduled(dateToday); testDetails.setScore(testScoreResult); testDetails.setTestTaken(true); databaseReference.child("Students").child(currentUser).child("AvailableTests").child(className).child(testNumber).setValue(testDetails); startActivity(go); finish(); } } private void calculateScore(Map<String, String> m1, Map<String, String> m2) { if (m1.size() != m2.size()) { Toast.makeText(this, "Some questions not attempted!", Toast.LENGTH_SHORT).show(); } allAnswersSelected = true; for (String key : m1.keySet()) if (m1.get(key).equals(m2.get(key))) testScore++; } private void initData() { listDataHeader = new ArrayList<>(); listDataHeadertest = new ArrayList<>(); listHash = new HashMap<>(); questionAnswerHash = new HashMap<>(); questionAnswerSelectedHash = new HashMap<>(); databaseReference.child("testdata").child(testNumber).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { int i = 0; Iterable<DataSnapshot> children = dataSnapshot.getChildren(); for (DataSnapshot child : children) { Questions question = child.getValue(Questions.class); choices = new ArrayList<>(); choices.add(question.getChoice1()); choices.add(question.getChoice2()); choices.add(question.getChoice3()); choices.add(question.getChoice4()); allChoices.add(choices); listDataHeader.add(question.getQuestion()); questionAnswerHash.put(question.getQuestion(), question.correctAnswer); listHash.put(listDataHeader.get(i), allChoices.get(i)); i++; } listAdapter = new com.example.esha.quizapp.ExpandableListAdapter(getBaseContext(), listDataHeader, listHash); listView.setAdapter(listAdapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onBackPressed() { Toast.makeText(this, "Default Back Button Disabled", Toast.LENGTH_SHORT).show(); } }
52a72c3fa11297076342ad678a22e147eabecc7a
e11aba5e83340e8299a4e91778c410bae9ff3587
/Lucid Dreaming App/src/com/luciddreamingapp/beta/RealTimeListActivity.java
5762ed62ea9a13dc0b567a8853aa9d279b30b84b
[]
no_license
ParadoxDesign/android-lucid-dreaming-app
71b96de8b54746d462d05f1a8f690b2755fe4763
2960e327ed5b1f84f673717fd448456b1b917b50
refs/heads/master
2021-01-10T16:02:25.555083
2011-05-27T15:48:16
2011-05-27T15:48:16
48,666,693
0
0
null
null
null
null
UTF-8
Java
false
false
10,101
java
package com.luciddreamingapp.beta; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.gesture.Gesture; import android.gesture.GestureLibraries; import android.gesture.GestureLibrary; import android.gesture.GestureOverlayView; import android.gesture.GestureOverlayView.OnGesturePerformedListener; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.webkit.WebView; import com.luciddreamingapp.beta.RealTimeGraphActivity.UpdateRunnable; import com.luciddreamingapp.beta.util.ActigraphyService; import com.luciddreamingapp.beta.util.DataManagerObserver; import com.luciddreamingapp.beta.util.SleepDataManager; import com.luciddreamingapp.beta.util.SleepDataPoint; import com.luciddreamingapp.beta.util.gesturebuilder.GestureBuilderActivity; public class RealTimeListActivity extends Activity implements OnGesturePerformedListener,OnSharedPreferenceChangeListener,DataManagerObserver { private static final String TAG = "Lucid Dreaming App List";//tag for LogCat and eclipse log private static final boolean D = false;//debug private GestureLibrary gestureLibrary; private GestureOverlayView gestures; private WebView listView; private Handler handler; private boolean gesturesEnabled ; private boolean calibrationCompleted; private String sleepStatus = ""; private SleepDataManager dataManager; private WakeLock wakeLock; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); setupViews(prefs); if(D)Log.e(TAG, "+ON CREATE+"); handler = new Handler(); dataManager = SleepDataManager.getInstance(); dataManager.addObserver(this, SleepDataManager.LIST_UPDATED); sleepStatus = dataManager.getSleepStatus(); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); dataManager.addObserver(this, SleepDataManager.LIST_UPDATED); sleepStatus = dataManager.getSleepStatus(); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if(D)Log.e(TAG, "-ON DESTROY-"); dataManager.unregisterObserver(this, SleepDataManager.LIST_UPDATED); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if(D)Log.e(TAG, "+++ON RESUME+++"); dataManager.addObserver(this, SleepDataManager.LIST_UPDATED); // try{ // //acquire application context and get a reference to power service // Context context = getApplicationContext(); // PowerManager pm = (PowerManager)context.getSystemService( // Context.POWER_SERVICE); // // //create a wake lock to prevent phone from sleeping (screen dim/cpu on) // // wakeLock = pm.newWakeLock( // PowerManager.SCREEN_DIM_WAKE_LOCK,"Lucid Dreaming List"); // wakeLock.acquire(); // // if(D){System.out.println("Wakelock held: "+wakeLock.isHeld());} // // }catch(Exception e){ // if(D)Log.e(TAG,"Error aquiring wakelock"); // e.printStackTrace(); // } } @Override protected void onPostResume(){ super.onPostResume(); updateWebViewText(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); if(D)Log.e(TAG, "---ON PAUSE---"); dataManager.unregisterObserver(this, SleepDataManager.LIST_UPDATED); // if(wakeLock!=null &&wakeLock.isHeld()){ // wakeLock.release(); // } } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); if(D)Log.e(TAG, "--ON STOP--"); } public void updateWebViewText(){ //final String s = text; handler.post(new Runnable() { public void run() { if(D)Log.e(TAG, "--Update webview--"); if(calibrationCompleted){ listView.loadUrl("javascript:updateHTML()"); } } }); } public String getSleepStatus(){ return sleepStatus; } @Override public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) { // TODO Auto-generated method stub } //attempts to respond to preference changes and set up views accordingly @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String name) { // if(name.equals("enable_gestures")){ // boolean temp = prefs.getBoolean(name,false); // //if the gesture option is different, reset views // if(temp!=gesturesEnabled){ // setupViews(prefs); // } // // // }else if(name.equals("calibration_completed")){ setupViews(prefs); } } protected void setupViews(SharedPreferences prefs){ gesturesEnabled =prefs.getBoolean("enable_gestures", false); calibrationCompleted =prefs.getBoolean("calibration_completed", false); // if(gesturesEnabled){ // // with gestures // setContentView(R.layout.accelerometer_list); // try{ // gestureLibrary= GestureLibraries.fromFile(GestureBuilderActivity.GESTURES_FILE); // // gestures= (GestureOverlayView) findViewById(R.id.gestures); // // gestures.addOnGesturePerformedListener(this); // // gestureLibrary.load(); // gestures.setVisibility(View.VISIBLE); // // }catch(Exception e){if(D)e.printStackTrace();} // } else{ //without gestures setContentView(R.layout.accelerometer_list_no_gestures); // } listView = (WebView)findViewById(R.id.list_view); listView.getSettings().setJavaScriptEnabled(true); listView.getSettings().setLoadWithOverviewMode(true); listView.getSettings().setUseWideViewPort(true); listView.getSettings().setBuiltInZoomControls(true);//disable zoom for list? listView.addJavascriptInterface(this, "javahandler"); if(!prefs.getBoolean("calibration_completed", false)){ listView.loadUrl("file:///android_asset/html/instructions.html"); }else{ listView.loadUrl("file:///android_asset/html/epoch_activity_list.html"); } } @Override public void dataPointAdded(SleepDataPoint epoch) { // TODO Auto-generated method stub } @Override public void dataPointUpdated(SleepDataPoint epoch) { // TODO Auto-generated method stub } class UpdateRunnable implements Runnable{ UpdateRunnable(String innerHTML){ sleepStatus = innerHTML; } public void run(){ updateWebViewText(); } } @Override public void listUpdated(String innerHTML) { handler.post(new UpdateRunnable(innerHTML)); } @Override public void graphUpdated(JSONObject graphData) { } @Override public void dataReset() { // TODO Auto-generated method stub } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.accelerometer_monitoring_activity_menu, menu); menu.removeItem(R.id.menu_show_list); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_show_list: finish(); return true; case R.id.menu_show_graph: Intent graphIntent = new Intent(getBaseContext(), RealTimeGraphActivity.class); graphIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(graphIntent); // finish(); return true; case R.id.menu_show_clock: Intent clockIntent = new Intent(getBaseContext(), NightGUIActivity.class); clockIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(clockIntent); // finish(); return true; //saves the currently displayed graph as a JSON File case R.id.menu_save_data: ((GlobalApp)getApplication()).saveData(); return true; case R.id.menu_preferences: Intent settingsActivity = new Intent(getBaseContext(), Preferences.class); startActivity(settingsActivity); return true; case R.id.menu_exit_app: // stopService(new Intent(this, ActigraphyService.class)); // dataManager.reset(); //stopService(new Intent(this, ActigraphyService.class)); //System.exit(0); finish(); return true; } return false; } }
54826a1a2016c1596b93e23b1f16b0165deaef93
0bb4ec608891690c072551fb2ba0a47a95f42613
/app/src/main/java/app/com/project/csmith/finalyearproject/PlacesUI/DetailActivity.java
ad91c51fe6d27b37d8b0eefb24b5075b8a6323f7
[]
no_license
csmith55/FinalYearProj
ab063f58b278ab959beed6dc5571ac2ee52d9944
db82f7faae0c76ebf9c5661359ee223bed60be1c
refs/heads/master
2016-09-06T19:39:05.784277
2015-05-12T10:08:08
2015-05-12T10:08:08
30,021,198
0
0
null
null
null
null
UTF-8
Java
false
false
2,559
java
/* * Copyright (C) 2014 The Android Open Source 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 app.com.project.csmith.finalyearproject.PlacesUI; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import app.com.project.csmith.finalyearproject.R; import app.com.project.csmith.finalyearproject.QueryUI.SettingsActivity; public class DetailActivity extends Activity { /** * Creates the UI and variables to be displayed * @param savedInstanceState saved */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); createDetailFragment(savedInstanceState); } /** * Creates the detail fragment to display in UI * @param savedInstanceState state saved */ private void createDetailFragment(Bundle savedInstanceState) { if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new DetailFragment()) .commit(); } } /** * Creates the menu action bar for the UI * @param menu menu to create * @return if the action was completed */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.detail, menu); return true; } /** * Determines the item selected from the menu and starts the next activity * @param item selected * @return if the action was completed */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { startActivity(new Intent(this, SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
737f98fc0157354a3b6ecadeb34183aa6751603e
71e5ca67d8259a01cfd1edf492c08fede37022fd
/hz3context/src/main/java/org/example/jet/hz3context/Utils.java
caa85ab850fb9c5580a3d45d17159e9248fe6e33
[]
no_license
frant-hartm/jet-processor-classloader
bd3fe40f56a505881bc79be90950d3619781c7e9
9fd28049da6ff86911bd2ac2765f0edab832d15a
refs/heads/master
2023-03-26T00:29:31.370551
2021-03-31T02:42:59
2021-03-31T02:42:59
352,939,999
0
0
null
null
null
null
UTF-8
Java
false
false
1,132
java
package org.example.jet.hz3context; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.config.XmlClientConfigBuilder; import com.hazelcast.nio.IOUtil; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; public final class Utils { public static ClientConfig xmlToConfig(String xmlConfig) { Path tempFile = null; ClientConfig var3; try { tempFile = Files.createTempFile("client-config", ".xml"); Files.write(tempFile, xmlConfig.getBytes(StandardCharsets.UTF_8), new OpenOption[0]); XmlClientConfigBuilder configBuilder = new XmlClientConfigBuilder(tempFile.toFile()); var3 = configBuilder.build(); } catch (IOException var7) { throw new RuntimeException(var7); } finally { deleteQuietly(tempFile); } return var3; } private static void deleteQuietly(Path path) { if (path != null) { IOUtil.deleteQuietly(path.toFile()); } } }
99864cb8409816870c27f774a819fd6f18b67531
eeb52e31a4be94e9d944c917df970297c7af864c
/src/main/java/webapp/Doctor/DoctorService.java
f1682961c64e6e3fd4aef889edbb69581beed573
[]
no_license
rishabh-kochar/MediTrack-ADMIN
974f05cbe273da5e7b4cbaa3fcdeef7d78d612f5
e6a27802d31ab18a56c0289e75c7b9ec1c16d154
refs/heads/master
2020-04-07T20:58:35.803482
2018-11-22T14:23:51
2018-11-22T14:23:51
158,709,693
0
0
null
null
null
null
UTF-8
Java
false
false
1,203
java
package webapp.Doctor; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import webapp.DBConnection.DBConnection; public class DoctorService { private Connection con; public DoctorService() { try { con = DBConnection.getInstance().getConnection(); } catch (Exception e) { con = null; System.out.println(e); } } public ArrayList<Doctor> doctorList() throws ClassNotFoundException, SQLException { ArrayList<Doctor> doctorls = new ArrayList<>(); try { String sql = "select * from tbldoctor"; PreparedStatement pst = con.prepareStatement(sql); ResultSet rs = pst.executeQuery(); while (rs.next()) { Doctor tempdoctor = new Doctor(rs.getInt("DoctorID"), rs.getString("DoctorName"), rs.getString("username"), rs.getString("password"), rs.getString("DoctorDesignation"), rs.getString("DoctorSpecialization"), rs.getString("DoctorContact"), rs.getString("DoctorAddress")); doctorls.add(tempdoctor); System.out.println(tempdoctor.toString()); } } catch (Exception e) { System.out.println(e); } return doctorls; } }
fb08b1852a942af9176a8c34e261fbd02451a223
be2560280b87d7187e5f1ec8d01c08f7e37f369c
/src/lc322_CoinChange.java
b82b7dc52f0806bf883b7a51d3d48fb794c78b67
[]
no_license
Ddogzhouyuan/LeetCode
c54e523d1687b3fa38ed1dbca98c07793ff42bfc
a7e8382e2a22a20d81ead4b0aa4f6c2769bcb608
refs/heads/master
2023-04-11T11:05:24.605661
2023-03-30T14:52:18
2023-03-30T14:52:18
202,290,978
1
0
null
null
null
null
UTF-8
Java
false
false
1,003
java
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class lc322_CoinChange { static class Solution { public int coinChange(int[] coins, int amount) { long[] dp = new long[amount + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for (int i = 1; i <= amount; i++) { for (int j = 0; j < coins.length; j++) { if (coins[j] <= i) { dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1); } } } if (dp[amount] > amount) { return -1; } else { return (int)dp[amount]; } } } public static void main(String[] args) { int[] coins = {2}; int amount = 3; Solution tool = new Solution(); int result = tool.coinChange(coins, amount); System.out.println(result); } }
1bffe776531524575dc16adb6b5bf35d70489681
7af2bb75b87a874520f92ab534f7bb04c96b8433
/libgdx/HelloGdx/src/com/badlogic/gdx/assets/loaders/resolvers/ResolutionFileResolver.java
098377621268e8dcfff812ac574342631a530c6e
[]
no_license
ARLM-Attic/android-games
399037330e434f371447f98b4d8e99974e714f1c
8052702224983092d0223bf598b1420cf2cd52b1
refs/heads/master
2021-01-23T11:32:18.975874
2012-10-01T21:39:23
2012-10-01T21:39:23
93,143,294
0
0
null
null
null
null
UTF-8
Java
false
false
2,537
java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.assets.loaders.resolvers; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.files.FileHandle; public class ResolutionFileResolver implements FileHandleResolver { public static class Resolution { int portraitWidth; int portraitHeight; String suffix; public Resolution (int portraitWidth, int portraitHeight, String suffix) { this.portraitWidth = portraitWidth; this.portraitHeight = portraitHeight; this.suffix = suffix; } } final FileHandleResolver baseResolver; final Resolution[] descriptors; public ResolutionFileResolver (FileHandleResolver baseResolver, Resolution... descriptors) { this.baseResolver = baseResolver; this.descriptors = descriptors; } @Override public FileHandle resolve (String fileName) { int width = 0; int height = 0; if (Gdx.graphics.getWidth() > Gdx.graphics.getHeight()) { width = Gdx.graphics.getHeight(); height = Gdx.graphics.getWidth(); } else { width = Gdx.graphics.getWidth(); height = Gdx.graphics.getHeight(); } Resolution bestDesc = null; int bestDistance = Integer.MAX_VALUE; for (int i = 0, n = descriptors.length; i < n; i++) { int distance = Math.abs(width - descriptors[i].portraitWidth) + Math.abs(height - descriptors[i].portraitHeight); if (distance < bestDistance) { bestDistance = distance; bestDesc = descriptors[i]; } } FileHandle originalHandle = new FileHandle(fileName); FileHandle handle = baseResolver.resolve(originalHandle.parent() + "/" + bestDesc.suffix + "/" + originalHandle.name()); if (!handle.exists()) handle = baseResolver.resolve(fileName); return handle; } }
[ "SND\\haijianfeng123_cp@e03b891a-eeb4-4526-88e4-ac663395cb9e" ]
SND\haijianfeng123_cp@e03b891a-eeb4-4526-88e4-ac663395cb9e
1025696aecfacc03d0acca758f4683d90d61bf28
4c5c6b8e8ad9585c8713e71939b9e9e4a21e6059
/nacos-2.0.0/naming/src/main/java/com/alibaba/nacos/naming/push/v2/NamingSubscriberServiceV2Impl.java
9ba7ed06cdc7ff6c9bc13667a9d89bb4bf211215
[ "Apache-2.0" ]
permissive
aoiliao/study
bbfc8d0b091a437681c07ec5b73c2535710790e2
fdba2adbff9211b40278e3c01ad414e332b6a5fa
refs/heads/master
2023-07-06T17:06:54.277457
2021-08-10T03:09:03
2021-08-10T03:09:03
344,394,341
0
0
null
null
null
null
UTF-8
Java
false
false
5,332
java
/* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.naming.push.v2; import com.alibaba.nacos.api.naming.utils.NamingUtils; import com.alibaba.nacos.common.notify.Event; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.listener.SmartSubscriber; import com.alibaba.nacos.naming.core.v2.client.manager.ClientManager; import com.alibaba.nacos.naming.core.v2.client.manager.ClientManagerDelegate; import com.alibaba.nacos.naming.core.v2.event.service.ServiceEvent; import com.alibaba.nacos.naming.core.v2.index.ClientServiceIndexesManager; import com.alibaba.nacos.naming.core.v2.index.ServiceStorage; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement; import com.alibaba.nacos.naming.pojo.Subscriber; import com.alibaba.nacos.naming.push.NamingSubscriberService; import com.alibaba.nacos.naming.push.v2.executor.PushExecutorDelegate; import com.alibaba.nacos.naming.push.v2.task.PushDelayTask; import com.alibaba.nacos.naming.push.v2.task.PushDelayTaskExecuteEngine; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.stream.Stream; /** * Naming subscriber service for v2.x. * * @author xiweng.yy */ @org.springframework.stereotype.Service public class NamingSubscriberServiceV2Impl extends SmartSubscriber implements NamingSubscriberService { private static final int PARALLEL_SIZE = 100; private final ClientManager clientManager; private final ClientServiceIndexesManager indexesManager; private final PushDelayTaskExecuteEngine delayTaskEngine; private final UpgradeJudgement upgradeJudgement; public NamingSubscriberServiceV2Impl(ClientManagerDelegate clientManager, ClientServiceIndexesManager indexesManager, ServiceStorage serviceStorage, PushExecutorDelegate pushExecutor, UpgradeJudgement upgradeJudgement) { this.clientManager = clientManager; this.indexesManager = indexesManager; this.upgradeJudgement = upgradeJudgement; this.delayTaskEngine = new PushDelayTaskExecuteEngine(clientManager, indexesManager, serviceStorage, pushExecutor); NotifyCenter.registerSubscriber(this); } @Override public Collection<Subscriber> getSubscribers(String namespaceId, String serviceName) { String serviceNameWithoutGroup = NamingUtils.getServiceName(serviceName); String groupName = NamingUtils.getGroupName(serviceName); Service service = Service.newService(namespaceId, groupName, serviceNameWithoutGroup); return getSubscribers(service); } @Override public Collection<Subscriber> getSubscribers(Service service) { Collection<Subscriber> result = new HashSet<>(); for (String each : indexesManager.getAllClientsSubscribeService(service)) { result.add(clientManager.getClient(each).getSubscriber(service)); } return result; } @Override public Collection<Subscriber> getFuzzySubscribers(String namespaceId, String serviceName) { Collection<Subscriber> result = new HashSet<>(); Stream<Service> serviceStream = getServiceStream(); String serviceNamePattern = NamingUtils.getServiceName(serviceName); String groupNamePattern = NamingUtils.getGroupName(serviceName); serviceStream.filter(service -> service.getNamespace().equals(namespaceId) && service.getName() .contains(serviceNamePattern) && service.getGroup().contains(groupNamePattern)) .forEach(service -> result.addAll(getSubscribers(service))); return result; } @Override public Collection<Subscriber> getFuzzySubscribers(Service service) { return getFuzzySubscribers(service.getNamespace(), service.getGroupedServiceName()); } @Override public List<Class<? extends Event>> subscribeTypes() { return Collections.singletonList(ServiceEvent.ServiceChangedEvent.class); } @Override public void onEvent(Event event) { if (!upgradeJudgement.isUseGrpcFeatures()) { return; } ServiceEvent.ServiceChangedEvent serviceChangedEvent = (ServiceEvent.ServiceChangedEvent) event; Service service = serviceChangedEvent.getService(); delayTaskEngine.addTask(service, new PushDelayTask(service, 500L)); } private Stream<Service> getServiceStream() { Collection<Service> services = indexesManager.getSubscribedService(); return services.size() > PARALLEL_SIZE ? services.parallelStream() : services.stream(); } }
32e027d6a63b21aca710b2ae8788d20439bb3dad
3c4c1f24f551fb18a7881167855d886c52a66b25
/day17_case_remake/src/cn/itcast/service/impl/UserServiceImpl.java
056c3140cf2849739e07aec7c445b2e21de488b8
[]
no_license
WuQi9527/ideapro
8302821803e03735debb2a5f37afacd5aaf7ae82
ba70709d41011c943baf8cd4a2f8e04743bfce50
refs/heads/master
2021-10-09T11:06:01.428004
2018-12-27T02:36:56
2018-12-27T02:36:56
162,893,631
0
1
null
null
null
null
UTF-8
Java
false
false
1,065
java
package cn.itcast.service.impl; import cn.itcast.dao.UserDao; import cn.itcast.dao.impl.UserDaoImpl; import cn.itcast.domain.User; import cn.itcast.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { private UserDao dao=new UserDaoImpl(); @Override public List<User> findAll() { return dao.findAll(); } @Override public void addUser(User user) { dao.addUser(user); } @Override public void deleteUser(String id) { dao.delete(Integer.parseInt(id)); } @Override public User findUserById(String id) { return dao.findById(Integer.parseInt(id)); } @Override public void updateUser(User user) { dao.updateUser(user); } @Override public void delSelectUser(String[] uids) { for (String uid : uids) { dao.delete(Integer.parseInt(uid)); } } public User login(User user) { return dao.findUserByusernameAndPassword(user.getUsername(),user.getPassword()); } }
b996c50a528ad1ea085cda3755d5f4f9e0a879f1
4bc86d08b0491a1bc04da900bcb87855962bc1ac
/src/main/java/org/reactome/cancer/MCLClusterWrapper.java
513b41d7af3e285a095b1881b3a6a5f3f9f843fe
[]
no_license
reactome-fi/reactome_cancer
62144fdab41a307c9b6c8c73434c5a07f0111b5f
7a68b29e2ff981fdbb263df2f85e2c7b3a2a66fe
refs/heads/master
2020-05-30T10:18:32.217936
2019-06-18T21:54:09
2019-06-18T21:54:09
189,668,484
0
0
null
null
null
null
UTF-8
Java
false
false
8,313
java
/* * Created on Nov 19, 2011 * */ package org.reactome.cancer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.reactome.r3.fi.MCLClusteringHelper; import org.reactome.r3.fi.MCLClusteringResult; import org.reactome.r3.util.FileUtility; import org.reactome.r3.util.InteractionUtilities; import org.reactome.r3.util.R3Constants; /** * @author gwu * */ public class MCLClusterWrapper { private MCLClusteringHelper mclHelper; private double inflation = 5.0d; private boolean useAbsolute = true; public MCLClusterWrapper() { mclHelper = new MCLClusteringHelper(); mclHelper.setMclScript(R3Constants.mclScript); mclHelper.setTempDirName(R3Constants.TEMP_DIR); } public void setTempDirName(String dirName) { mclHelper.setTempDirName(dirName); } public void setInflation(double inflation) { this.inflation = inflation; } public void setUseAbsolute(boolean useAbsolute) { this.useAbsolute = useAbsolute; } public void setKeepTempFile(boolean keep) { mclHelper.setKeepTempFile(keep); } public List<Set<String>> mclCluster(String geneExpFileName, int sizeCutoff, double corCutoff) throws Exception { CancerGeneExpressionCommon helper = new CancerGeneExpressionCommon(); Map<String, Map<String, Double>> geneToSampleToValue = helper.loadGeneExp(geneExpFileName); Set<String> fis = new FileUtility().loadInteractions(R3Constants.GENE_FI_FILE_NAME); Set<String> fisWithCorrs = helper.calculateGeneExpCorrForFIs(geneToSampleToValue, fis, this.useAbsolute, null); return mclCluster(fisWithCorrs, fis, sizeCutoff, corCutoff); } /** * Do a MCL clustering by using p-values for genes. Gene-based p-values are converted * into edge-weights by using geometric or arithemtic mean of two genes involved in the same FIs. * If p-values for either or both genes are missing for a FI, that FI will be excluded. * @param geneToScore * @param useAsPValue the scores are p-values, geometric mean should be used. The edge score * should be -log10. * @return */ public List<Set<String>> mclClusterForGeneScores(Map<String, Double> geneToScore, boolean useAsPValue, Integer sizeCutoff, Double corCutoff) throws Exception { // Load FI network Set<String> fis = new FileUtility().loadInteractions(R3Constants.GENE_FI_BIG_COMP_FILE_NAME); Set<String> fisWithValues = new HashSet<String>(); for (String fi : fis) { String[] tokens = fi.split("\t"); Double value1 = geneToScore.get(tokens[0]); Double value2 = geneToScore.get(tokens[1]); if (value1 == null || value2 == null) continue; if (useAsPValue) { // Use geometric mean for pvalue Double score = -Math.log10(Math.sqrt(value1 * value2)); fisWithValues.add(fi + "\t" + score); } else { // Double score = (value1 + value2) / 2.0d; Double score = Math.min(value1, value2); fisWithValues.add(fi + "\t" + score); } } // clusterWrapper.setInflation(4.5d); List<Set<String>> clusters = mclCluster(fisWithValues); filterClusters(clusters, fisWithValues, fis, sizeCutoff, corCutoff); return clusters; } public List<Set<String>> mclCluster(Set<String> fisWithCorrs, Set<String> fis, int sizeCutoff, double corCutoff) throws Exception { List<Set<String>> clusters = mclCluster(fisWithCorrs); filterClusters(clusters, fisWithCorrs, fis, sizeCutoff, corCutoff); return clusters; } /** * Do a filtering based on average score and size. * @param clusters * @param fisWithCorrs * @param fis * @param sizeCutoff * @param corCutoff * @return the same cluster set should be returned. */ private void filterClusters(List<Set<String>> clusters, Set<String> fisWithCorrs, Set<String> fis, Integer sizeCutoff, Double corCutoff) { if (sizeCutoff != null) { for (Iterator<Set<String>> it = clusters.iterator(); it.hasNext();) { Set<String> cluster = it.next(); if (cluster.size() < sizeCutoff) it.remove(); } } if (corCutoff != null) { List<Double> averageCorrs = calculateAverageCorrelations(clusters, fis, fisWithCorrs); // Filter out some clusters int index = 0; for (Iterator<Set<String>> it = clusters.iterator(); it.hasNext();) { it.next(); Double cor = averageCorrs.get(index); if (cor == null || cor < corCutoff) it.remove(); index ++; } } } /** * The actual method for doing MCL clustering. * @param fisWithCorrs * @return * @throws Exception */ public List<Set<String>> mclCluster(Set<String> fisWithCorrs) throws Exception { MCLClusteringResult mclResults = mclHelper.cluster(fisWithCorrs, inflation); List<Set<String>> clusters = parseMCLResults(mclResults); return clusters; } public List<Double> calculateAverageCorrelations(List<Set<String>> clusters, Set<String> fis, Set<String> fisWithCorrs) { // Use this map for calculation Map<String, Double> fiToCorr = new HashMap<String, Double>(); int index = 0; for (String fiWithCorr : fisWithCorrs) { index = fiWithCorr.lastIndexOf("\t"); fiToCorr.put(fiWithCorr.substring(0, index), new Double(fiWithCorr.substring(index + 1))); } List<Double> corrs = new ArrayList<Double>(); double total = 0.0d; int count = 0; index = 0; for (Set<String> cluster : clusters) { index ++; Set<String> fisInCluster = InteractionUtilities.getFIs(cluster, fis); total = 0.0d; count = 0; for (String fi : fisInCluster) { Double value = fiToCorr.get(fi); if (value != null) { total += value; count ++; } } if (count == 0) // It is possible for some small modules or for sparse array data sets corrs.add(null); else corrs.add(total / count); } return corrs; } private List<Set<String>> parseMCLResults(MCLClusteringResult result) { List<Set<String>> rtn = new ArrayList<Set<String>>(); for (String text : result.getClusters()) { String[] tokens = text.split("\t"); Set<String> set = new HashSet<String>(); for (String token : tokens) set.add(token); rtn.add(set); } return rtn; } }
4e6a9aab453cff3897c93fa2827819a138529a03
6e2241aac77e19b5c2b5adebfca3ae9ea17a3628
/app/src/main/java/com/hzkc/parent/Bean/VipRootBean.java
0190df07f4f90978fdf8cfc88eb3fe55e4df89ed
[]
no_license
15528167063/parent
01234d10c5646d137bd9e0d241383190f799a98a
6094315f327ed004a35d7eecd33d498f65ccc5da
refs/heads/master
2020-04-06T10:40:45.482968
2018-11-13T13:53:30
2018-11-13T13:53:30
157,387,946
0
0
null
null
null
null
UTF-8
Java
false
false
581
java
package com.hzkc.parent.Bean; /** * Created by Administrator on 2018/8/20. */ public class VipRootBean { private int code; private String msg; private VipDataBean data; public void setCode(int code){ this.code = code; } public int getCode(){ return this.code; } public void setMsg(String msg){ this.msg = msg; } public String getMsg(){ return this.msg; } public void setData(VipDataBean data){ this.data = data; } public VipDataBean getData(){ return this.data; } }
03f738032b33b1d342281cd64045a3623800a246
3138255c677a7972ff3f6153282d23ccb99d1c37
/src/main/java/dao/DAOServer.java
b56d129f35da9e1034f0ed71ffe1fa9f95effd57
[]
no_license
thaonoucamp/TEST_MD3
db7821fe8de59cc30b7d902eb813008fa1d3f43a
6eeb857fd52abd218bb7f73543b8481fc3eb49c2
refs/heads/master
2023-06-24T22:26:45.777143
2021-07-12T06:30:21
2021-07-12T06:30:21
385,132,328
0
0
null
null
null
null
UTF-8
Java
false
false
5,012
java
package dao; import model.Product; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class DAOServer implements IDAO<Product> { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; private final String INSERT_INTO_QUERY = "insert into product(`name`, price, quantity, color, description, category) values (?, ?, ?, ?, ?, ?);"; private final String SHOW_ALL_QUERY = "SELECT * FROM product;"; private final String FIND_NAME_QUERY = "select * from product where name like ?;"; private final String FIND_ID_QUERY = "select * from product where id = ?;"; private final String UPDATE_QUERY = "UPDATE product SET `name` = ?, price = ?, quantity = ?, color=?, description=?, category = ? WHERE (id = ?);"; private final String DELETE_QUERY = "DELETE FROM product WHERE (id = ?);"; ConnecMySQL connecMySQL = new ConnecMySQL(); @Override public List<Product> showAll() throws SQLException { List<Product> list = new ArrayList<>(); connection = connecMySQL.getConnection(); statement = connection.prepareStatement(SHOW_ALL_QUERY); resultSet = statement.executeQuery(); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); double price = resultSet.getDouble("price"); int quantity = resultSet.getInt("quantity"); String color = resultSet.getString("color"); String description = resultSet.getString("description"); int category = resultSet.getInt("category"); list.add(new Product(id, name, price, quantity, color, description, category)); } return list; } @Override public List<Product> find(String name) throws SQLException { List<Product> list = new ArrayList<>(); connection = connecMySQL.getConnection(); statement = connection.prepareStatement(FIND_NAME_QUERY); statement.setString(1, name); resultSet = statement.executeQuery(); while (resultSet.next()) { int id = resultSet.getInt("id"); double price = resultSet.getDouble("price"); int quantity = resultSet.getInt("quantity"); String color = resultSet.getString("color"); String description = resultSet.getString("description"); int category = resultSet.getInt("category"); name = resultSet.getString("name"); list.add(new Product(id, name, price, quantity, color, description, category)); } return list; } public Product findId(int id) throws SQLException { Product product = null; connection = connecMySQL.getConnection(); statement = connection.prepareStatement(FIND_ID_QUERY); statement.setInt(1, id); resultSet = statement.executeQuery(); while (resultSet.next()) { id = resultSet.getInt("id"); String name = resultSet.getString("name"); double price = resultSet.getDouble("price"); int quantity = resultSet.getInt("quantity"); String color = resultSet.getString("color"); String description = resultSet.getString("description"); int category = resultSet.getInt("category"); product = new Product(id, name, price, quantity, color, description, category); } return product; } @Override public void add(Product product) throws SQLException { connection = connecMySQL.getConnection(); statement = connection.prepareStatement(INSERT_INTO_QUERY); statement.setString(1, product.getName()); statement.setDouble(2, product.getPrice()); statement.setInt(3, product.getQuantity()); statement.setString(4, product.getColor()); statement.setString(5, product.getDescription()); statement.setInt(6, product.getCategory()); statement.executeUpdate(); } @Override public void edit(int id, Product product) throws SQLException { connection = connecMySQL.getConnection(); statement = connection.prepareStatement(UPDATE_QUERY); statement.setString(1, product.getName()); statement.setDouble(2, product.getPrice()); statement.setInt(3, product.getQuantity()); statement.setString(4, product.getColor()); statement.setString(5, product.getDescription()); statement.setInt(6, product.getCategory()); statement.setInt(7, id); statement.executeUpdate(); } @Override public void delete(int id) throws SQLException { connection = connecMySQL.getConnection(); statement = connection.prepareStatement(DELETE_QUERY); statement.setInt(1, id); statement.executeUpdate(); } }
d63341faae7fbd2178f39d7b57bae9ff52efb511
d97ed809a8b304992ff2b1691483e186b09539d1
/app/src/main/java/lockdown/org/actvapp/MainActivity.java
5d4029a72f7cbbdf4ce1ef1721b810ba90c13204
[]
no_license
shivy1998/AutoCompleteTextViewApp
580751fb67036cf072beddb2cc6840e213941bfc
ac5a1061411ac6384d6cb361c9098f630224fc6f
refs/heads/master
2022-12-01T23:31:12.147697
2020-08-08T16:49:34
2020-08-08T16:49:34
286,082,459
0
0
null
null
null
null
UTF-8
Java
false
false
795
java
package lockdown.org.actvapp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { AutoCompleteTextView actv; public void onCreate(Bundle b) { super.onCreate(b); setContentView(R.layout.activity_main); actv = findViewById(R.id.actv); ArrayList al = new ArrayList(); al.add("Python "); al.add("PHP "); al.add("PERL "); al.add("Android "); al.add("Apple "); ArrayAdapter aa = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,al); actv.setAdapter(aa); actv.setThreshold(1); } }
19b060d8046de97c5722755beb4371c140019ee3
3495c075834a70688858a07236207443a701c04d
/qmui/src/main/java/com/qmuiteam/qmui/widget/textview/QMUISpanTouchFixTextView.java
4596794343ad77a577d9876e21b95d9c60e123ae
[]
no_license
JJOGGER/YiYanKT
413074f1ea24700fbf88d794dfa8c7f4aaa21b19
b8a2b389c2e0803cdd8ad0c1521a4f88e2fcb7b7
refs/heads/master
2021-02-06T19:28:37.205792
2020-05-03T08:06:40
2020-05-03T08:06:40
243,942,932
3
2
null
null
null
null
UTF-8
Java
false
false
14,094
java
/* * Tencent is pleased to support the open source community by making QMUI_Android available. * * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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.qmuiteam.qmui.widget.textview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.text.Spannable; import android.text.method.MovementMethod; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.TextView; import com.qmuiteam.qmui.layout.IQMUILayout; import com.qmuiteam.qmui.layout.QMUILayoutHelper; import com.qmuiteam.qmui.link.QMUILinkTouchMovementMethod; import com.qmuiteam.qmui.span.QMUITouchableSpan; import androidx.annotation.ColorInt; import androidx.appcompat.widget.AppCompatTextView; /** * <p> * 修复了 {@link TextView} 与 {@link android.text.style.ClickableSpan} 一起使用时, * 点击 {@link android.text.style.ClickableSpan} 也会触发 {@link TextView} 的事件的问题。 * </p> * <p> * 同时通过 {@link #setNeedForceEventToParent(boolean)} 控制该 TextView 的点击事件能否传递给其 Parent, * 修复了 {@link TextView} 默认情况下如果添加了 {@link android.text.style.ClickableSpan} 之后就无法把点击事件传递给 {@link TextView} 的 Parent 的问题。 * </p> * <p> * 注意: 使用该 {@link TextView} 时, 用 {@link QMUITouchableSpan} 代替 {@link android.text.style.ClickableSpan}, * 且同时可以使用 {@link QMUITouchableSpan} 达到修改 span 的文字颜色和背景色的目的。 * </p> * <p> * 注意: 使用该 {@link TextView} 时, 需调用 {@link #setMovementMethodDefault()} 方法设置默认的 {@link QMUILinkTouchMovementMethod}, * TextView 会在 {@link #onTouchEvent(MotionEvent)} 时将事件传递给 {@link QMUILinkTouchMovementMethod}, * 然后传递给 {@link QMUITouchableSpan}, 实现点击态的变化和点击事件的响应。 * </p> * * @author cginechen * @date 2017-03-20 * @see QMUITouchableSpan * @see QMUILinkTouchMovementMethod */ public class QMUISpanTouchFixTextView extends AppCompatTextView implements ISpanTouchFix, IQMUILayout { /** * 记录当前 Touch 事件对应的点是不是点在了 span 上面 */ private boolean mTouchSpanHit; /** * 记录每次真正传入的press,每次更改mTouchSpanHint,需要再调用一次setPressed,确保press状态正确 */ private boolean mIsPressedRecord = false; /** * TextView是否应该消耗事件 */ private boolean mNeedForceEventToParent = false; private QMUILayoutHelper mLayoutHelper; public QMUISpanTouchFixTextView(Context context) { this(context, null); } public QMUISpanTouchFixTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public QMUISpanTouchFixTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setHighlightColor(Color.TRANSPARENT); mLayoutHelper = new QMUILayoutHelper(context, attrs, defStyleAttr, this); } public void setNeedForceEventToParent(boolean needForceEventToParent) { mNeedForceEventToParent = needForceEventToParent; setFocusable(!needForceEventToParent); setClickable(!needForceEventToParent); setLongClickable(!needForceEventToParent); } /** * 使用者主动调用 */ public void setMovementMethodDefault(){ setMovementMethodCompat(QMUILinkTouchMovementMethod.getInstance()); } public void setMovementMethodCompat(MovementMethod movement){ setMovementMethod(movement); if(mNeedForceEventToParent){ setNeedForceEventToParent(true); } } @Override public boolean onTouchEvent(MotionEvent event) { if (!(getText() instanceof Spannable)) { return super.onTouchEvent(event); } mTouchSpanHit = true; // 调用super.onTouchEvent,会走到QMUILinkTouchMovementMethod // 会走到QMUILinkTouchMovementMethod#onTouchEvent会修改mTouchSpanHint boolean ret = super.onTouchEvent(event); if(mNeedForceEventToParent){ return mTouchSpanHit; } return ret; } @Override public void setTouchSpanHit(boolean hit) { if (mTouchSpanHit != hit) { mTouchSpanHit = hit; setPressed(mIsPressedRecord); } } @SuppressWarnings("SimplifiableIfStatement") @Override public boolean performClick() { if (!mTouchSpanHit && !mNeedForceEventToParent) { return super.performClick(); } return false; } @SuppressWarnings("SimplifiableIfStatement") @Override public boolean performLongClick() { if (!mTouchSpanHit && !mNeedForceEventToParent) { return super.performLongClick(); } return false; } @Override public final void setPressed(boolean pressed) { mIsPressedRecord = pressed; if (!mTouchSpanHit) { onSetPressed(pressed); } } protected void onSetPressed(boolean pressed) { super.setPressed(pressed); } @Override public void updateTopDivider(int topInsetLeft, int topInsetRight, int topDividerHeight, int topDividerColor) { mLayoutHelper.updateTopDivider(topInsetLeft, topInsetRight, topDividerHeight, topDividerColor); invalidate(); } @Override public void updateBottomDivider(int bottomInsetLeft, int bottomInsetRight, int bottomDividerHeight, int bottomDividerColor) { mLayoutHelper.updateBottomDivider(bottomInsetLeft, bottomInsetRight, bottomDividerHeight, bottomDividerColor); invalidate(); } @Override public void updateLeftDivider(int leftInsetTop, int leftInsetBottom, int leftDividerWidth, int leftDividerColor) { mLayoutHelper.updateLeftDivider(leftInsetTop, leftInsetBottom, leftDividerWidth, leftDividerColor); invalidate(); } public void updateRightDivider(int rightInsetTop, int rightInsetBottom, int rightDividerWidth, int rightDividerColor) { mLayoutHelper.updateRightDivider(rightInsetTop, rightInsetBottom, rightDividerWidth, rightDividerColor); invalidate(); } @Override public void onlyShowTopDivider(int topInsetLeft, int topInsetRight, int topDividerHeight, int topDividerColor) { mLayoutHelper.onlyShowTopDivider(topInsetLeft, topInsetRight, topDividerHeight, topDividerColor); invalidate(); } @Override public void onlyShowBottomDivider(int bottomInsetLeft, int bottomInsetRight, int bottomDividerHeight, int bottomDividerColor) { mLayoutHelper.onlyShowBottomDivider(bottomInsetLeft, bottomInsetRight, bottomDividerHeight, bottomDividerColor); invalidate(); } @Override public void onlyShowLeftDivider(int leftInsetTop, int leftInsetBottom, int leftDividerWidth, int leftDividerColor) { mLayoutHelper.onlyShowLeftDivider(leftInsetTop, leftInsetBottom, leftDividerWidth, leftDividerColor); invalidate(); } @Override public void onlyShowRightDivider(int rightInsetTop, int rightInsetBottom, int rightDividerWidth, int rightDividerColor) { mLayoutHelper.onlyShowRightDivider(rightInsetTop, rightInsetBottom, rightDividerWidth, rightDividerColor); invalidate(); } @Override public void setTopDividerAlpha(int dividerAlpha) { mLayoutHelper.setTopDividerAlpha(dividerAlpha); invalidate(); } @Override public void setBottomDividerAlpha(int dividerAlpha) { mLayoutHelper.setBottomDividerAlpha(dividerAlpha); invalidate(); } @Override public void setLeftDividerAlpha(int dividerAlpha) { mLayoutHelper.setLeftDividerAlpha(dividerAlpha); invalidate(); } @Override public void setRightDividerAlpha(int dividerAlpha) { mLayoutHelper.setRightDividerAlpha(dividerAlpha); invalidate(); } @Override public void setHideRadiusSide(int hideRadiusSide) { mLayoutHelper.setHideRadiusSide(hideRadiusSide); invalidate(); } @Override public int getHideRadiusSide() { return mLayoutHelper.getHideRadiusSide(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { widthMeasureSpec = mLayoutHelper.getMeasuredWidthSpec(widthMeasureSpec); heightMeasureSpec = mLayoutHelper.getMeasuredHeightSpec(heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); int minW = mLayoutHelper.handleMiniWidth(widthMeasureSpec, getMeasuredWidth()); int minH = mLayoutHelper.handleMiniHeight(heightMeasureSpec, getMeasuredHeight()); if (widthMeasureSpec != minW || heightMeasureSpec != minH) { super.onMeasure(minW, minH); } } @Override public void setRadiusAndShadow(int radius, int shadowElevation, final float shadowAlpha) { mLayoutHelper.setRadiusAndShadow(radius, shadowElevation, shadowAlpha); } @Override public void setRadiusAndShadow(int radius, @HideRadiusSide int hideRadiusSide, int shadowElevation, final float shadowAlpha) { mLayoutHelper.setRadiusAndShadow(radius, hideRadiusSide, shadowElevation, shadowAlpha); } @Override public void setRadiusAndShadow(int radius, int hideRadiusSide, int shadowElevation, int shadowColor, float shadowAlpha) { mLayoutHelper.setRadiusAndShadow(radius, hideRadiusSide, shadowElevation, shadowColor, shadowAlpha); } @Override public void setRadius(int radius) { mLayoutHelper.setRadius(radius); } @Override public void setRadius(int radius, @HideRadiusSide int hideRadiusSide) { mLayoutHelper.setRadius(radius, hideRadiusSide); } @Override public int getRadius() { return mLayoutHelper.getRadius(); } @Override public void setOutlineInset(int left, int top, int right, int bottom) { mLayoutHelper.setOutlineInset(left, top, right, bottom); } @Override public void setBorderColor(@ColorInt int borderColor) { mLayoutHelper.setBorderColor(borderColor); invalidate(); } @Override public void setBorderWidth(int borderWidth) { mLayoutHelper.setBorderWidth(borderWidth); invalidate(); } @Override public void setShowBorderOnlyBeforeL(boolean showBorderOnlyBeforeL) { mLayoutHelper.setShowBorderOnlyBeforeL(showBorderOnlyBeforeL); invalidate(); } @Override public boolean setWidthLimit(int widthLimit) { if (mLayoutHelper.setWidthLimit(widthLimit)) { requestLayout(); invalidate(); } return true; } @Override public boolean setHeightLimit(int heightLimit) { if (mLayoutHelper.setHeightLimit(heightLimit)) { requestLayout(); invalidate(); } return true; } @Override public void setUseThemeGeneralShadowElevation() { mLayoutHelper.setUseThemeGeneralShadowElevation(); } @Override public void setOutlineExcludePadding(boolean outlineExcludePadding) { mLayoutHelper.setOutlineExcludePadding(outlineExcludePadding); } @Override public void setShadowElevation(int elevation) { mLayoutHelper.setShadowElevation(elevation); } @Override public int getShadowElevation() { return mLayoutHelper.getShadowElevation(); } @Override public void setShadowAlpha(float shadowAlpha) { mLayoutHelper.setShadowAlpha(shadowAlpha); } @Override public float getShadowAlpha() { return mLayoutHelper.getShadowAlpha(); } @Override public void setShadowColor(int shadowColor) { mLayoutHelper.setShadowColor(shadowColor); } @Override public int getShadowColor() { return mLayoutHelper.getShadowColor(); } @Override public void setOuterNormalColor(int color) { mLayoutHelper.setOuterNormalColor(color); } @Override public void updateBottomSeparatorColor(int color) { mLayoutHelper.updateBottomSeparatorColor(color); } @Override public void updateLeftSeparatorColor(int color) { mLayoutHelper.updateLeftSeparatorColor(color); } @Override public void updateRightSeparatorColor(int color) { mLayoutHelper.updateRightSeparatorColor(color); } @Override public void updateTopSeparatorColor(int color) { mLayoutHelper.updateTopSeparatorColor(color); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); mLayoutHelper.drawDividers(canvas, getWidth(), getHeight()); mLayoutHelper.dispatchRoundBorderDraw(canvas); } @Override public boolean hasBorder() { return mLayoutHelper.hasBorder(); } @Override public boolean hasLeftSeparator() { return mLayoutHelper.hasLeftSeparator(); } @Override public boolean hasTopSeparator() { return mLayoutHelper.hasTopSeparator(); } @Override public boolean hasRightSeparator() { return mLayoutHelper.hasRightSeparator(); } @Override public boolean hasBottomSeparator() { return mLayoutHelper.hasBottomSeparator(); } }
e9fee4b8e4ef49eaa5da9e39c13af537b1c75f85
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/15/15_c3e4b87d01edbca974e83ffe7e4b4ace1e8f9d86/SetupUtils/15_c3e4b87d01edbca974e83ffe7e4b4ace1e8f9d86_SetupUtils_t.java
630f7bb7b8d77f7ad3ad25117a47b2f2bbfec9bc
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
20,039
java
/* The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * https://opensso.dev.java.net/public/CDDLv1.0.html or * opensso/legal/CDDLv1.0.txt * See the License for the specific language governing * permission and limitations under the License. * * When distributing Covered Code, include this CDDL * Header Notice in each file and include the License file * at opensso/legal/CDDLv1.0.txt. * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * $Id: SetupUtils.java,v 1.3 2008-04-24 07:54:21 beomsuk Exp $ * * Copyright 2007 Sun Microsystems Inc. All Rights Reserved */ package com.sun.identity.tools.bundles; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.util.Enumeration; import java.util.LinkedList; import java.util.ListIterator; import java.util.MissingResourceException; import java.util.Properties; import java.util.ResourceBundle; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class SetupUtils implements SetupConstants{ private SetupUtils() { } /** * Loads properties from file. * * @param fileName The path to the properties file. * @param outside The flat to indicate whether the file is in the package. * @return The Properties object of the specified propertoes file. */ public static Properties loadProperties(String fileName) throws IOException { Properties prop = new Properties(); InputStream propIn = new FileInputStream(fileName); try { prop.load(propIn); } finally { propIn.close(); } return prop; } /** * Prompts user for input from system in. * * @param message The text message to prompt the user. * @return The user input. */ public static String getUserInput(String message) throws IOException { String userInput = null; BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); try { System.out.print(message); userInput = in.readLine(); } finally { in.close(); } return userInput; } /** * Gets the map for text replacement. * * @param bundle The ResourceBundle which contains the tokens' name. * @param confProp The properties which may contain the tokens value. * @return The properties object as a map for text replacement. */ public static Properties getTokens(ResourceBundle bundle, Properties confProp) { String currentOS = determineOS(); String tokenString = bundle.getString(currentOS + TOKEN); int tokensOffset = 0; int commaIndex = tokenString.indexOf(",", tokensOffset); String tempVarName = null; String tempVarValue = null; Properties tokens = new Properties(); do { if (commaIndex > tokensOffset) { tempVarName = tokenString.substring(tokensOffset, commaIndex). trim(); try{ tempVarValue = bundle.getString(currentOS + "." + tempVarName); } catch (MissingResourceException ex) { tempVarValue = bundle.getString(tempVarName); } tempVarValue = evaluatePropertiesValue(tempVarValue, confProp); if (tempVarValue != null) { tokens.setProperty(tempVarName, tempVarValue); } } else { if (tokensOffset < tokenString.length()) { tempVarName = tokenString.substring(tokensOffset, tokenString.length()).trim(); if (tempVarName.length() > 0) { try{ tempVarValue = bundle.getString(currentOS + "." + tempVarName); } catch (MissingResourceException ex) { tempVarValue = bundle.getString(tempVarName); } } else { break; } tempVarValue = evaluatePropertiesValue(tempVarValue, confProp); if (tempVarValue != null) { tokens.setProperty(tempVarName, tempVarValue); } } break; } tokensOffset = commaIndex + 1; commaIndex = tokenString.indexOf(",", tokensOffset); } while (true); return tokens; } /** * Lookups and replaces the variables in the string * * @param value The string may contain variables which need to be replaced. * @param lookupProp The properties may contain the real values. * @return The String with variables replaced by correct value. */ public static String evaluatePropertiesValue(String value, Properties lookupProp) { if (value == null) { return null; } String returnValue = value; if (lookupProp != null) { int offset = 0; int refPrefix = 0; int refSuffix = 0; String key = null; String realValue = null; while (((refPrefix = returnValue.indexOf(VAR_PREFIX)) >= 0) && ((refSuffix = returnValue.indexOf(VAR_SUFFIX)) > refPrefix)) { key = returnValue.substring(refPrefix + VAR_PREFIX.length(), refSuffix); if ((lookupProp != null) && (lookupProp.containsKey(key))) { realValue = lookupProp.getProperty(key); } else { if (key.equals(BASE_DIR)) { try { realValue = new File(".").getCanonicalPath(); } catch (IOException ignored) { } } else { realValue = System.getProperty(key); } } if (realValue != null) { if (realValue.indexOf("\\") >= 0) { realValue = realValue.replaceAll("\\\\", "/"); } returnValue = returnValue.replaceAll(REX_VAR_PREFIX + key + REX_VAR_SUFFIX, realValue); } //offset = refSuffix + 1; } } return returnValue; } /** * Get the from files list and the to file list. * * @param fromDir The directory of the source files located * @param toDir The directory of the destinated files located * @param fromFilePattern The pattern of the name of source files. * @param toFilePattern The pattern of the name of destinated files. * @param (as return) fromFileList List of files from the source directory. * @param (as return) toFileList List of files of the destinated directory. */ public static void getFiles(File fromDir, File toDir, String fromFilePattern, String toFilePattern, LinkedList fromFilesList, LinkedList toFilesList) { File[] fromFiles = fromDir.listFiles( new GeneralFileFilter(fromFilePattern)); for (int i = 0 ; i < fromFiles.length ; i++) { fromFilesList.addLast(fromFiles[ i ]); if (fromFiles[ i ].isDirectory()) { toFilesList.addLast(new File(toDir, fromFiles[ i ].getName())); getFiles(fromFiles[ i ], new File(toDir, fromFiles[ i ] .getName()), fromFilePattern, toFilePattern, fromFilesList, toFilesList); } else { toFilesList.addLast(new File(toDir, SetupUtils.transformFileName(fromFilePattern, toFilePattern, fromFiles[ i ]))); } } } /** * Determines the current operating system. * * @return The string to represent the current operating system. */ public static String determineOS() { if (OS_ARCH.toLowerCase().indexOf(X86) >= 0) { if (OS_NAME.toLowerCase().indexOf(WINDOWS) >= 0) { return WINDOWS; } else { if (OS_NAME.toLowerCase().indexOf(SUNOS) >= 0) { return X86SOLARIS; } else { return LINUX; } } } else { return SOLARIS; } } /** * Transform the file name by using string patterns. * * @param from The pattern of the source file. * @param to The pattern of the destinated file. * @param file The file to be transform. * @return The transformed name of the file. */ public static String transformFileName(String from, String to, File file) { return transformFileName(from, to, file, DEFAULT_WILD_CARD); } /** * Transform the file name by using string patterns. * * @param from The pattern of the source file. * @param to The pattern of the destinated file. * @param file The file to be transform. * @param wildCard The wildcard character is used in the string pattern. * @return The transformed name of the file. */ public static String transformFileName(String from, String to, File file, char wildCard) { if (file.isDirectory()) { return file.getName(); } else { String fileName = file.getName(); LinkedList tokensToKeep = new LinkedList(); StringBuffer nameToReturn = new StringBuffer(); String tempFrom = from.trim(); String tempTo = to.trim(); int fileNameOffset = 0; boolean matched = true; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < tempFrom.length(); i++) { if (tempFrom.charAt(i) != wildCard) { buffer.append(tempFrom.charAt(i)); } if ((i == (tempFrom.length() - 1)) || (tempFrom.charAt(i) == wildCard)) { if (buffer.length() > 0) { int matchedIndex = fileName.indexOf(buffer.toString(), fileNameOffset); if (matchedIndex >= fileNameOffset) { if (matchedIndex != fileNameOffset) { tokensToKeep.addLast(fileName.substring( fileNameOffset, matchedIndex)); } else { if ((tempFrom.charAt(i) == wildCard) && (i == tempFrom.length() - 1)) { if (matchedIndex + buffer.toString().length() < fileName.length()) { tokensToKeep.addLast( fileName.substring( matchedIndex + buffer.toString().length(), fileName.length())); } } } if (i != (tempFrom.length() - 1)) { fileNameOffset = matchedIndex + buffer.length(); } else { if (tempFrom.charAt(i) != wildCard) { if (fileName.substring(matchedIndex) .length() != buffer.length()) { matched = false; break; } } } } else { matched = false; break; } buffer = new StringBuffer(); } } } if (matched) { for (int i = 0; i < tempTo.length(); i++) { if (tempTo.charAt(i) != wildCard) { nameToReturn.append(tempTo.charAt(i)); } else { if (tokensToKeep.size() > 0) { nameToReturn.append(tokensToKeep.removeFirst()); } } } return nameToReturn.toString(); } } return null; } /** * Unzip the zip archive from source file to destinated directory. * * @param srcFile The path to the source zip archive. * @param destDir The destinated directory for the decompressed zip archive. * @param overwrite The flat to indicate whether to overwrite the files. */ public static void unzip(String srcFile, String destDir, boolean overwrite) throws IOException { File jmqDir = new File(destDir); if (! jmqDir.exists() || overwrite) { jmqDir.mkdirs(); ZipFile zf = new ZipFile(srcFile); Enumeration e = zf.entries(); byte[] buffer = new byte[BUFFER_SIZE]; while (e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); if (ze.isDirectory()) { new File(destDir, ze.getName()).mkdirs(); } else { File destFile = new File(destDir, ze.getName()); File destParentFile=new File(destFile.getParent()); destParentFile.mkdirs(); FileOutputStream fout = new FileOutputStream(destFile); InputStream in = zf.getInputStream(ze); int byteRead = 0; while ((byteRead = in.read(buffer)) != -1) { fout.write(buffer, 0, byteRead); } in.close(); fout.close(); } } } } /** * Ungzip the gzip archive from source file to destinated directory. * * @param srcFile The path to the source gzip archive. * @param destDir The destinated directory for the decompression. */ public static void ungzip(String srcFile, String destDir) throws IOException { String tempDestFileName = srcFile.substring(0, srcFile.lastIndexOf(".")); tempDestFileName = tempDestFileName.substring(srcFile.lastIndexOf( FILE_SEPARATOR) + 1); File bdbDir = new File(destDir); if (!bdbDir.exists()) { bdbDir.mkdir(); byte[] buffer = new byte[BUFFER_SIZE]; GZIPInputStream gzin = new GZIPInputStream(new FileInputStream(srcFile)); FileOutputStream fout = new FileOutputStream(new File(destDir, tempDestFileName)); int byteRead = 0; while ((byteRead = gzin.read(buffer)) != -1) { fout.write(buffer, 0, byteRead); } gzin.close(); fout.close(); } } /** * Prints the usage through system out. * @param bundle The ResourceBundle which contains the message. */ public static void printUsage(ResourceBundle bundle){ System.out.println(bundle.getString("message.info.usage")); } /** * Lookups and set the resource bundle variables to the Properties * * @param bundle The ResourceBundle is going to be evaluated. * @param lookupProp The properties may contain the real values and the * storage of the results. */ public static void evaluateBundleValues(ResourceBundle bundle, Properties lookupProp){ Enumeration propNames = bundle.getKeys(); while (propNames.hasMoreElements()) { String name = (String) propNames.nextElement(); String value = (String) SetupUtils.evaluatePropertiesValue(bundle .getString(name), lookupProp); if (value != null) { lookupProp.setProperty(name, value); } } } /** * Copy and replace the variables in the scripts. * * @param bundle The ResourceBundle which contains the prompt messages. * @param lookupProp The properties which contains the variables map, file * patterns, source directory, and destinated directory. */ public static void copyAndFilterScripts(ResourceBundle bundle, Properties lookupProp) throws IOException{ String currentOS = determineOS(); String fromFilePattern = lookupProp.getProperty(currentOS + FROM_FILE); String toFilePattern = lookupProp.getProperty(currentOS + TO_FILE); String tempFromDir = lookupProp.getProperty(currentOS + FROM_DIR); String tempToDir = lookupProp.getProperty(currentOS + TO_DIR); File fromDir = new File(tempFromDir); File toDir = new File(tempToDir); if (toDir.isAbsolute()) { toDir = new File(toDir.getName()); } Properties tokens = SetupUtils.getTokens(bundle, lookupProp); LinkedList fromFilesList = new LinkedList(); LinkedList toFilesList = new LinkedList(); SetupUtils.getFiles(fromDir, toDir, fromFilePattern, toFilePattern, fromFilesList, toFilesList); ListIterator srcIter = fromFilesList.listIterator(); ListIterator destIter = toFilesList.listIterator(); while ((srcIter.hasNext()) && (destIter.hasNext())) { File srcFile = (File) srcIter.next(); File destFile = (File) destIter.next(); CopyUtils.copyFile(srcFile, destFile, tokens, true, false); } if (! currentOS.equals(WINDOWS)) { Process proc = Runtime.getRuntime().exec("/bin/chmod -R +x " + toDir.getName()); try { if (proc.waitFor() != 0) { System.out.println(bundle.getString("message.info." + "permission.scripts")); } } catch (InterruptedException ex) { System.out.println(bundle.getString("message.info." + "permission.scripts")); //ex.printStackTrace(); } } System.out.println(bundle.getString("message.info.success") + " " + (new File(".")).getCanonicalPath() + FILE_SEPARATOR + toDir.getName()); } }
c95c542b3270a6f48766e534771575493e18f940
3b7682f5dc9595f368eb1dd809ea67e502f92872
/app/src/main/java/com/jeahn/skyscanner/src/login/LoginSuccessActivity.java
009a3de4448041156ec197c0f80423316ac3a1cb
[]
no_license
JieunAn21/skyscanner-mock-android-jinny
26ddf25eba23d61a6326c1d8f68dda7dcd614cf3
3d181c93e485b6ddf3c91fc922923e303344d950
refs/heads/master
2021-01-03T21:37:18.937935
2020-02-29T05:27:21
2020-02-29T05:27:21
240,245,779
0
0
null
2020-02-13T11:35:52
2020-02-13T11:35:51
null
UTF-8
Java
false
false
1,394
java
package com.jeahn.skyscanner.src.login; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; import androidx.annotation.Nullable; import com.jeahn.skyscanner.R; import com.jeahn.skyscanner.src.BaseActivity; public class LoginSuccessActivity extends BaseActivity { private static int REGISTER_SUCCESS = 100; private static int LOGIN_SUCCESS = 200; private TextView mTvMessage; private int type; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_success); mTvMessage = findViewById(R.id.login_success_tv_message); Intent intent = getIntent(); if(intent != null){ String message = intent.getStringExtra("message"); mTvMessage.setText(message); type = intent.getIntExtra("type", 0); } Handler handler = new Handler(); handler.postDelayed(() -> { finish(); setResult(type); // LoginActivity.mLoginActivity.finish(); // if(type == LOGIN_SUCCESS){ // LoginMainActivity.mLogintMainActivity.finish(); // } }, 2000); } @Override public void onBackPressed() { //뒤로가기 버튼 못누르게 함 } }
5055644f877c4726eed9568a7005a8b8008eb7e5
44d3f9b302f15b6439c6290a12be8f30fb8faadb
/src/java/hoaitq/user/UserErrorDTO.java
66626fd9703b859f1f0008455be4fdff8dd68748
[]
no_license
ThaiQuocHoai/Car-Rental
7c2f84eaff523f0a313d8928836bd739494f89cc
cf5d370279614609c718ecd03b6d8f4d28e3beb2
refs/heads/main
2023-03-23T15:13:18.660286
2021-03-11T05:48:31
2021-03-11T05:48:31
346,252,355
0
0
null
null
null
null
UTF-8
Java
false
false
3,583
java
/* * 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 hoaitq.user; import java.io.Serializable; /** * * @author QH */ public class UserErrorDTO implements Serializable{ private String usernameError ; private String passwordError; private String fullnameError; private String phoneError; private String addressError; private String createdateError; private String validateCodeError; private String confirmPasswordError; public UserErrorDTO() { } public UserErrorDTO(String usernameError, String passwordError, String fullnameError, String phoneError, String addressError, String createdateError, String validateCodeError, String confirmPasswordError) { this.usernameError = usernameError; this.passwordError = passwordError; this.fullnameError = fullnameError; this.phoneError = phoneError; this.addressError = addressError; this.createdateError = createdateError; this.validateCodeError = validateCodeError; this.confirmPasswordError = confirmPasswordError; } /** * @return the usernameError */ public String getUsernameError() { return usernameError; } /** * @param usernameError the usernameError to set */ public void setUsernameError(String usernameError) { this.usernameError = usernameError; } /** * @return the passwordError */ public String getPasswordError() { return passwordError; } /** * @param passwordError the passwordError to set */ public void setPasswordError(String passwordError) { this.passwordError = passwordError; } /** * @return the fullnameError */ public String getFullnameError() { return fullnameError; } /** * @param fullnameError the fullnameError to set */ public void setFullnameError(String fullnameError) { this.fullnameError = fullnameError; } /** * @return the phoneError */ public String getPhoneError() { return phoneError; } /** * @param phoneError the phoneError to set */ public void setPhoneError(String phoneError) { this.phoneError = phoneError; } /** * @return the addressError */ public String getAddressError() { return addressError; } /** * @param addressError the addressError to set */ public void setAddressError(String addressError) { this.addressError = addressError; } /** * @return the createdateError */ public String getCreatedateError() { return createdateError; } /** * @param createdateError the createdateError to set */ public void setCreatedateError(String createdateError) { this.createdateError = createdateError; } /** * @return the validateCodeError */ public String getValidateCodeError() { return validateCodeError; } /** * @param validateCodeError the validateCodeError to set */ public void setValidateCodeError(String validateCodeError) { this.validateCodeError = validateCodeError; } public String getConfirmPasswordError() { return confirmPasswordError; } public void setConfirmPasswordError(String confirmPasswordError) { this.confirmPasswordError = confirmPasswordError; } }
20e8a8228bbd0e652b842ed5ef2acda572b8abbe
987b4a0e2124d2c308e886115ff7bda347e820f7
/后端/backstage/java/javas1/day19_filter&listener/filter&listener/src/cn/itcast/web/servlet/ServletDemo2.java
a5f2b83c23db5472470ec1b7c935a8b4c62401ef
[ "MIT" ]
permissive
togethter/learnDic
48606e0afbb08b77c49c135cdd4238f0011fcfc9
f1d0623ff96e24d67aa150ea45862d1cf52b75f3
refs/heads/master
2021-06-13T06:08:08.235217
2021-03-14T15:45:09
2021-03-14T15:45:09
163,981,843
0
0
MIT
2019-06-21T14:37:03
2019-01-03T14:15:27
null
UTF-8
Java
false
false
816
java
package cn.itcast.web.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/user/updateServlet") public class ServletDemo2 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("updateServlet..."); // 转发到index.jsp request.getRequestDispatcher("/index.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
fd5617bc28659b496e049474182b7eb01585aa1e
50fe9521ae11cbebab8b3880598db8d01ad98f9f
/src/main/java/com/github/hugovallada/gvendas/dto/ItemVendaResponseDTO.java
9326ce70e7b12001d1616e31a30a5f22847c28a4
[]
no_license
hugovallada/gvendas
bcf8cc89286ce59d550235f995068ede611e7007
64d2c07cfabef8246bac6cd7aed6fd702eb909b9
refs/heads/main
2023-03-22T14:05:32.475959
2021-03-12T20:49:43
2021-03-12T20:49:43
344,896,708
0
0
null
2021-03-12T20:49:43
2021-03-05T18:17:29
Java
UTF-8
Java
false
false
757
java
package com.github.hugovallada.gvendas.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.*; import java.math.BigDecimal; @ApiModel("Itens da Venda Retorno DTO") @Getter @Setter @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode public class ItemVendaResponseDTO { @ApiModelProperty(name = "Código do item da venda") private Long codigo; @ApiModelProperty(name = "Quantidade") private Integer quantidade; @ApiModelProperty(name = "Preço da venda") private BigDecimal precoVendido; @ApiModelProperty(name = "Código do Produto") private Long codigoProduto; @ApiModelProperty(name = "Descrição do Produto") private String produtoDescricao; }
aac961628a77fd1df7cd70f288d2e06b82928216
109eabe8d75f93b0fca13e78ebcedb3d6fc5d4bb
/proyecto/src/main/java/com/kenny/app/repository/JPAComunidadDao.java
db23031e43e2569b56d8b9813bf8aea0785c34ff
[]
no_license
kennyrodas/proyecto
23887a67cd53e367d920cb912b4ce4c684d64c0d
9db6f93ba4e614c4ca91dd6995b7960ada20fed1
refs/heads/master
2016-09-06T21:26:01.759520
2013-11-09T18:31:33
2013-11-09T18:31:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,067
java
package com.kenny.app.repository; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.kenny.app.domain.Comunidad; @Repository(value = "ComunidadDao") public class JPAComunidadDao implements ComunidadDao { private EntityManager em = null; /* * Sets the entity manager. */ @PersistenceContext public void setEntityManager(EntityManager em) { this.em = em; } @Transactional(readOnly = true) @SuppressWarnings("unchecked") public List<Comunidad> getComunidadList() { return em.createQuery("select p from Comunidad p").getResultList(); } @Transactional(readOnly = true) @SuppressWarnings("unchecked") public List<Comunidad> getComunidadListByDistrito(int distrito_id) { return em.createQuery("select p from Comunidad p WHERE distritoId = '"+distrito_id+"'").getResultList(); } }
4461c33539c91003501777ad69df421747e79f16
dfd59a5f5fa79f7d93f7da94862cfcc8d349277d
/back/main/java/py/com/ceamso/administracion/model/CptECategoria.java
d69d8d60b59453189f530e671ef1b2dab8e74a35
[]
no_license
federix8190/Silv
05c6097cf0ebd60629a4fe9c7212f31ef29730a6
989cb2a52880cb8961280f87ece873e10c55f5e6
refs/heads/main
2023-04-03T06:31:30.287262
2021-04-13T13:31:37
2021-04-13T13:31:37
357,357,718
0
1
null
null
null
null
UTF-8
Java
false
false
1,073
java
/* * 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 py.com.ceamso.administracion.model; import java.io.Serializable; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; import py.com.ceamso.base.WritableEntity; /** * * @author daniel */ @Entity @Table(name = "cpt_ee_categoria") public class CptECategoria extends WritableEntity implements Serializable{ private static final long serialVersionUID = 1L; @EmbeddedId private CptECategoriaPK pk; public CptECategoria(){ } public CptECategoria(CptECategoriaPK pk) { this.pk = pk; } public CptECategoriaPK getPk() { return pk; } public void setPk(CptECategoriaPK pk) { this.pk = pk; } public Long getIdCptE(){ return pk.getIdCptE(); } public String getIdCategoria(){ return pk.getIdCategoria(); } }
[ "federix.8190@gmail" ]
federix.8190@gmail
cd24991d07666c8d4ffdb23865661577f61519d1
7579968901e8ba07621b8ee800e4dbdd992d223b
/app/src/main/java/com/example/dash/model/Item.java
518241a4e0f168c054c9128f4229c59d9bb10ee6
[]
no_license
mike1806/dash
d045421d42761f758b107459a2834f5adf5aaba9
4dcd6bad7d017e77fc1c6516f91f3b3308a9f3ae
refs/heads/master
2022-05-28T01:37:42.946157
2020-04-25T22:21:35
2020-04-25T22:21:35
258,885,290
0
0
null
null
null
null
UTF-8
Java
false
false
759
java
package com.example.dash.model; public class Item { private String image; private String name; private String description; public Item(){}; public Item(String image, String name, String description){ this.image = image; this.name = name; this.description = description; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
2be7a8b26e4528ada9784f47f949bc6065135b90
c3282c43d88c1ea0886d90b7c4dbf377f36e8d66
/SpringDemo/src/main/java/cn/jjz/spring804_1/dao/IStockDAO.java
bbdd7b3e84488c75aee4b2ca4797381f34d1a5cf
[]
no_license
jiangjize/Y2
511ca4d693cd00a9754aa03da10139c2d259a8d2
2233d59885c5ff93df76117990572165d8c72934
refs/heads/master
2021-08-16T07:03:29.028958
2017-11-19T07:13:27
2017-11-19T07:13:27
111,273,000
0
0
null
null
null
null
UTF-8
Java
false
false
258
java
package cn.jjz.spring804_1.dao; import cn.jjz.spring804_1.entity.Stock; /** * Created by Happy on 2017-08-04. */ public interface IStockDAO { public boolean addStock(Stock stock); public boolean updateStock(int sid, int count, boolean isBuy); }
9e4e4ee7c6e33217e9066d3297a620bd466c1fef
bb77aa275eba268038949ac74e2f594301a592d4
/src/main/java/br/com/estudomock/leilao/infra/dao/LeilaoDao.java
2aaa7ea15c1b89aa20026fb477b9a4b37e6702b2
[]
no_license
huelton/ProjetoEstudoMockTest
6b4cb5a747db67c99e672801b193272fce1f30f6
bb0c3c2dae9622baa2d03ad62a4d0f39a5eb7b34
refs/heads/master
2020-05-16T08:38:44.685584
2019-04-23T03:18:51
2019-04-23T03:18:51
182,920,469
0
0
null
null
null
null
ISO-8859-1
Java
false
false
3,876
java
package br.com.estudomock.leilao.infra.dao; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import br.com.estudomock.leilao.dominio.Lance; import br.com.estudomock.leilao.dominio.Leilao; import br.com.estudomock.leilao.dominio.Usuario; import br.com.estudomock.leilao.infra.repositorio.RepositorioDeLeiloes; public class LeilaoDao implements RepositorioDeLeiloes{ private Connection conexao; public LeilaoDao() { try { this.conexao = DriverManager.getConnection( "jdbc:mysql://localhost/mocks", "root", "root"); } catch (Exception e) { throw new RuntimeException(e); } } private Calendar data(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); return c; } public void salva(Leilao leilao) { try { String sql = "INSERT INTO LEILAO (DESCRICAO, DATA, ENCERRADO) VALUES (?,?,?);"; PreparedStatement ps = conexao.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, leilao.getDescricao()); ps.setDate(2, new java.sql.Date(leilao.getData().getTimeInMillis())); ps.setBoolean(3, leilao.isEncerrado()); ps.execute(); ResultSet generatedKeys = ps.getGeneratedKeys(); if (generatedKeys.next()) { leilao.setId(generatedKeys.getInt(1)); } for(Lance lance : leilao.getLances()) { sql = "INSERT INTO LANCE (ID_LEILAO, ID_USUARIO, VALOR) VALUES (?,?,?);"; PreparedStatement ps2 = conexao.prepareStatement(sql); ps2.setInt(1, leilao.getId()); ps2.setInt(2, lance.getUsuario().getId()); ps2.setDouble(3, lance.getValor()); ps2.execute(); ps2.close(); } ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } } public List<Leilao> encerrados() { return porEncerrado(true); } public List<Leilao> correntes() { return porEncerrado(false); } private List<Leilao> porEncerrado(boolean status) { try { String sql = "SELECT * FROM LEILAO WHERE ENCERRADO = " + status + ";"; PreparedStatement ps = conexao.prepareStatement(sql); ResultSet rs = ps.executeQuery(); List<Leilao> leiloes = new ArrayList<Leilao>(); while(rs.next()) { Leilao leilao = new Leilao(rs.getString("descricao"), data(rs.getDate("data"))); leilao.setId(rs.getInt("id")); if(rs.getBoolean("encerrado")) leilao.encerra(); String sql2 = "SELECT VALOR, NOME, U.ID AS ID_USUARIO, L.ID AS ID_LANCE FROM LANCE L INNER JOIN USUARIO U ON U.ID = L.ID_USUARIO WHERE ID_LEILAO = " + rs.getInt("id"); PreparedStatement ps2 = conexao.prepareStatement(sql2); ResultSet rs2 = ps2.executeQuery(); while(rs2.next()) { Usuario usuario = new Usuario(rs2.getInt("id"), rs2.getString("nome")); Lance lance = new Lance(usuario, rs2.getDouble("valor")); leilao.propoe(lance); } rs2.close(); ps2.close(); leiloes.add(leilao); } rs.close(); ps.close(); return leiloes; } catch (SQLException e) { throw new RuntimeException(e); } } public void atualiza(Leilao leilao) { try { String sql = "UPDATE LEILAO SET DESCRICAO=?, DATA=?, ENCERRADO=? WHERE ID = ?;"; PreparedStatement ps = conexao.prepareStatement(sql); ps.setString(1, leilao.getDescricao()); ps.setDate(2, new java.sql.Date(leilao.getData().getTimeInMillis())); ps.setBoolean(3, leilao.isEncerrado()); ps.setInt(4, leilao.getId()); ps.execute(); } catch (SQLException e) { throw new RuntimeException(e); } } public int x() { return 10; } // para conhecimento, NÃO É POSSIVEL MOCKAR OBJETOS ESTATICOS. public static String teste() { return "teste"; } }
9192d256d5fd2ddbd0c6e887a91bffd144e85f21
ad685cb18b18a29867305e4cf5a851dc31257ff5
/src/lab3/ViewLibrary.java
aa892070c3ea03a84b40b1b1b91dab1f68729c3d
[]
no_license
savani84/LMS-System
60f958efa9eb779917efe35d14f582b174cdd9bc
2d1e1c6ee60706b83d83a49cad62f581ec2891e8
refs/heads/master
2021-01-01T03:40:16.918032
2016-05-16T04:23:41
2016-05-16T04:23:41
58,903,201
0
0
null
null
null
null
UTF-8
Java
false
false
1,728
java
package lab3; import java.util.List; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ViewLibrary */ @WebServlet("/ViewLibrary") public class ViewLibrary extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public ViewLibrary() { // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ public void init() throws ServletException { // TODO Auto-generated method stub List<Library> entries = new ArrayList<Library>(); entries.add(new Library(1,"A","B",5)); entries.add(new Library(2,"C","D",0)); getServletContext().setAttribute( "entries", entries ); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @SuppressWarnings("unchecked") protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub List<Library> entries = (List<Library>)getServletContext().getAttribute("entries"); request.setAttribute("htmlentries",entries); request.getRequestDispatcher("ViewLib.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
99cf068ed726508339cd993bb590248f997f1b27
aafa7bcb4d914eb6341bd767a4317800c818a8b7
/assignments/Collectionb/src/com/manthan/collection/set/Test.java
51cc2ba2954085b5da53de507527dee5a17b138f
[]
no_license
prashantsuman07/Manthan-ELF-16-OCT-19-Prashant-Suman
2bf4923678f0defa0a2d67ab1079bed9624f8c31
a11f5305ada7974bb2fe0b739b27ff192ef014db
refs/heads/master
2020-09-16T21:22:57.364955
2019-12-09T10:08:57
2019-12-09T10:08:57
223,890,473
0
0
null
null
null
null
UTF-8
Java
false
false
696
java
package com.manthan.collection.set; import java.util.Iterator; import java.util.TreeSet; public class Test { public static void main(String[] args) { Student p1=new Student(1, "Divya", 1.7); Student p2=new Student(20, "Divyaa", 9.7); Student p3=new Student(3, "Divyaaa", 2.7); Student p4=new Student(4, "Divyaaaa", 1.7); StudentById s=new StudentById(); StudentByName s1=new StudentByName(); TreeSet<Student> a=new TreeSet<Student>(s1); a.add(p1); a.add(p2); a.add(p3); a.add(p4); Iterator<Student>i=a.iterator(); while(i.hasNext()) { Student e=i.next(); System.out.println(e.id); System.out.println(e.name); System.out.println(e.per); } } }
7401813b502cae9b4451dfdb8cb5d065dd51c875
e3b1bd03d2723d476b3df04e101d1a151976ae4e
/app/src/main/java/ello/views/customize/RangeSeekBar.java
4b7ec070edf6a68128f6bdef861607de028873fd
[]
no_license
skysoft419/android-dating-Elo
44001da8dda7ce9ff6a3b132d2310cfa7e411b9c
3b33f2be65d54cccc1c6a8796254f7c31b6a492a
refs/heads/master
2020-08-27T18:03:03.077474
2019-10-25T14:48:54
2019-10-25T14:48:54
217,453,487
0
0
null
null
null
null
UTF-8
Java
false
false
34,771
java
package ello.views.customize; /** * @package com.trioangle.igniter * @subpackage view.customize * @category RangeSeekBar * @author Trioangle Product Team * @version 1.0 **/ import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import ello.R; import ello.interfaces.OnRangeSeekBarChangeListener; import ello.interfaces.OnRangeSeekBarFinalValueListener; /***************************************************************** Custom range seek bar ****************************************************************/ public class RangeSeekBar extends View { ////////////////////////////////////////// // PRIVATE CONSTANTS ////////////////////////////////////////// private static final int INVALID_POINTER_ID = 255; //private static final int DEFAULT_THUMB_WIDTH = 80; //private static final int DEFAULT_THUMB_HEIGHT = 80; private final float NO_STEP = -1f; private final float NO_FIXED_GAP = -1f; ////////////////////////////////////////// // PUBLIC CONSTANTS CLASS ////////////////////////////////////////// private OnRangeSeekBarChangeListener onRangeSeekbarChangeListener; ////////////////////////////////////////// // PRIVATE VAR ////////////////////////////////////////// private OnRangeSeekBarFinalValueListener onRangeSeekbarFinalValueListener; private float absoluteMinValue; private float absoluteMaxValue; private float absoluteMinStartValue; private float absoluteMaxStartValue; private float minValue; private float maxValue; private float minStartValue; private float maxStartValue; private float steps; private float gap; private float fixGap; private int mActivePointerId = INVALID_POINTER_ID; private int dataType; private float cornerRadius; private int barColor; private int barHighlightColor; private int leftThumbColor; private int rightThumbColor; private int leftThumbColorNormal; private int leftThumbColorPressed; private int rightThumbColorNormal; private int rightThumbColorPressed; private float barPadding; private float barHeight; private float thumbWidth; private float thumbDiameter; //private float thumbHalfWidth; //private float thumbHalfHeight; private float thumbHeight; private Drawable leftDrawable; private Drawable rightDrawable; private Drawable leftDrawablePressed; private Drawable rightDrawablePressed; private Bitmap leftThumb; private Bitmap leftThumbPressed; private Bitmap rightThumb; private Bitmap rightThumbPressed; private Thumb pressedThumb; private double normalizedMinValue = 0d; private double normalizedMaxValue = 100d; private int pointerIndex; private RectF _rect; private Paint _paint; private RectF rectLeftThumb, rectRightThumb; private boolean mIsDragging; public RangeSeekBar(Context context) { this(context, null); } ////////////////////////////////////////// // ENUMERATION ////////////////////////////////////////// public RangeSeekBar(Context context, AttributeSet attrs) { this(context, attrs, 0); } ////////////////////////////////////////// // CONSTRUCTOR ////////////////////////////////////////// public RangeSeekBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // prevent render is in edit mode if (isInEditMode()) return; TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RangeSeekBar); try { cornerRadius = getCornerRadius(array); minValue = getMinValue(array); maxValue = getMaxValue(array); minStartValue = getMinStartValue(array); maxStartValue = getMaxStartValue(array); steps = getSteps(array); gap = getGap(array); fixGap = getFixedGap(array); barColor = getBarColor(array); barHighlightColor = getBarHighlightColor(array); leftThumbColorNormal = getLeftThumbColor(array); rightThumbColorNormal = getRightThumbColor(array); leftThumbColorPressed = getLeftThumbColorPressed(array); rightThumbColorPressed = getRightThumbColorPressed(array); leftDrawable = getLeftDrawable(array); rightDrawable = getRightDrawable(array); leftDrawablePressed = getLeftDrawablePressed(array); rightDrawablePressed = getRightDrawablePressed(array); thumbDiameter = getDiameter(array); dataType = getDataType(array); } finally { array.recycle(); } init(); } protected void init() { absoluteMinValue = minValue; absoluteMaxValue = maxValue; leftThumbColor = leftThumbColorNormal; rightThumbColor = rightThumbColorNormal; leftThumb = getBitmap(leftDrawable); rightThumb = getBitmap(rightDrawable); leftThumbPressed = getBitmap(leftDrawablePressed); rightThumbPressed = getBitmap(rightDrawablePressed); leftThumbPressed = (leftThumbPressed == null) ? leftThumb : leftThumbPressed; rightThumbPressed = (rightThumbPressed == null) ? rightThumb : rightThumbPressed; gap = Math.max(0, Math.min(gap, absoluteMaxValue - absoluteMinValue)); gap = gap / (absoluteMaxValue - absoluteMinValue) * 100; if (fixGap != NO_FIXED_GAP) { fixGap = Math.min(fixGap, absoluteMaxValue); fixGap = fixGap / (absoluteMaxValue - absoluteMinValue) * 100; addFixGap(true); } thumbWidth = getThumbWidth(); thumbHeight = getThumbHeight(); //thumbHalfWidth = thumbWidth / 2; //thumbHalfHeight = thumbHeight / 2; barHeight = getBarHeight(); barPadding = getBarPadding(); _paint = new Paint(Paint.ANTI_ALIAS_FLAG); _rect = new RectF(); rectLeftThumb = new RectF(); rectRightThumb = new RectF(); pressedThumb = null; setMinStartValue(); setMaxStartValue(); setWillNotDraw(false); } public RangeSeekBar setCornerRadius(float cornerRadius) { this.cornerRadius = cornerRadius; return this; } ////////////////////////////////////////// // INITIALIZING ////////////////////////////////////////// public RangeSeekBar setMinValue(float minValue) { this.minValue = minValue; this.absoluteMinValue = minValue; return this; } ////////////////////////////////////////// // PUBLIC METHODS ////////////////////////////////////////// public RangeSeekBar setMaxValue(float maxValue) { this.maxValue = maxValue; this.absoluteMaxValue = maxValue; return this; } public RangeSeekBar setMinStartValue(float minStartValue) { this.minStartValue = minStartValue; this.absoluteMinStartValue = minStartValue; return this; } public RangeSeekBar setMaxStartValue(float maxStartValue) { this.maxStartValue = maxStartValue; this.absoluteMaxStartValue = maxStartValue; return this; } public RangeSeekBar setSteps(float steps) { this.steps = steps; return this; } public RangeSeekBar setGap(float gap) { this.gap = gap; return this; } public RangeSeekBar setFixGap(float fixGap) { this.fixGap = fixGap; return this; } public RangeSeekBar setBarColor(int barColor) { this.barColor = barColor; return this; } public RangeSeekBar setBarHighlightColor(int barHighlightColor) { this.barHighlightColor = barHighlightColor; return this; } public RangeSeekBar setLeftThumbColor(int leftThumbColorNormal) { this.leftThumbColorNormal = leftThumbColorNormal; return this; } public RangeSeekBar setLeftThumbHighlightColor(int leftThumbColorPressed) { this.leftThumbColorPressed = leftThumbColorPressed; return this; } public RangeSeekBar setLeftThumbDrawable(int resId) { setLeftThumbDrawable(ContextCompat.getDrawable(getContext(), resId)); return this; } public RangeSeekBar setLeftThumbDrawable(Drawable drawable) { setLeftThumbBitmap(getBitmap(drawable)); return this; } public RangeSeekBar setLeftThumbBitmap(Bitmap bitmap) { leftThumb = bitmap; return this; } public RangeSeekBar setLeftThumbHighlightDrawable(int resId) { setLeftThumbHighlightDrawable(ContextCompat.getDrawable(getContext(), resId)); return this; } public RangeSeekBar setLeftThumbHighlightDrawable(Drawable drawable) { setLeftThumbHighlightBitmap(getBitmap(drawable)); return this; } public RangeSeekBar setLeftThumbHighlightBitmap(Bitmap bitmap) { leftThumbPressed = bitmap; return this; } public RangeSeekBar setRightThumbColor(int rightThumbColorNormal) { this.rightThumbColorNormal = rightThumbColorNormal; return this; } public RangeSeekBar setRightThumbHighlightColor(int rightThumbColorPressed) { this.rightThumbColorPressed = rightThumbColorPressed; return this; } public RangeSeekBar setRightThumbDrawable(int resId) { setRightThumbDrawable(ContextCompat.getDrawable(getContext(), resId)); return this; } public RangeSeekBar setRightThumbDrawable(Drawable drawable) { setRightThumbBitmap(getBitmap(drawable)); return this; } public RangeSeekBar setRightThumbBitmap(Bitmap bitmap) { rightThumb = bitmap; return this; } public RangeSeekBar setRightThumbHighlightDrawable(int resId) { setRightThumbHighlightDrawable(ContextCompat.getDrawable(getContext(), resId)); return this; } public RangeSeekBar setRightThumbHighlightDrawable(Drawable drawable) { setRightThumbHighlightBitmap(getBitmap(drawable)); return this; } public RangeSeekBar setRightThumbHighlightBitmap(Bitmap bitmap) { rightThumbPressed = bitmap; return this; } public RangeSeekBar setDataType(int dataType) { this.dataType = dataType; return this; } public void setOnRangeSeekbarChangeListener(OnRangeSeekBarChangeListener onRangeSeekbarChangeListener) { this.onRangeSeekbarChangeListener = onRangeSeekbarChangeListener; if (this.onRangeSeekbarChangeListener != null) { this.onRangeSeekbarChangeListener.valueChanged(getSelectedMinValue(), getSelectedMaxValue()); } } public void setOnRangeSeekbarFinalValueListener(OnRangeSeekBarFinalValueListener onRangeSeekbarFinalValueListener) { this.onRangeSeekbarFinalValueListener = onRangeSeekbarFinalValueListener; } public Number getSelectedMinValue() { double nv = normalizedMinValue; if (steps > 0 && steps <= ((Math.abs(absoluteMaxValue)) / 2)) { float stp = steps / (absoluteMaxValue - absoluteMinValue) * 100; double half_step = stp / 2; double mod = nv % stp; if (mod > half_step) { nv = nv - mod; nv = nv + stp; } else { nv = nv - mod; } } else { if (steps != NO_STEP) throw new IllegalStateException("steps out of range " + steps); } return formatValue(normalizedToValue(nv)); } public Number getSelectedMaxValue() { double nv = normalizedMaxValue; if (steps > 0 && steps <= (Math.abs(absoluteMaxValue) / 2)) { float stp = steps / (absoluteMaxValue - absoluteMinValue) * 100; double half_step = stp / 2; double mod = nv % stp; if (mod > half_step) { nv = nv - mod; nv = nv + stp; } else { nv = nv - mod; } } else { if (steps != NO_STEP) throw new IllegalStateException("steps out of range " + steps); } return formatValue(normalizedToValue(nv)); } public void apply() { // reset normalize min and max value normalizedMinValue = 0d; normalizedMaxValue = 100d; gap = Math.max(0, Math.min(gap, absoluteMaxValue - absoluteMinValue)); gap = gap / (absoluteMaxValue - absoluteMinValue) * 100; if (fixGap != NO_FIXED_GAP) { fixGap = Math.min(fixGap, absoluteMaxValue); fixGap = fixGap / (absoluteMaxValue - absoluteMinValue) * 100; addFixGap(true); } thumbWidth = getThumbWidth(); thumbHeight = getThumbHeight(); //thumbHalfWidth = thumbWidth / 2; //thumbHalfHeight = thumbHeight / 2; barHeight = getBarHeight(); barPadding = thumbWidth * 0.5f; // set min start value if (minStartValue <= absoluteMinValue) { minStartValue = 0; setNormalizedMinValue(minStartValue); } else if (minStartValue >= absoluteMaxValue) { minStartValue = absoluteMaxValue; setMinStartValue(); } else { setMinStartValue(); } // set max start value if (maxStartValue < absoluteMinStartValue || maxStartValue <= absoluteMinValue) { maxStartValue = 0; setNormalizedMaxValue(maxStartValue); } else if (maxStartValue >= absoluteMaxValue) { maxStartValue = absoluteMaxValue; setMaxStartValue(); } else { setMaxStartValue(); } invalidate(); if (onRangeSeekbarChangeListener != null) { onRangeSeekbarChangeListener.valueChanged(getSelectedMinValue(), getSelectedMaxValue()); } } protected Thumb getPressedThumb() { return pressedThumb; } protected float getThumbWidth() { return (leftThumb != null) ? leftThumb.getWidth() : getThumbDiameter(); } ////////////////////////////////////////// // PROTECTED METHODS ////////////////////////////////////////// protected float getThumbHeight() { return (leftThumb != null) ? leftThumb.getHeight() : getThumbDiameter(); } protected float getThumbDiameter() { return (thumbDiameter > 0) ? thumbDiameter : getResources().getDimension(R.dimen.thumb_width); } protected float getBarHeight() { return (thumbHeight * 0.5f) * 0.3f; } protected float getBarPadding() { return thumbWidth * 0.5f; } protected Bitmap getBitmap(Drawable drawable) { return (drawable != null) ? ((BitmapDrawable) drawable).getBitmap() : null; } protected float getCornerRadius(final TypedArray typedArray) { return typedArray.getFloat(R.styleable.RangeSeekBar_corner_radius, 0f); } protected float getMinValue(final TypedArray typedArray) { return typedArray.getFloat(R.styleable.RangeSeekBar_min_value, 0f); } protected float getMaxValue(final TypedArray typedArray) { return typedArray.getFloat(R.styleable.RangeSeekBar_max_value, 100f); } protected float getMinStartValue(final TypedArray typedArray) { return typedArray.getFloat(R.styleable.RangeSeekBar_min_start_value, minValue); } protected float getMaxStartValue(final TypedArray typedArray) { return typedArray.getFloat(R.styleable.RangeSeekBar_max_start_value, maxValue); } protected float getSteps(final TypedArray typedArray) { return typedArray.getFloat(R.styleable.RangeSeekBar_steps, NO_STEP); } protected float getGap(final TypedArray typedArray) { return typedArray.getFloat(R.styleable.RangeSeekBar_gap, 0f); } protected float getFixedGap(final TypedArray typedArray) { return typedArray.getFloat(R.styleable.RangeSeekBar_fix_gap, NO_FIXED_GAP); } protected int getBarColor(final TypedArray typedArray) { return typedArray.getColor(R.styleable.RangeSeekBar_bar_color, Color.GRAY); } protected int getBarHighlightColor(final TypedArray typedArray) { return typedArray.getColor(R.styleable.RangeSeekBar_bar_highlight_color, Color.BLACK); } protected int getLeftThumbColor(final TypedArray typedArray) { return typedArray.getColor(R.styleable.RangeSeekBar_left_thumb_color, Color.BLACK); } protected int getRightThumbColor(final TypedArray typedArray) { return typedArray.getColor(R.styleable.RangeSeekBar_right_thumb_color, Color.BLACK); } protected int getLeftThumbColorPressed(final TypedArray typedArray) { return typedArray.getColor(R.styleable.RangeSeekBar_left_thumb_color_pressed, Color.DKGRAY); } protected int getRightThumbColorPressed(final TypedArray typedArray) { return typedArray.getColor(R.styleable.RangeSeekBar_right_thumb_color_pressed, Color.DKGRAY); } protected Drawable getLeftDrawable(final TypedArray typedArray) { return typedArray.getDrawable(R.styleable.RangeSeekBar_left_thumb_image); } protected Drawable getRightDrawable(final TypedArray typedArray) { return typedArray.getDrawable(R.styleable.RangeSeekBar_right_thumb_image); } protected Drawable getLeftDrawablePressed(final TypedArray typedArray) { return typedArray.getDrawable(R.styleable.RangeSeekBar_left_thumb_image_pressed); } protected Drawable getRightDrawablePressed(final TypedArray typedArray) { return typedArray.getDrawable(R.styleable.RangeSeekBar_right_thumb_image_pressed); } protected int getDataType(final TypedArray typedArray) { return typedArray.getInt(R.styleable.RangeSeekBar_data_type, DataType.INTEGER); } protected float getDiameter(final TypedArray typedArray) { return typedArray.getDimensionPixelSize(R.styleable.RangeSeekBar_thumb_diameter, getResources().getDimensionPixelSize(R.dimen.thumb_height)); } protected RectF getLeftThumbRect() { return rectLeftThumb; } protected RectF getRightThumbRect() { return rectRightThumb; } protected void setupBar(final Canvas canvas, final Paint paint, final RectF rect) { rect.left = barPadding; rect.top = 0.5f * (getHeight() - barHeight); rect.right = getWidth() - barPadding; rect.bottom = 0.5f * (getHeight() + barHeight); paint.setStyle(Paint.Style.FILL); paint.setColor(barColor); paint.setAntiAlias(true); drawBar(canvas, paint, rect); } protected void drawBar(final Canvas canvas, final Paint paint, final RectF rect) { canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint); } protected void setupHighlightBar(final Canvas canvas, final Paint paint, final RectF rect) { rect.left = normalizedToScreen(normalizedMinValue) + (getThumbWidth() / 2); rect.right = normalizedToScreen(normalizedMaxValue) + (getThumbWidth() / 2); paint.setColor(barHighlightColor); drawHighlightBar(canvas, paint, rect); } protected void drawHighlightBar(final Canvas canvas, final Paint paint, final RectF rect) { canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint); } protected void setupLeftThumb(final Canvas canvas, final Paint paint, final RectF rect) { leftThumbColor = (Thumb.MIN.equals(pressedThumb)) ? leftThumbColorPressed : leftThumbColorNormal; paint.setColor(leftThumbColor); //float leftL = normalizedToScreen(normalizedMinValue); //float rightL = Math.min(leftL + thumbHalfWidth + barPadding, getWidth()); rectLeftThumb.left = normalizedToScreen(normalizedMinValue); rectLeftThumb.right = Math.min(rectLeftThumb.left + (getThumbWidth() / 2) + barPadding, getWidth()); rectLeftThumb.top = 0f; rectLeftThumb.bottom = thumbHeight; if (leftThumb != null) { Bitmap lThumb = (Thumb.MIN.equals(pressedThumb)) ? leftThumbPressed : leftThumb; drawLeftThumbWithImage(canvas, paint, rectLeftThumb, lThumb); } else { drawLeftThumbWithColor(canvas, paint, rectLeftThumb); } } protected void drawLeftThumbWithColor(final Canvas canvas, final Paint paint, final RectF rect) { canvas.drawOval(rect, paint); } protected void drawLeftThumbWithImage(final Canvas canvas, final Paint paint, final RectF rect, final Bitmap image) { canvas.drawBitmap(image, rect.left, rect.top, paint); } protected void setupRightThumb(final Canvas canvas, final Paint paint, final RectF rect) { rightThumbColor = (Thumb.MAX.equals(pressedThumb)) ? rightThumbColorPressed : rightThumbColorNormal; paint.setColor(rightThumbColor); //float leftR = normalizedToScreen(normalizedMaxValue); //float rightR = Math.min(leftR + thumbHalfWidth + barPadding, getWidth()); rectRightThumb.left = normalizedToScreen(normalizedMaxValue); rectRightThumb.right = Math.min(rectRightThumb.left + (getThumbWidth() / 2) + barPadding, getWidth()); rectRightThumb.top = 0f; rectRightThumb.bottom = thumbHeight; if (rightThumb != null) { Bitmap rThumb = (Thumb.MAX.equals(pressedThumb)) ? rightThumbPressed : rightThumb; drawRightThumbWithImage(canvas, paint, rectRightThumb, rThumb); } else { drawRightThumbWithColor(canvas, paint, rectRightThumb); } } protected void drawRightThumbWithColor(final Canvas canvas, final Paint paint, final RectF rect) { canvas.drawOval(rect, paint); } protected void drawRightThumbWithImage(final Canvas canvas, final Paint paint, final RectF rect, final Bitmap image) { canvas.drawBitmap(image, rect.left, rect.top, paint); } protected void trackTouchEvent(MotionEvent event) { final int pointerIndex = event.findPointerIndex(mActivePointerId); try { final float x = event.getX(pointerIndex); if (Thumb.MIN.equals(pressedThumb)) { setNormalizedMinValue(screenToNormalized(x)); } else if (Thumb.MAX.equals(pressedThumb)) { setNormalizedMaxValue(screenToNormalized(x)); } } catch (Exception ignored) { } } protected void touchDown(final float x, final float y) { } protected void touchMove(final float x, final float y) { } protected void touchUp(final float x, final float y) { } protected int getMeasureSpecWith(int widthMeasureSpec) { int width = 200; if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(widthMeasureSpec)) { width = MeasureSpec.getSize(widthMeasureSpec); } return width; } protected int getMeasureSpecHeight(int heightMeasureSpec) { int height = Math.round(thumbHeight); if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(heightMeasureSpec)) { height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec)); } return height; } protected final void log(Object object) { Log.d("CRS=>", String.valueOf(object)); } private void setMinStartValue() { if (minStartValue > minValue && minStartValue <= maxValue) { minStartValue = Math.min(minStartValue, absoluteMaxValue); minStartValue -= absoluteMinValue; minStartValue = minStartValue / (absoluteMaxValue - absoluteMinValue) * 100; setNormalizedMinValue(minStartValue); } } private void setMaxStartValue() { if (maxStartValue <= absoluteMaxValue && maxStartValue > absoluteMinValue && maxStartValue >= absoluteMinStartValue) { maxStartValue = Math.max(absoluteMaxStartValue, absoluteMinValue); maxStartValue -= absoluteMinValue; maxStartValue = maxStartValue / (absoluteMaxValue - absoluteMinValue) * 100; setNormalizedMaxValue(maxStartValue); } } ////////////////////////////////////////// // PRIVATE METHODS ////////////////////////////////////////// private Thumb evalPressedThumb(float touchX) { Thumb result = null; boolean minThumbPressed = isInThumbRange(touchX, normalizedMinValue); boolean maxThumbPressed = isInThumbRange(touchX, normalizedMaxValue); if (minThumbPressed && maxThumbPressed) { // if both thumbs are pressed (they lie on top of each other), choose the one with more room to drag. this avoids "stalling" the thumbs in a corner, not being able to drag them apart anymore. result = (touchX / getWidth() > 0.5f) ? Thumb.MIN : Thumb.MAX; } else if (minThumbPressed) { result = Thumb.MIN; } else if (maxThumbPressed) { result = Thumb.MAX; } return result; } private boolean isInThumbRange(float touchX, double normalizedThumbValue) { float thumbPos = normalizedToScreen(normalizedThumbValue); float left = thumbPos - (getThumbWidth() / 2); float right = thumbPos + (getThumbWidth() / 2); float x = touchX - (getThumbWidth() / 2); if (thumbPos > (getWidth() - thumbWidth)) x = touchX; return (x >= left && x <= right); //return Math.abs(touchX - normalizedToScreen(normalizedThumbValue)) <= thumbWidth; } private void onStartTrackingTouch() { mIsDragging = true; } private void onStopTrackingTouch() { mIsDragging = false; } private float normalizedToScreen(double normalizedCoord) { float width = getWidth() - (barPadding * 2); return (float) normalizedCoord / 100f * width; } private double screenToNormalized(float screenCoord) { double width = getWidth(); if (width <= 2 * barPadding) { // prevent division by zero, simply return 0. return 0d; } else { width = width - (barPadding * 2); double result = screenCoord / width * 100d; result = result - (barPadding / width * 100d); result = Math.min(100d, Math.max(0d, result)); return result; } } private void setNormalizedMinValue(double value) { normalizedMinValue = Math.max(0d, Math.min(100d, Math.min(value, normalizedMaxValue))); if (fixGap != NO_FIXED_GAP && fixGap > 0) { addFixGap(true); } else { addMinGap(); } invalidate(); } private void setNormalizedMaxValue(double value) { normalizedMaxValue = Math.max(0d, Math.min(100d, Math.max(value, normalizedMinValue))); if (fixGap != NO_FIXED_GAP && fixGap > 0) { addFixGap(false); } else { addMaxGap(); } invalidate(); } private void addFixGap(boolean leftThumb) { if (leftThumb) { normalizedMaxValue = normalizedMinValue + fixGap; if (normalizedMaxValue >= 100) { normalizedMaxValue = 100; normalizedMinValue = normalizedMaxValue - fixGap; } } else { normalizedMinValue = normalizedMaxValue - fixGap; if (normalizedMinValue <= 0) { normalizedMinValue = 0; normalizedMaxValue = normalizedMinValue + fixGap; } } } private void addMinGap() { if ((normalizedMinValue + gap) > normalizedMaxValue) { double g = normalizedMinValue + gap; normalizedMaxValue = g; normalizedMaxValue = Math.max(0d, Math.min(100d, Math.max(g, normalizedMinValue))); if (normalizedMinValue >= (normalizedMaxValue - gap)) { normalizedMinValue = normalizedMaxValue - gap; } } } private void addMaxGap() { if ((normalizedMaxValue - gap) < normalizedMinValue) { double g = normalizedMaxValue - gap; normalizedMinValue = g; normalizedMinValue = Math.max(0d, Math.min(100d, Math.min(g, normalizedMaxValue))); if (normalizedMaxValue <= (normalizedMinValue + gap)) { normalizedMaxValue = normalizedMinValue + gap; } } } private double normalizedToValue(double normalized) { double val = normalized / 100 * (maxValue - minValue); val = val + minValue; return val; } private void attemptClaimDrag() { if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(true); } } private <T extends Number> Number formatValue(T value) throws IllegalArgumentException { final Double v = (Double) value; if (dataType == DataType.LONG) { return v.longValue(); } if (dataType == DataType.DOUBLE) { return v; } if (dataType == DataType.INTEGER) { return Math.round(v); } if (dataType == DataType.FLOAT) { return v.floatValue(); } if (dataType == DataType.SHORT) { return v.shortValue(); } if (dataType == DataType.BYTE) { return v.byteValue(); } throw new IllegalArgumentException("Number class '" + value.getClass().getName() + "' is not supported"); } @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); // prevent render is in edit mode if (isInEditMode()) return; // setup bar setupBar(canvas, _paint, _rect); // setup seek bar active range line setupHighlightBar(canvas, _paint, _rect); // draw left thumb setupLeftThumb(canvas, _paint, _rect); // draw right thumb setupRightThumb(canvas, _paint, _rect); } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getMeasureSpecWith(widthMeasureSpec), getMeasureSpecHeight(heightMeasureSpec)); } ////////////////////////////////////////// // OVERRIDE METHODS ////////////////////////////////////////// /** * Handles thumb selection and movement. Notifies listener callback on certain events. */ @Override public synchronized boolean onTouchEvent(MotionEvent event) { if (!isEnabled()) return false; final int action = event.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: mActivePointerId = event.getPointerId(event.getPointerCount() - 1); pointerIndex = event.findPointerIndex(mActivePointerId); float mDownMotionX = event.getX(pointerIndex); pressedThumb = evalPressedThumb(mDownMotionX); if (pressedThumb == null) return super.onTouchEvent(event); touchDown(event.getX(pointerIndex), event.getY(pointerIndex)); setPressed(true); invalidate(); onStartTrackingTouch(); trackTouchEvent(event); attemptClaimDrag(); break; case MotionEvent.ACTION_MOVE: if (pressedThumb != null) { if (mIsDragging) { touchMove(event.getX(pointerIndex), event.getY(pointerIndex)); trackTouchEvent(event); } if (onRangeSeekbarChangeListener != null) { onRangeSeekbarChangeListener.valueChanged(getSelectedMinValue(), getSelectedMaxValue()); } } break; case MotionEvent.ACTION_UP: if (mIsDragging) { trackTouchEvent(event); onStopTrackingTouch(); setPressed(false); touchUp(event.getX(pointerIndex), event.getY(pointerIndex)); if (onRangeSeekbarFinalValueListener != null) { onRangeSeekbarFinalValueListener.finalValue(getSelectedMinValue(), getSelectedMaxValue()); } } else { // Touch up when we never crossed the touch slop threshold // should be interpreted as a tap-seek to that location. onStartTrackingTouch(); trackTouchEvent(event); onStopTrackingTouch(); } pressedThumb = null; invalidate(); if (onRangeSeekbarChangeListener != null) { onRangeSeekbarChangeListener.valueChanged(getSelectedMinValue(), getSelectedMaxValue()); } break; case MotionEvent.ACTION_POINTER_DOWN: { //final int index = event.getPointerCount() - 1; // final int index = ev.getActionIndex(); /*mDownMotionX = event.getX(index); mActivePointerId = event.getPointerId(index); invalidate();*/ break; } case MotionEvent.ACTION_POINTER_UP: /*onSecondaryPointerUp(event);*/ invalidate(); break; case MotionEvent.ACTION_CANCEL: if (mIsDragging) { onStopTrackingTouch(); setPressed(false); touchUp(event.getX(pointerIndex), event.getY(pointerIndex)); } invalidate(); // see above explanation break; } return true; } protected enum Thumb {MIN, MAX} public static final class DataType { public static final int LONG = 0; public static final int DOUBLE = 1; public static final int INTEGER = 2; public static final int FLOAT = 3; public static final int SHORT = 4; public static final int BYTE = 5; } }
4768fc5d66db0815222507259431fa8148976160
456d43c584fb66f65c6a7147cdd22595facf8bd9
/jpa/deferred/src/main/java/example/model/Customer1490.java
ed857a1f42e614f7c34c7b8dc473b1be6a80f961
[ "Apache-2.0" ]
permissive
niushapaks/spring-data-examples
283eec991014e909981055f48efe67ff1e6e19e6
1ad228b04523e958236d58ded302246bba3c1e9b
refs/heads/main
2023-08-21T14:25:55.998574
2021-09-29T13:14:33
2021-09-29T13:14:33
411,679,335
1
0
Apache-2.0
2021-09-29T13:11:03
2021-09-29T13:11:02
null
UTF-8
Java
false
false
628
java
package example.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Customer1490 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1490() {} public Customer1490(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1490[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } }
16394b684e0573c1d685509a8b383c4651791315
407d1b7bbf02ea7a9926cdf550483beaa33b7695
/transpiler/javatests/com/google/j2cl/integration/testing/AssertsBase.java
5bb5728193293642cbe8d2b872e947b9057c45e0
[ "LicenseRef-scancode-unknown-license-reference", "Zlib", "SunPro", "EPL-1.0", "BSD-3-Clause", "Apache-2.0", "BSD-2-Clause" ]
permissive
google/j2cl
7d92a24dbf019c44b7bbbc5971cd9ff24640b72b
afa547faa2a369d74c3bc7ae24bc84a2f47fc716
refs/heads/master
2023-08-31T03:32:50.930089
2023-08-30T18:25:52
2023-08-30T18:27:11
94,876,336
1,155
145
Apache-2.0
2023-07-17T09:39:41
2017-06-20T09:53:52
Java
UTF-8
Java
false
false
3,602
java
/* * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.j2cl.integration.testing; import static com.google.j2cl.integration.testing.TestUtils.isJvm; import com.google.j2cl.integration.testing.Asserts.JsRunnable; /** * This class introduces an indirection for assertThrows methods so we can super source them and * make them noop for Wasm. */ public class AssertsBase { public static void fail() { throw new AssertionError(); } public static void fail(String message) { throw new AssertionError(message); } public static void assertTrue(boolean condition) { if (!condition) { fail(); } } public static void assertTrue(String message, boolean condition) { if (!condition) { fail(message); } } // DO NOT INTRODUCE a helper from a Supplier, since the implicit return in the lambda might // introduce casts and autoboxing. The whole purpose of this assert helper is to make sure that // the code written by the user does not omit casts. public static void assertThrowsClassCastException(JsRunnable runnable) { assertThrowsClassCastException(runnable, (String) null); } public static void assertThrowsClassCastException( JsRunnable runnable, String qualifiedBinaryName) { // If compiler inlines this method and if the cast checking is disabled for size testing (which // is the default), then it will remove everything afterwards and result inaccurate size // tracking. // This statement will never be true, but the compiler is unable to determine that statically. if (Math.random() > 1) { return; } try { runnable.run(); fail("Should have thrown ClassCastException"); } catch (ClassCastException expected) { if (qualifiedBinaryName != null) { String message = expected.getMessage(); String expectedMessage = isJvm() ? "cannot be cast to class " : "cannot be cast to "; expectedMessage += qualifiedBinaryName; assertTrue( getFailureMessage(expectedMessage, message, "exception message should contain"), message.contains(expectedMessage)); } } } public static void assertThrowsClassCastException(JsRunnable runnable, Class<?> toClass) { assertThrowsClassCastException(runnable, toClass.getName()); } public static void assertThrowsNullPointerException(JsRunnable runnable) { assertThrows(NullPointerException.class, runnable); } public static void assertThrows(Class<? extends Exception> exceptionClass, JsRunnable runnable) { try { runnable.run(); } catch (Throwable e) { if (e.getClass() == exceptionClass) { return; } } fail("Should have thrown " + exceptionClass); } static String getFailureMessage(Object expected, Object actual, String msg) { String expectedString = expected == null ? null : expected.toString(); String actualString = actual == null ? null : actual.toString(); return "<" + actualString + "> " + msg + " <" + expectedString + ">"; } }
90033a0417548c46603cd86d7fb8eacd5da96929
d7c34039bee019140ac6faae0b50d9ba939815e8
/src/main/java/server/ChatServer.java
4767727d0536f3f303d5e107c04787d6a0c2fac2
[]
no_license
Tomerhek/chat
1d23758359d87d05544f698c85b676354f18881d
e5442c14c67d01fbe1238a06d0abe4605d8386af
refs/heads/master
2020-04-23T17:35:27.778070
2019-04-27T18:34:54
2019-04-27T18:34:54
171,336,884
0
0
null
null
null
null
UTF-8
Java
false
false
2,515
java
package server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; import java.util.Set; /** * This is the chat server program. * Press Ctrl + C to terminate the program. * * @author www.codejava.net */ public class ChatServer { public int port; private Set<String> userNames = new HashSet<>(); private Set<UserThread> userThreads = new HashSet<>(); public ChatServer(int port) { this.port = port; } public void execute() { try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Chat Server is listening on port " + port); while (true) { Socket socket = serverSocket.accept(); System.out.println("New user connected"); UserThread newUser = new UserThread(socket, this); userThreads.add(newUser); newUser.start(); } } catch (IOException ex) { System.out.println("Error in the server: " + ex.getMessage()); ex.printStackTrace(); } } public static void main(String[] args) { if (args.length < 1) { System.out.println("Syntax: java ChatServer <port-number>"); System.exit(0); } int port = Integer.parseInt(args[0]); ChatServer server = new ChatServer(port); server.execute(); } /** * Delivers a message from one user to others (broadcasting) */ void broadcast(String message, UserThread excludeUser) { for (UserThread aUser : userThreads) { if (aUser != excludeUser) { aUser.sendMessage(message); } } } /** * Stores username of the newly connected client. */ void addUserName(String userName) { userNames.add(userName); } /** * When a client is disconneted, removes the associated username and UserThread */ void removeUser(String userName, UserThread aUser) { boolean removed = userNames.remove(userName); if (removed) { userThreads.remove(aUser); System.out.println("The user " + userName + " quitted"); } } Set<String> getUserNames() { return this.userNames; } /** * Returns true if there are other users connected (not count the currently connected user) */ boolean hasUsers() { return !this.userNames.isEmpty(); } }
df175462406f4898881e1efa9d78a3828730b5d3
4519b5e0f57ad9b5b99087271b152042f292eb48
/shadowsocks-demon/shadowsocks-test/src/main/java/com/nihao001/helloworld/cipher/CryptFactory.java
15532ca4eb5b2484ed130c733023d2aa1562b163
[]
no_license
RokeAbbey-chen/java-workspace1
ddbf5d4f25fcc287ea39bf387a380e72364df5b8
10c849867c09d9bbc7174114abbdb143e2261d23
refs/heads/master
2020-05-17T23:13:02.899753
2019-04-29T07:43:56
2019-04-29T07:43:56
184,024,041
0
0
null
null
null
null
UTF-8
Java
false
false
2,775
java
/* * Copyright (c) 2015, Blake * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.nihao001.helloworld.cipher; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; /** * Crypt factory */ public class CryptFactory { private static final Map<String, String> crypts = new HashMap<String, String>() {{ putAll(AesCrypt.getCiphers()); putAll(CamelliaCrypt.getCiphers()); putAll(BlowFishCrypt.getCiphers()); putAll(SeedCrypt.getCiphers()); // TODO: other crypts }}; private static Logger logger = Logger.getLogger(CryptFactory.class.getName()); public static boolean isCipherExisted(String name) { return (crypts.get(name) != null); } public static ICrypt get(String name, String password) { try { Object obj = Reflection.get(crypts.get(name), String.class, name, String.class, password); return (ICrypt)obj; } catch (Exception e) { logger.info(Util.getErrorMessage(e)); } return null; } public static List<String> getSupportedCiphers() { List sortedKeys = new ArrayList<>(crypts.keySet()); Collections.sort(sortedKeys); return sortedKeys; } }
64377b1a6c2db18ee894450c91b1ca2369024361
c7b722e92445c1956c467b13cb1fb7b284585b04
/Android/app/src/main/java/database/UsersOnDeviceDao.java
9708c7214e3d612fa400c8d2a883ebe93e6cfb60
[]
no_license
EmadNaguiDarwish/team_zero_application
4a704446274d20e5a543971578fc84d60e73a649
346c2b1bc17ba1fe0365748fe34ba2c71ec1e5ff
refs/heads/master
2020-08-27T05:35:30.695877
2020-02-13T10:56:15
2020-02-13T10:56:15
217,257,776
0
0
null
2020-01-18T21:24:13
2019-10-24T09:08:37
JavaScript
UTF-8
Java
false
false
756
java
package database; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import java.util.List; // Interface for the CRUD operations on UsersOnDevice table @Dao public interface UsersOnDeviceDao { @Query("SELECT * FROM usersondevice") List<UsersOnDevice> getAllUsersOnDevice(); @Query("DELETE FROM usersondevice WHERE username LIKE :username") void deleteUserFromDevice(String username); @Insert void insert(UsersOnDevice usersOnDevice); @Delete void delete(UsersOnDevice usersOnDevice); @Update void update(UsersOnDevice usersOnDevice); }
45657f8e24427a068509fb34e99e6cd5b4d5539f
66c6898d2ce2f6cc7f89cde60fb6a4426559dc10
/vimeo-networking/build/generated/source/apt/main/com/vimeo/stag/generated/ParseUtils.java
1055c7e16ec211fbe3e80beeb40c83ca37976bcd
[]
no_license
zainincubasys/Gotha_Dubai
b1cd56a0bc45ea5425ecf8c6a46f7bc70632e6cd
3dcb7bc11493bea78e64fd35c41b1eafcf1a2fb5
refs/heads/master
2021-04-29T11:16:20.659063
2017-05-10T12:23:40
2017-05-10T12:23:40
77,821,950
1
0
null
null
null
null
UTF-8
Java
false
false
162,238
java
package com.vimeo.stag.generated; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.vimeo.networking.model.Category; import com.vimeo.networking.model.CategoryList; import com.vimeo.networking.model.Channel; import com.vimeo.networking.model.ChannelList; import com.vimeo.networking.model.Comment; import com.vimeo.networking.model.CommentList; import com.vimeo.networking.model.Connection; import com.vimeo.networking.model.ConnectionCollection; import com.vimeo.networking.model.Email; import com.vimeo.networking.model.Embed; import com.vimeo.networking.model.FeedItem; import com.vimeo.networking.model.FeedList; import com.vimeo.networking.model.Group; import com.vimeo.networking.model.Interaction; import com.vimeo.networking.model.InteractionCollection; import com.vimeo.networking.model.Metadata; import com.vimeo.networking.model.Paging; import com.vimeo.networking.model.Picture; import com.vimeo.networking.model.PictureCollection; import com.vimeo.networking.model.PictureResource; import com.vimeo.networking.model.PinCodeInfo; import com.vimeo.networking.model.Preferences; import com.vimeo.networking.model.Privacy; import com.vimeo.networking.model.Quota; import com.vimeo.networking.model.Recommendation; import com.vimeo.networking.model.Space; import com.vimeo.networking.model.StatsCollection; import com.vimeo.networking.model.Tag; import com.vimeo.networking.model.UploadQuota; import com.vimeo.networking.model.User; import com.vimeo.networking.model.UserBadge; import com.vimeo.networking.model.UserList; import com.vimeo.networking.model.Video; import com.vimeo.networking.model.VideoFile; import com.vimeo.networking.model.VideoList; import com.vimeo.networking.model.VideosPreference; import com.vimeo.networking.model.VimeoAccount; import com.vimeo.networking.model.VodItem; import com.vimeo.networking.model.VodList; import com.vimeo.networking.model.Website; import com.vimeo.networking.model.playback.Drm; import com.vimeo.networking.model.playback.Play; import com.vimeo.networking.model.playback.PlayProgress; import com.vimeo.networking.model.playback.VideoLog; import com.vimeo.networking.model.search.FacetOption; import com.vimeo.networking.model.search.SearchFacet; import com.vimeo.networking.model.search.SearchFacetCollection; import com.vimeo.networking.model.search.SearchResponse; import com.vimeo.networking.model.search.SearchResult; import java.io.IOException; import java.lang.Class; import java.util.ArrayList; final class ParseUtils { public static <T> ArrayList<T> parseArray(Gson gson, JsonReader reader, Class<T> clazz) throws IOException { if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_ARRAY) { reader.skipValue(); return null; } reader.beginArray(); ArrayList<T> list = Stag.readListFromAdapter(gson, clazz, reader); reader.endArray(); return list; } public static <T> void write(Gson gson, JsonWriter writer, Class clazz, ArrayList<T> list) throws IOException { if (list == null) { return; } writer.beginArray(); Stag.writeListToAdapter(gson, clazz, writer, list); writer.endArray(); } public static void write(Gson gson, JsonWriter writer, Channel object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.modifiedTime != null) { writer.name("modified_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.modifiedTime); } if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.metadata != null) { writer.name("metadata"); ParseUtils.write(gson, writer, object.metadata); } if (object.createdTime != null) { writer.name("created_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.createdTime); } if (object.user != null) { writer.name("user"); ParseUtils.write(gson, writer, object.user); } if (object.header != null) { writer.name("header"); ParseUtils.write(gson, writer, object.header); } if (object.link != null) { writer.name("link"); writer.value(object.link); } if (object.privacy != null) { writer.name("privacy"); ParseUtils.write(gson, writer, object.privacy); } if (object.name != null) { writer.name("name"); writer.value(object.name); } if (object.pictures != null) { writer.name("pictures"); ParseUtils.write(gson, writer, object.pictures); } if (object.description != null) { writer.name("description"); writer.value(object.description); } } writer.endObject(); } public static Channel parseChannel(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Channel object = new com.vimeo.networking.model.Channel(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "modified_time": try { object.modifiedTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Channel.modifiedTime JSON!", exception); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "metadata": try { object.metadata = ParseUtils.parseMetadata(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Channel.metadata JSON!", exception); } break; case "created_time": try { object.createdTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Channel.createdTime JSON!", exception); } break; case "user": try { object.user = ParseUtils.parseUser(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Channel.user JSON!", exception); } break; case "header": try { object.header = ParseUtils.parsePictureCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Channel.header JSON!", exception); } break; case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.link = reader.nextString(); } else { reader.skipValue(); } break; case "privacy": try { object.privacy = ParseUtils.parsePrivacy(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Channel.privacy JSON!", exception); } break; case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.name = reader.nextString(); } else { reader.skipValue(); } break; case "pictures": try { object.pictures = ParseUtils.parsePictureCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Channel.pictures JSON!", exception); } break; case "description": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.description = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, StatsCollection object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.plays != null) { writer.name("plays"); Stag.writeToAdapter(gson, java.lang.Integer.class, writer, object.plays); } } writer.endObject(); } public static StatsCollection parseStatsCollection(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.StatsCollection object = new com.vimeo.networking.model.StatsCollection(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "plays": try { object.plays = Stag.readFromAdapter(gson, java.lang.Integer.class, reader); } catch(Exception exception) { throw new IOException("Error parsing StatsCollection.plays JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, CategoryList object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("total"); writer.value(object.total); writer.name("per_page"); writer.value(object.perPage); writer.name("page"); writer.value(object.page); if (object.data != null) { writer.name("data"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Category.class, object.data); } if (object.paging != null) { writer.name("paging"); ParseUtils.write(gson, writer, object.paging); } } writer.endObject(); } public static CategoryList parseCategoryList(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.CategoryList object = new com.vimeo.networking.model.CategoryList(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.total = reader.nextInt(); } else { reader.skipValue(); } break; case "per_page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.perPage = reader.nextInt(); } else { reader.skipValue(); } break; case "page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.page = reader.nextInt(); } else { reader.skipValue(); } break; case "data": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.data = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Category.class); } else { reader.skipValue(); } break; case "paging": try { object.paging = ParseUtils.parsePaging(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing CategoryList.paging JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, ConnectionCollection object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.appearances != null) { writer.name("appearances"); ParseUtils.write(gson, writer, object.appearances); } if (object.trailer != null) { writer.name("trailer"); ParseUtils.write(gson, writer, object.trailer); } if (object.ondemand != null) { writer.name("ondemand"); ParseUtils.write(gson, writer, object.ondemand); } if (object.videos != null) { writer.name("videos"); ParseUtils.write(gson, writer, object.videos); } if (object.feed != null) { writer.name("feed"); ParseUtils.write(gson, writer, object.feed); } if (object.credits != null) { writer.name("credits"); ParseUtils.write(gson, writer, object.credits); } if (object.shared != null) { writer.name("shared"); ParseUtils.write(gson, writer, object.shared); } if (object.categories != null) { writer.name("categories"); ParseUtils.write(gson, writer, object.categories); } if (object.recommendations != null) { writer.name("recommendations"); ParseUtils.write(gson, writer, object.recommendations); } if (object.recommendedUsers != null) { writer.name("recommended_users"); ParseUtils.write(gson, writer, object.recommendedUsers); } if (object.replies != null) { writer.name("replies"); ParseUtils.write(gson, writer, object.replies); } if (object.comments != null) { writer.name("comments"); ParseUtils.write(gson, writer, object.comments); } if (object.groups != null) { writer.name("groups"); ParseUtils.write(gson, writer, object.groups); } if (object.watchlater != null) { writer.name("watchlater"); ParseUtils.write(gson, writer, object.watchlater); } if (object.texttracks != null) { writer.name("texttracks"); ParseUtils.write(gson, writer, object.texttracks); } if (object.likes != null) { writer.name("likes"); ParseUtils.write(gson, writer, object.likes); } if (object.activities != null) { writer.name("activities"); ParseUtils.write(gson, writer, object.activities); } if (object.moderatedChannels != null) { writer.name("moderated_channels"); ParseUtils.write(gson, writer, object.moderatedChannels); } if (object.related != null) { writer.name("related"); ParseUtils.write(gson, writer, object.related); } if (object.users != null) { writer.name("users"); ParseUtils.write(gson, writer, object.users); } if (object.following != null) { writer.name("following"); ParseUtils.write(gson, writer, object.following); } if (object.pictures != null) { writer.name("pictures"); ParseUtils.write(gson, writer, object.pictures); } if (object.followers != null) { writer.name("followers"); ParseUtils.write(gson, writer, object.followers); } if (object.albums != null) { writer.name("albums"); ParseUtils.write(gson, writer, object.albums); } if (object.channels != null) { writer.name("channels"); ParseUtils.write(gson, writer, object.channels); } if (object.playbackFailureReason != null) { writer.name("playback"); ParseUtils.write(gson, writer, object.playbackFailureReason); } if (object.recommendedChannels != null) { writer.name("recommended_channels"); ParseUtils.write(gson, writer, object.recommendedChannels); } if (object.portfolios != null) { writer.name("portfolios"); ParseUtils.write(gson, writer, object.portfolios); } } writer.endObject(); } public static ConnectionCollection parseConnectionCollection(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.ConnectionCollection object = new com.vimeo.networking.model.ConnectionCollection(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "appearances": try { object.appearances = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.appearances JSON!", exception); } break; case "trailer": try { object.trailer = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.trailer JSON!", exception); } break; case "ondemand": try { object.ondemand = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.ondemand JSON!", exception); } break; case "videos": try { object.videos = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.videos JSON!", exception); } break; case "feed": try { object.feed = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.feed JSON!", exception); } break; case "credits": try { object.credits = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.credits JSON!", exception); } break; case "shared": try { object.shared = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.shared JSON!", exception); } break; case "categories": try { object.categories = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.categories JSON!", exception); } break; case "recommendations": try { object.recommendations = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.recommendations JSON!", exception); } break; case "recommended_users": try { object.recommendedUsers = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.recommendedUsers JSON!", exception); } break; case "replies": try { object.replies = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.replies JSON!", exception); } break; case "comments": try { object.comments = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.comments JSON!", exception); } break; case "groups": try { object.groups = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.groups JSON!", exception); } break; case "watchlater": try { object.watchlater = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.watchlater JSON!", exception); } break; case "texttracks": try { object.texttracks = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.texttracks JSON!", exception); } break; case "likes": try { object.likes = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.likes JSON!", exception); } break; case "activities": try { object.activities = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.activities JSON!", exception); } break; case "moderated_channels": try { object.moderatedChannels = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.moderatedChannels JSON!", exception); } break; case "related": try { object.related = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.related JSON!", exception); } break; case "users": try { object.users = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.users JSON!", exception); } break; case "following": try { object.following = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.following JSON!", exception); } break; case "pictures": try { object.pictures = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.pictures JSON!", exception); } break; case "followers": try { object.followers = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.followers JSON!", exception); } break; case "albums": try { object.albums = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.albums JSON!", exception); } break; case "channels": try { object.channels = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.channels JSON!", exception); } break; case "playback": try { object.playbackFailureReason = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.playbackFailureReason JSON!", exception); } break; case "recommended_channels": try { object.recommendedChannels = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.recommendedChannels JSON!", exception); } break; case "portfolios": try { object.portfolios = ParseUtils.parseConnection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ConnectionCollection.portfolios JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, VideoFile object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.token != null) { writer.name("token"); writer.value(object.token); } writer.name("size"); writer.value(object.size); if (object.linkExpirationTime != null) { writer.name("link_expiration_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.linkExpirationTime); } writer.name("fps"); writer.value(object.fps); writer.name("height"); writer.value(object.height); if (object.quality != null) { writer.name("quality"); Stag.writeToAdapter(gson, com.vimeo.networking.model.VideoFile.VideoQuality.class, writer, object.quality); } if (object.link != null) { writer.name("link"); writer.value(object.link); } if (object.licenseLink != null) { writer.name("license_link"); writer.value(object.licenseLink); } writer.name("width"); writer.value(object.width); if (object.md5 != null) { writer.name("md5"); writer.value(object.md5); } if (object.log != null) { writer.name("log"); ParseUtils.write(gson, writer, object.log); } if (object.createdTime != null) { writer.name("created_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.createdTime); } if (object.type != null) { writer.name("type"); Stag.writeToAdapter(gson, com.vimeo.networking.model.VideoFile.MimeType.class, writer, object.type); } if (object.expires != null) { writer.name("expires"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.expires); } } writer.endObject(); } public static VideoFile parseVideoFile(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.VideoFile object = new com.vimeo.networking.model.VideoFile(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "token": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.token = reader.nextString(); } else { reader.skipValue(); } break; case "size": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.size = reader.nextLong(); } else { reader.skipValue(); } break; case "link_expiration_time": try { object.linkExpirationTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing VideoFile.linkExpirationTime JSON!", exception); } break; case "fps": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.fps = reader.nextDouble(); } else { reader.skipValue(); } break; case "height": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.height = reader.nextInt(); } else { reader.skipValue(); } break; case "quality": try { object.quality = Stag.readFromAdapter(gson, com.vimeo.networking.model.VideoFile.VideoQuality.class, reader); } catch(Exception exception) { throw new IOException("Error parsing VideoFile.quality JSON!", exception); } break; case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.link = reader.nextString(); } else { reader.skipValue(); } break; case "license_link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.licenseLink = reader.nextString(); } else { reader.skipValue(); } break; case "width": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.width = reader.nextInt(); } else { reader.skipValue(); } break; case "md5": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.md5 = reader.nextString(); } else { reader.skipValue(); } break; case "log": try { object.log = ParseUtils.parseVideoLog(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VideoFile.log JSON!", exception); } break; case "created_time": try { object.createdTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing VideoFile.createdTime JSON!", exception); } break; case "type": try { object.type = Stag.readFromAdapter(gson, com.vimeo.networking.model.VideoFile.MimeType.class, reader); } catch(Exception exception) { throw new IOException("Error parsing VideoFile.type JSON!", exception); } break; case "expires": try { object.expires = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing VideoFile.expires JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Space object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("free"); writer.value(object.free); writer.name("used"); writer.value(object.used); writer.name("max"); writer.value(object.max); } writer.endObject(); } public static Space parseSpace(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Space object = new com.vimeo.networking.model.Space(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "free": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.free = reader.nextLong(); } else { reader.skipValue(); } break; case "used": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.used = reader.nextLong(); } else { reader.skipValue(); } break; case "max": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.max = reader.nextLong(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, VideoLog object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mLikePressLink != null) { writer.name("like_press_link"); writer.value(object.mLikePressLink); } if (object.mLoadLink != null) { writer.name("load_link"); writer.value(object.mLoadLink); } if (object.mExitLink != null) { writer.name("exit_link"); writer.value(object.mExitLink); } if (object.mPlayLink != null) { writer.name("play_link"); writer.value(object.mPlayLink); } if (object.mWatchLaterPressLink != null) { writer.name("watchlater_press_link"); writer.value(object.mWatchLaterPressLink); } } writer.endObject(); } public static VideoLog parseVideoLog(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.playback.VideoLog object = new com.vimeo.networking.model.playback.VideoLog(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "like_press_link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mLikePressLink = reader.nextString(); } else { reader.skipValue(); } break; case "load_link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mLoadLink = reader.nextString(); } else { reader.skipValue(); } break; case "exit_link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mExitLink = reader.nextString(); } else { reader.skipValue(); } break; case "play_link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mPlayLink = reader.nextString(); } else { reader.skipValue(); } break; case "watchlater_press_link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mWatchLaterPressLink = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, User object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.name != null) { writer.name("name"); writer.value(object.name); } if (object.bio != null) { writer.name("bio"); writer.value(object.bio); } if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.metadata != null) { writer.name("metadata"); ParseUtils.write(gson, writer, object.metadata); } if (object.emails != null) { writer.name("emails"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Email.class, object.emails); } if (object.pictures != null) { writer.name("pictures"); ParseUtils.write(gson, writer, object.pictures); } if (object.uploadQuota != null) { writer.name("upload_quota"); ParseUtils.write(gson, writer, object.uploadQuota); } if (object.link != null) { writer.name("link"); writer.value(object.link); } if (object.createdTime != null) { writer.name("created_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.createdTime); } if (object.account != null) { writer.name("account"); writer.value(object.account); } if (object.preferences != null) { writer.name("preferences"); ParseUtils.write(gson, writer, object.preferences); } if (object.location != null) { writer.name("location"); writer.value(object.location); } if (object.websites != null) { writer.name("websites"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Website.class, object.websites); } if (object.badge != null) { writer.name("badge"); ParseUtils.write(gson, writer, object.badge); } } writer.endObject(); } public static User parseUser(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.User object = new com.vimeo.networking.model.User(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.name = reader.nextString(); } else { reader.skipValue(); } break; case "bio": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.bio = reader.nextString(); } else { reader.skipValue(); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "metadata": try { object.metadata = ParseUtils.parseMetadata(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing User.metadata JSON!", exception); } break; case "emails": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.emails = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Email.class); } else { reader.skipValue(); } break; case "pictures": try { object.pictures = ParseUtils.parsePictureCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing User.pictures JSON!", exception); } break; case "upload_quota": try { object.uploadQuota = ParseUtils.parseUploadQuota(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing User.uploadQuota JSON!", exception); } break; case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.link = reader.nextString(); } else { reader.skipValue(); } break; case "created_time": try { object.createdTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing User.createdTime JSON!", exception); } break; case "account": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.account = reader.nextString(); } else { reader.skipValue(); } break; case "preferences": try { object.preferences = ParseUtils.parsePreferences(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing User.preferences JSON!", exception); } break; case "location": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.location = reader.nextString(); } else { reader.skipValue(); } break; case "websites": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.websites = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Website.class); } else { reader.skipValue(); } break; case "badge": try { object.badge = ParseUtils.parseUserBadge(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing User.badge JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, FacetOption object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("total"); writer.value(object.mTotal); if (object.mText != null) { writer.name("text"); writer.value(object.mText); } if (object.mName != null) { writer.name("name"); writer.value(object.mName); } } writer.endObject(); } public static FacetOption parseFacetOption(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.search.FacetOption object = new com.vimeo.networking.model.search.FacetOption(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.mTotal = reader.nextInt(); } else { reader.skipValue(); } break; case "text": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mText = reader.nextString(); } else { reader.skipValue(); } break; case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mName = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Category object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.name != null) { writer.name("name"); writer.value(object.name); } if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.metadata != null) { writer.name("metadata"); ParseUtils.write(gson, writer, object.metadata); } if (object.pictures != null) { writer.name("pictures"); ParseUtils.write(gson, writer, object.pictures); } writer.name("top_level"); writer.value(object.topLevel); if (object.subcategories != null) { writer.name("subcategories"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Category.class, object.subcategories); } if (object.parent != null) { writer.name("parent"); ParseUtils.write(gson, writer, object.parent); } if (object.link != null) { writer.name("link"); writer.value(object.link); } } writer.endObject(); } public static Category parseCategory(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Category object = new com.vimeo.networking.model.Category(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.name = reader.nextString(); } else { reader.skipValue(); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "metadata": try { object.metadata = ParseUtils.parseMetadata(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Category.metadata JSON!", exception); } break; case "pictures": try { object.pictures = ParseUtils.parsePictureCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Category.pictures JSON!", exception); } break; case "top_level": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.topLevel = reader.nextBoolean(); } else { reader.skipValue(); } break; case "subcategories": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.subcategories = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Category.class); } else { reader.skipValue(); } break; case "parent": try { object.parent = ParseUtils.parseCategory(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Category.parent JSON!", exception); } break; case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.link = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, VodList object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("total"); writer.value(object.total); writer.name("per_page"); writer.value(object.perPage); writer.name("page"); writer.value(object.page); if (object.data != null) { writer.name("data"); ParseUtils.write(gson, writer, com.vimeo.networking.model.VodItem.class, object.data); } if (object.paging != null) { writer.name("paging"); ParseUtils.write(gson, writer, object.paging); } } writer.endObject(); } public static VodList parseVodList(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.VodList object = new com.vimeo.networking.model.VodList(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.total = reader.nextInt(); } else { reader.skipValue(); } break; case "per_page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.perPage = reader.nextInt(); } else { reader.skipValue(); } break; case "page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.page = reader.nextInt(); } else { reader.skipValue(); } break; case "data": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.data = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.VodItem.class); } else { reader.skipValue(); } break; case "paging": try { object.paging = ParseUtils.parsePaging(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VodList.paging JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, InteractionCollection object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.rent != null) { writer.name("rent"); ParseUtils.write(gson, writer, object.rent); } if (object.watchlater != null) { writer.name("watchlater"); ParseUtils.write(gson, writer, object.watchlater); } if (object.follow != null) { writer.name("follow"); ParseUtils.write(gson, writer, object.follow); } if (object.like != null) { writer.name("like"); ParseUtils.write(gson, writer, object.like); } if (object.buy != null) { writer.name("buy"); ParseUtils.write(gson, writer, object.buy); } if (object.subscribe != null) { writer.name("subscribe"); ParseUtils.write(gson, writer, object.subscribe); } } writer.endObject(); } public static InteractionCollection parseInteractionCollection(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.InteractionCollection object = new com.vimeo.networking.model.InteractionCollection(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "rent": try { object.rent = ParseUtils.parseInteraction(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing InteractionCollection.rent JSON!", exception); } break; case "watchlater": try { object.watchlater = ParseUtils.parseInteraction(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing InteractionCollection.watchlater JSON!", exception); } break; case "follow": try { object.follow = ParseUtils.parseInteraction(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing InteractionCollection.follow JSON!", exception); } break; case "like": try { object.like = ParseUtils.parseInteraction(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing InteractionCollection.like JSON!", exception); } break; case "buy": try { object.buy = ParseUtils.parseInteraction(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing InteractionCollection.buy JSON!", exception); } break; case "subscribe": try { object.subscribe = ParseUtils.parseInteraction(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing InteractionCollection.subscribe JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Interaction object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("added"); writer.value(object.added); if (object.addedTime != null) { writer.name("added_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.addedTime); } if (object.expiration != null) { writer.name("expires_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.expiration); } if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.stream != null) { writer.name("stream"); Stag.writeToAdapter(gson, com.vimeo.networking.model.Interaction.Stream.class, writer, object.stream); } } writer.endObject(); } public static Interaction parseInteraction(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Interaction object = new com.vimeo.networking.model.Interaction(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "added": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.added = reader.nextBoolean(); } else { reader.skipValue(); } break; case "added_time": try { object.addedTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Interaction.addedTime JSON!", exception); } break; case "expires_time": try { object.expiration = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Interaction.expiration JSON!", exception); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "stream": try { object.stream = Stag.readFromAdapter(gson, com.vimeo.networking.model.Interaction.Stream.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Interaction.stream JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Video object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.releaseTime != null) { writer.name("release_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.releaseTime); } if (object.description != null) { writer.name("description"); writer.value(object.description); } if (object.modifiedTime != null) { writer.name("modified_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.modifiedTime); } if (object.contentRating != null) { writer.name("content_rating"); ParseUtils.write(gson, writer, java.lang.String.class, object.contentRating); } if (object.license != null) { writer.name("license"); writer.value(object.license); } if (object.tags != null) { writer.name("tags"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Tag.class, object.tags); } if (object.reviewLink != null) { writer.name("review_link"); writer.value(object.reviewLink); } writer.name("height"); writer.value(object.height); if (object.files != null) { writer.name("files"); ParseUtils.write(gson, writer, com.vimeo.networking.model.VideoFile.class, object.files); } if (object.link != null) { writer.name("link"); writer.value(object.link); } if (object.stats != null) { writer.name("stats"); ParseUtils.write(gson, writer, object.stats); } if (object.metadata != null) { writer.name("metadata"); ParseUtils.write(gson, writer, object.metadata); } if (object.language != null) { writer.name("language"); writer.value(object.language); } if (object.createdTime != null) { writer.name("created_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.createdTime); } if (object.password != null) { writer.name("password"); writer.value(object.password); } if (object.pictures != null) { writer.name("pictures"); ParseUtils.write(gson, writer, object.pictures); } if (object.embed != null) { writer.name("embed"); ParseUtils.write(gson, writer, object.embed); } if (object.status != null) { writer.name("status"); Stag.writeToAdapter(gson, com.vimeo.networking.model.Video.Status.class, writer, object.status); } if (object.play != null) { writer.name("play"); ParseUtils.write(gson, writer, object.play); } writer.name("duration"); writer.value(object.duration); if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.resourceKey != null) { writer.name("resource_key"); writer.value(object.resourceKey); } if (object.privacy != null) { writer.name("privacy"); ParseUtils.write(gson, writer, object.privacy); } writer.name("width"); writer.value(object.width); if (object.categories != null) { writer.name("categories"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Category.class, object.categories); } if (object.name != null) { writer.name("name"); writer.value(object.name); } if (object.user != null) { writer.name("user"); ParseUtils.write(gson, writer, object.user); } if (object.download != null) { writer.name("download"); ParseUtils.write(gson, writer, com.vimeo.networking.model.VideoFile.class, object.download); } } writer.endObject(); } public static Video parseVideo(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Video object = new com.vimeo.networking.model.Video(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "release_time": try { object.releaseTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.releaseTime JSON!", exception); } break; case "description": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.description = reader.nextString(); } else { reader.skipValue(); } break; case "modified_time": try { object.modifiedTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.modifiedTime JSON!", exception); } break; case "content_rating": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.contentRating = ParseUtils.parseArray(gson, reader, java.lang.String.class); } else { reader.skipValue(); } break; case "license": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.license = reader.nextString(); } else { reader.skipValue(); } break; case "tags": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.tags = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Tag.class); } else { reader.skipValue(); } break; case "review_link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.reviewLink = reader.nextString(); } else { reader.skipValue(); } break; case "height": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.height = reader.nextInt(); } else { reader.skipValue(); } break; case "files": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.files = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.VideoFile.class); } else { reader.skipValue(); } break; case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.link = reader.nextString(); } else { reader.skipValue(); } break; case "stats": try { object.stats = ParseUtils.parseStatsCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.stats JSON!", exception); } break; case "metadata": try { object.metadata = ParseUtils.parseMetadata(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.metadata JSON!", exception); } break; case "language": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.language = reader.nextString(); } else { reader.skipValue(); } break; case "created_time": try { object.createdTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.createdTime JSON!", exception); } break; case "password": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.password = reader.nextString(); } else { reader.skipValue(); } break; case "pictures": try { object.pictures = ParseUtils.parsePictureCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.pictures JSON!", exception); } break; case "embed": try { object.embed = ParseUtils.parseEmbed(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.embed JSON!", exception); } break; case "status": try { object.status = Stag.readFromAdapter(gson, com.vimeo.networking.model.Video.Status.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.status JSON!", exception); } break; case "play": try { object.play = ParseUtils.parsePlay(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.play JSON!", exception); } break; case "duration": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.duration = reader.nextInt(); } else { reader.skipValue(); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "resource_key": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.resourceKey = reader.nextString(); } else { reader.skipValue(); } break; case "privacy": try { object.privacy = ParseUtils.parsePrivacy(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.privacy JSON!", exception); } break; case "width": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.width = reader.nextInt(); } else { reader.skipValue(); } break; case "categories": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.categories = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Category.class); } else { reader.skipValue(); } break; case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.name = reader.nextString(); } else { reader.skipValue(); } break; case "user": try { object.user = ParseUtils.parseUser(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Video.user JSON!", exception); } break; case "download": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.download = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.VideoFile.class); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, VodItem object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mType != null) { writer.name("type"); Stag.writeToAdapter(gson, com.vimeo.networking.model.VodItem.VodType.class, writer, object.mType); } if (object.mPublish != null) { writer.name("publish"); ParseUtils.write(gson, writer, object.mPublish); } if (object.mFilm != null) { writer.name("film"); ParseUtils.write(gson, writer, object.mFilm); } if (object.mName != null) { writer.name("name"); writer.value(object.mName); } if (object.mMetadata != null) { writer.name("metadata"); ParseUtils.write(gson, writer, object.mMetadata); } if (object.mDescription != null) { writer.name("description"); writer.value(object.mDescription); } if (object.mPictures != null) { writer.name("pictures"); ParseUtils.write(gson, writer, object.mPictures); } if (object.mUser != null) { writer.name("user"); ParseUtils.write(gson, writer, object.mUser); } if (object.mTrailer != null) { writer.name("trailer"); ParseUtils.write(gson, writer, object.mTrailer); } if (object.mLink != null) { writer.name("link"); writer.value(object.mLink); } } writer.endObject(); } public static VodItem parseVodItem(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.VodItem object = new com.vimeo.networking.model.VodItem(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "type": try { object.mType = Stag.readFromAdapter(gson, com.vimeo.networking.model.VodItem.VodType.class, reader); } catch(Exception exception) { throw new IOException("Error parsing VodItem.mType JSON!", exception); } break; case "publish": try { object.mPublish = ParseUtils.parsePublish(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VodItem.mPublish JSON!", exception); } break; case "film": try { object.mFilm = ParseUtils.parseVideo(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VodItem.mFilm JSON!", exception); } break; case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mName = reader.nextString(); } else { reader.skipValue(); } break; case "metadata": try { object.mMetadata = ParseUtils.parseMetadata(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VodItem.mMetadata JSON!", exception); } break; case "description": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mDescription = reader.nextString(); } else { reader.skipValue(); } break; case "pictures": try { object.mPictures = ParseUtils.parsePictureCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VodItem.mPictures JSON!", exception); } break; case "user": try { object.mUser = ParseUtils.parseUser(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VodItem.mUser JSON!", exception); } break; case "trailer": try { object.mTrailer = ParseUtils.parseVideo(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VodItem.mTrailer JSON!", exception); } break; case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mLink = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Preferences object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.videos != null) { writer.name("videos"); ParseUtils.write(gson, writer, object.videos); } } writer.endObject(); } public static Preferences parsePreferences(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Preferences object = new com.vimeo.networking.model.Preferences(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "videos": try { object.videos = ParseUtils.parseVideosPreference(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Preferences.videos JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, ChannelList object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("total"); writer.value(object.total); writer.name("per_page"); writer.value(object.perPage); writer.name("page"); writer.value(object.page); if (object.data != null) { writer.name("data"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Channel.class, object.data); } if (object.paging != null) { writer.name("paging"); ParseUtils.write(gson, writer, object.paging); } } writer.endObject(); } public static ChannelList parseChannelList(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.ChannelList object = new com.vimeo.networking.model.ChannelList(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.total = reader.nextInt(); } else { reader.skipValue(); } break; case "per_page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.perPage = reader.nextInt(); } else { reader.skipValue(); } break; case "page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.page = reader.nextInt(); } else { reader.skipValue(); } break; case "data": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.data = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Channel.class); } else { reader.skipValue(); } break; case "paging": try { object.paging = ParseUtils.parsePaging(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing ChannelList.paging JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Metadata object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.connections != null) { writer.name("connections"); ParseUtils.write(gson, writer, object.connections); } if (object.interactions != null) { writer.name("interactions"); ParseUtils.write(gson, writer, object.interactions); } } writer.endObject(); } public static Metadata parseMetadata(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Metadata object = new com.vimeo.networking.model.Metadata(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "connections": try { object.connections = ParseUtils.parseConnectionCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Metadata.connections JSON!", exception); } break; case "interactions": try { object.interactions = ParseUtils.parseInteractionCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Metadata.interactions JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, PlayProgress object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mSeconds != null) { writer.name("seconds"); Stag.writeToAdapter(gson, java.lang.Float.class, writer, object.mSeconds); } } writer.endObject(); } public static PlayProgress parsePlayProgress(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.playback.PlayProgress object = new com.vimeo.networking.model.playback.PlayProgress(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "seconds": try { object.mSeconds = Stag.readFromAdapter(gson, java.lang.Float.class, reader); } catch(Exception exception) { throw new IOException("Error parsing PlayProgress.mSeconds JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Recommendation object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mDescription != null) { writer.name("description"); writer.value(object.mDescription); } if (object.mRecommendationType != null) { writer.name("type"); writer.value(object.mRecommendationType); } if (object.mResourceKey != null) { writer.name("resource_key"); writer.value(object.mResourceKey); } if (object.mUser != null) { writer.name("user"); ParseUtils.write(gson, writer, object.mUser); } if (object.mCategory != null) { writer.name("category"); ParseUtils.write(gson, writer, object.mCategory); } if (object.mChannel != null) { writer.name("channel"); ParseUtils.write(gson, writer, object.mChannel); } } writer.endObject(); } public static Recommendation parseRecommendation(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Recommendation object = new com.vimeo.networking.model.Recommendation(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "description": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mDescription = reader.nextString(); } else { reader.skipValue(); } break; case "type": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mRecommendationType = reader.nextString(); } else { reader.skipValue(); } break; case "resource_key": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mResourceKey = reader.nextString(); } else { reader.skipValue(); } break; case "user": try { object.mUser = ParseUtils.parseUser(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Recommendation.mUser JSON!", exception); } break; case "category": try { object.mCategory = ParseUtils.parseCategory(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Recommendation.mCategory JSON!", exception); } break; case "channel": try { object.mChannel = ParseUtils.parseChannel(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Recommendation.mChannel JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, CommentList object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("total"); writer.value(object.total); writer.name("per_page"); writer.value(object.perPage); writer.name("page"); writer.value(object.page); if (object.data != null) { writer.name("data"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Comment.class, object.data); } if (object.paging != null) { writer.name("paging"); ParseUtils.write(gson, writer, object.paging); } } writer.endObject(); } public static CommentList parseCommentList(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.CommentList object = new com.vimeo.networking.model.CommentList(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.total = reader.nextInt(); } else { reader.skipValue(); } break; case "per_page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.perPage = reader.nextInt(); } else { reader.skipValue(); } break; case "page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.page = reader.nextInt(); } else { reader.skipValue(); } break; case "data": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.data = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Comment.class); } else { reader.skipValue(); } break; case "paging": try { object.paging = ParseUtils.parsePaging(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing CommentList.paging JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Picture object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.link != null) { writer.name("link"); writer.value(object.link); } writer.name("height"); writer.value(object.height); writer.name("width"); writer.value(object.width); } writer.endObject(); } public static Picture parsePicture(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Picture object = new com.vimeo.networking.model.Picture(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.link = reader.nextString(); } else { reader.skipValue(); } break; case "height": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.height = reader.nextInt(); } else { reader.skipValue(); } break; case "width": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.width = reader.nextInt(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Tag object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.tag != null) { writer.name("tag"); writer.value(object.tag); } if (object.name != null) { writer.name("name"); writer.value(object.name); } if (object.metadata != null) { writer.name("metadata"); ParseUtils.write(gson, writer, object.metadata); } if (object.canonical != null) { writer.name("canonical"); writer.value(object.canonical); } } writer.endObject(); } public static Tag parseTag(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Tag object = new com.vimeo.networking.model.Tag(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "tag": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.tag = reader.nextString(); } else { reader.skipValue(); } break; case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.name = reader.nextString(); } else { reader.skipValue(); } break; case "metadata": try { object.metadata = ParseUtils.parseMetadata(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Tag.metadata JSON!", exception); } break; case "canonical": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.canonical = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Paging object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.next != null) { writer.name("next"); writer.value(object.next); } if (object.previous != null) { writer.name("previous"); writer.value(object.previous); } if (object.first != null) { writer.name("first"); writer.value(object.first); } if (object.last != null) { writer.name("last"); writer.value(object.last); } } writer.endObject(); } public static Paging parsePaging(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Paging object = new com.vimeo.networking.model.Paging(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "next": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.next = reader.nextString(); } else { reader.skipValue(); } break; case "previous": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.previous = reader.nextString(); } else { reader.skipValue(); } break; case "first": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.first = reader.nextString(); } else { reader.skipValue(); } break; case "last": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.last = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Website object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.description != null) { writer.name("description"); writer.value(object.description); } if (object.link != null) { writer.name("link"); writer.value(object.link); } if (object.name != null) { writer.name("name"); writer.value(object.name); } } writer.endObject(); } public static Website parseWebsite(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Website object = new com.vimeo.networking.model.Website(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "description": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.description = reader.nextString(); } else { reader.skipValue(); } break; case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.link = reader.nextString(); } else { reader.skipValue(); } break; case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.name = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Embed object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.html != null) { writer.name("html"); writer.value(object.html); } } writer.endObject(); } public static Embed parseEmbed(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Embed object = new com.vimeo.networking.model.Embed(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "html": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.html = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Play object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mEmbed != null) { writer.name("embed"); Stag.writeToAdapter(gson, com.vimeo.networking.model.playback.embed.Embed.class, writer, object.mEmbed); } if (object.mHls != null) { writer.name("hls"); ParseUtils.write(gson, writer, object.mHls); } if (object.mProgress != null) { writer.name("progress"); ParseUtils.write(gson, writer, object.mProgress); } if (object.mStatus != null) { writer.name("status"); Stag.writeToAdapter(gson, com.vimeo.networking.model.playback.Play.Status.class, writer, object.mStatus); } if (object.mDrm != null) { writer.name("drm"); ParseUtils.write(gson, writer, object.mDrm); } if (object.mDash != null) { writer.name("dash"); ParseUtils.write(gson, writer, object.mDash); } if (object.mProgressive != null) { writer.name("progressive"); ParseUtils.write(gson, writer, com.vimeo.networking.model.VideoFile.class, object.mProgressive); } } writer.endObject(); } public static Play parsePlay(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.playback.Play object = new com.vimeo.networking.model.playback.Play(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "embed": try { object.mEmbed = Stag.readFromAdapter(gson, com.vimeo.networking.model.playback.embed.Embed.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Play.mEmbed JSON!", exception); } break; case "hls": try { object.mHls = ParseUtils.parseVideoFile(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Play.mHls JSON!", exception); } break; case "progress": try { object.mProgress = ParseUtils.parsePlayProgress(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Play.mProgress JSON!", exception); } break; case "status": try { object.mStatus = Stag.readFromAdapter(gson, com.vimeo.networking.model.playback.Play.Status.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Play.mStatus JSON!", exception); } break; case "drm": try { object.mDrm = ParseUtils.parseDrm(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Play.mDrm JSON!", exception); } break; case "dash": try { object.mDash = ParseUtils.parseVideoFile(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Play.mDash JSON!", exception); } break; case "progressive": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.mProgressive = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.VideoFile.class); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, SearchResult object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mVod != null) { writer.name("ondemand"); ParseUtils.write(gson, writer, object.mVod); } if (object.mVideo != null) { writer.name("clip"); ParseUtils.write(gson, writer, object.mVideo); } if (object.mUser != null) { writer.name("people"); ParseUtils.write(gson, writer, object.mUser); } writer.name("is_staffpick"); writer.value(object.mIsStaffPick); writer.name("is_featured"); writer.value(object.mIsFeatured); if (object.mSearchType != null) { writer.name("type"); Stag.writeToAdapter(gson, com.vimeo.networking.model.search.SearchType.class, writer, object.mSearchType); } if (object.mChannel != null) { writer.name("channel"); ParseUtils.write(gson, writer, object.mChannel); } if (object.mGroup != null) { writer.name("group"); ParseUtils.write(gson, writer, object.mGroup); } } writer.endObject(); } public static SearchResult parseSearchResult(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.search.SearchResult object = new com.vimeo.networking.model.search.SearchResult(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "ondemand": try { object.mVod = ParseUtils.parseVodItem(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchResult.mVod JSON!", exception); } break; case "clip": try { object.mVideo = ParseUtils.parseVideo(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchResult.mVideo JSON!", exception); } break; case "people": try { object.mUser = ParseUtils.parseUser(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchResult.mUser JSON!", exception); } break; case "is_staffpick": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.mIsStaffPick = reader.nextBoolean(); } else { reader.skipValue(); } break; case "is_featured": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.mIsFeatured = reader.nextBoolean(); } else { reader.skipValue(); } break; case "type": try { object.mSearchType = Stag.readFromAdapter(gson, com.vimeo.networking.model.search.SearchType.class, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchResult.mSearchType JSON!", exception); } break; case "channel": try { object.mChannel = ParseUtils.parseChannel(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchResult.mChannel JSON!", exception); } break; case "group": try { object.mGroup = ParseUtils.parseGroup(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchResult.mGroup JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, PictureCollection object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("default"); writer.value(object.isDefault); if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.sizes != null) { writer.name("sizes"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Picture.class, object.sizes); } writer.name("active"); writer.value(object.active); } writer.endObject(); } public static PictureCollection parsePictureCollection(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.PictureCollection object = new com.vimeo.networking.model.PictureCollection(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "default": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.isDefault = reader.nextBoolean(); } else { reader.skipValue(); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "sizes": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.sizes = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Picture.class); } else { reader.skipValue(); } break; case "active": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.active = reader.nextBoolean(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, FeedItem object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.user != null) { writer.name("user"); ParseUtils.write(gson, writer, object.user); } if (object.time != null) { writer.name("time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.time); } if (object.metadata != null) { writer.name("metadata"); ParseUtils.write(gson, writer, object.metadata); } if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.clip != null) { writer.name("clip"); ParseUtils.write(gson, writer, object.clip); } if (object.type != null) { writer.name("type"); writer.value(object.type); } if (object.category != null) { writer.name("category"); ParseUtils.write(gson, writer, object.category); } if (object.group != null) { writer.name("group"); ParseUtils.write(gson, writer, object.group); } if (object.tag != null) { writer.name("tag"); ParseUtils.write(gson, writer, object.tag); } if (object.channel != null) { writer.name("channel"); ParseUtils.write(gson, writer, object.channel); } } writer.endObject(); } public static FeedItem parseFeedItem(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.FeedItem object = new com.vimeo.networking.model.FeedItem(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "user": try { object.user = ParseUtils.parseUser(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing FeedItem.user JSON!", exception); } break; case "time": try { object.time = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing FeedItem.time JSON!", exception); } break; case "metadata": try { object.metadata = ParseUtils.parseMetadata(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing FeedItem.metadata JSON!", exception); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "clip": try { object.clip = ParseUtils.parseVideo(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing FeedItem.clip JSON!", exception); } break; case "type": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.type = reader.nextString(); } else { reader.skipValue(); } break; case "category": try { object.category = ParseUtils.parseCategory(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing FeedItem.category JSON!", exception); } break; case "group": try { object.group = ParseUtils.parseGroup(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing FeedItem.group JSON!", exception); } break; case "tag": try { object.tag = ParseUtils.parseTag(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing FeedItem.tag JSON!", exception); } break; case "channel": try { object.channel = ParseUtils.parseChannel(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing FeedItem.channel JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Comment object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.type != null) { writer.name("type"); Stag.writeToAdapter(gson, com.vimeo.networking.model.Comment.CommentType.class, writer, object.type); } if (object.user != null) { writer.name("user"); ParseUtils.write(gson, writer, object.user); } if (object.text != null) { writer.name("text"); writer.value(object.text); } if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.metadata != null) { writer.name("metadata"); ParseUtils.write(gson, writer, object.metadata); } if (object.createdOn != null) { writer.name("created_on"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.createdOn); } } writer.endObject(); } public static Comment parseComment(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Comment object = new com.vimeo.networking.model.Comment(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "type": try { object.type = Stag.readFromAdapter(gson, com.vimeo.networking.model.Comment.CommentType.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Comment.type JSON!", exception); } break; case "user": try { object.user = ParseUtils.parseUser(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Comment.user JSON!", exception); } break; case "text": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.text = reader.nextString(); } else { reader.skipValue(); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "metadata": try { object.metadata = ParseUtils.parseMetadata(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Comment.metadata JSON!", exception); } break; case "created_on": try { object.createdOn = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Comment.createdOn JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, FeedList object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("total"); writer.value(object.total); writer.name("per_page"); writer.value(object.perPage); writer.name("page"); writer.value(object.page); if (object.data != null) { writer.name("data"); ParseUtils.write(gson, writer, com.vimeo.networking.model.FeedItem.class, object.data); } if (object.paging != null) { writer.name("paging"); ParseUtils.write(gson, writer, object.paging); } } writer.endObject(); } public static FeedList parseFeedList(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.FeedList object = new com.vimeo.networking.model.FeedList(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.total = reader.nextInt(); } else { reader.skipValue(); } break; case "per_page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.perPage = reader.nextInt(); } else { reader.skipValue(); } break; case "page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.page = reader.nextInt(); } else { reader.skipValue(); } break; case "data": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.data = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.FeedItem.class); } else { reader.skipValue(); } break; case "paging": try { object.paging = ParseUtils.parsePaging(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing FeedList.paging JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, VimeoAccount object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.accessToken != null) { writer.name("access_token"); writer.value(object.accessToken); } if (object.tokenType != null) { writer.name("token_type"); writer.value(object.tokenType); } if (object.scope != null) { writer.name("scope"); writer.value(object.scope); } if (object.user != null) { writer.name("user"); ParseUtils.write(gson, writer, object.user); } } writer.endObject(); } public static VimeoAccount parseVimeoAccount(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.VimeoAccount object = new com.vimeo.networking.model.VimeoAccount(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "access_token": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.accessToken = reader.nextString(); } else { reader.skipValue(); } break; case "token_type": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.tokenType = reader.nextString(); } else { reader.skipValue(); } break; case "scope": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.scope = reader.nextString(); } else { reader.skipValue(); } break; case "user": try { object.user = ParseUtils.parseUser(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VimeoAccount.user JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, VodItem.Publish object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mTime != null) { writer.name("time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.mTime); } } writer.endObject(); } public static VodItem.Publish parsePublish(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.VodItem.Publish object = new com.vimeo.networking.model.VodItem.Publish(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "time": try { object.mTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Publish.mTime JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, UploadQuota object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.quota != null) { writer.name("quota"); ParseUtils.write(gson, writer, object.quota); } if (object.space != null) { writer.name("space"); ParseUtils.write(gson, writer, object.space); } } writer.endObject(); } public static UploadQuota parseUploadQuota(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.UploadQuota object = new com.vimeo.networking.model.UploadQuota(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "quota": try { object.quota = ParseUtils.parseQuota(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing UploadQuota.quota JSON!", exception); } break; case "space": try { object.space = ParseUtils.parseSpace(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing UploadQuota.space JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, PictureResource object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } writer.name("active"); writer.value(object.active); if (object.link != null) { writer.name("link"); writer.value(object.link); } } writer.endObject(); } public static PictureResource parsePictureResource(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.PictureResource object = new com.vimeo.networking.model.PictureResource(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "active": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.active = reader.nextBoolean(); } else { reader.skipValue(); } break; case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.link = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, PinCodeInfo object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mAuthorizeLink != null) { writer.name("authorize_link"); writer.value(object.mAuthorizeLink); } writer.name("expires_in"); writer.value(object.expiresIn); if (object.mUserCode != null) { writer.name("user_code"); writer.value(object.mUserCode); } if (object.mActivateLink != null) { writer.name("activate_link"); writer.value(object.mActivateLink); } if (object.mDeviceCode != null) { writer.name("device_code"); writer.value(object.mDeviceCode); } writer.name("interval"); writer.value(object.interval); } writer.endObject(); } public static PinCodeInfo parsePinCodeInfo(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.PinCodeInfo object = new com.vimeo.networking.model.PinCodeInfo(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "authorize_link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mAuthorizeLink = reader.nextString(); } else { reader.skipValue(); } break; case "expires_in": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.expiresIn = reader.nextInt(); } else { reader.skipValue(); } break; case "user_code": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mUserCode = reader.nextString(); } else { reader.skipValue(); } break; case "activate_link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mActivateLink = reader.nextString(); } else { reader.skipValue(); } break; case "device_code": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mDeviceCode = reader.nextString(); } else { reader.skipValue(); } break; case "interval": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.interval = reader.nextInt(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, SearchFacetCollection object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mTypeFacet != null) { writer.name("type"); ParseUtils.write(gson, writer, object.mTypeFacet); } if (object.mUserTypeFacet != null) { writer.name("user_type"); ParseUtils.write(gson, writer, object.mUserTypeFacet); } if (object.mDurationFacet != null) { writer.name("duration"); ParseUtils.write(gson, writer, object.mDurationFacet); } if (object.mCategoryFacet != null) { writer.name("category"); ParseUtils.write(gson, writer, object.mCategoryFacet); } if (object.mLicenseFacet != null) { writer.name("license"); ParseUtils.write(gson, writer, object.mLicenseFacet); } if (object.mUploadedFacet != null) { writer.name("uploaded"); ParseUtils.write(gson, writer, object.mUploadedFacet); } } writer.endObject(); } public static SearchFacetCollection parseSearchFacetCollection(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.search.SearchFacetCollection object = new com.vimeo.networking.model.search.SearchFacetCollection(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "type": try { object.mTypeFacet = ParseUtils.parseSearchFacet(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchFacetCollection.mTypeFacet JSON!", exception); } break; case "user_type": try { object.mUserTypeFacet = ParseUtils.parseSearchFacet(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchFacetCollection.mUserTypeFacet JSON!", exception); } break; case "duration": try { object.mDurationFacet = ParseUtils.parseSearchFacet(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchFacetCollection.mDurationFacet JSON!", exception); } break; case "category": try { object.mCategoryFacet = ParseUtils.parseSearchFacet(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchFacetCollection.mCategoryFacet JSON!", exception); } break; case "license": try { object.mLicenseFacet = ParseUtils.parseSearchFacet(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchFacetCollection.mLicenseFacet JSON!", exception); } break; case "uploaded": try { object.mUploadedFacet = ParseUtils.parseSearchFacet(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchFacetCollection.mUploadedFacet JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Drm object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mWidevine != null) { writer.name("widevine"); ParseUtils.write(gson, writer, object.mWidevine); } if (object.mPlayReady != null) { writer.name("playready"); ParseUtils.write(gson, writer, object.mPlayReady); } } writer.endObject(); } public static Drm parseDrm(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.playback.Drm object = new com.vimeo.networking.model.playback.Drm(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "widevine": try { object.mWidevine = ParseUtils.parseVideoFile(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Drm.mWidevine JSON!", exception); } break; case "playready": try { object.mPlayReady = ParseUtils.parseVideoFile(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Drm.mPlayReady JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, VideosPreference object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.privacy != null) { writer.name("privacy"); writer.value(object.privacy); } if (object.password != null) { writer.name("password"); writer.value(object.password); } } writer.endObject(); } public static VideosPreference parseVideosPreference(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.VideosPreference object = new com.vimeo.networking.model.VideosPreference(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "privacy": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.privacy = reader.nextString(); } else { reader.skipValue(); } break; case "password": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.password = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, SearchResponse object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("total"); writer.value(object.total); writer.name("per_page"); writer.value(object.perPage); writer.name("page"); writer.value(object.page); writer.name("mature_hidden_count"); writer.value(object.mMatureHiddenCount); if (object.paging != null) { writer.name("paging"); ParseUtils.write(gson, writer, object.paging); } if (object.mFacetCollection != null) { writer.name("facets"); ParseUtils.write(gson, writer, object.mFacetCollection); } if (object.data != null) { writer.name("data"); ParseUtils.write(gson, writer, com.vimeo.networking.model.search.SearchResult.class, object.data); } } writer.endObject(); } public static SearchResponse parseSearchResponse(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.search.SearchResponse object = new com.vimeo.networking.model.search.SearchResponse(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.total = reader.nextInt(); } else { reader.skipValue(); } break; case "per_page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.perPage = reader.nextInt(); } else { reader.skipValue(); } break; case "page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.page = reader.nextInt(); } else { reader.skipValue(); } break; case "mature_hidden_count": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.mMatureHiddenCount = reader.nextInt(); } else { reader.skipValue(); } break; case "paging": try { object.paging = ParseUtils.parsePaging(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchResponse.paging JSON!", exception); } break; case "facets": try { object.mFacetCollection = ParseUtils.parseSearchFacetCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing SearchResponse.mFacetCollection JSON!", exception); } break; case "data": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.data = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.search.SearchResult.class); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, UserList object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("total"); writer.value(object.total); writer.name("per_page"); writer.value(object.perPage); writer.name("page"); writer.value(object.page); if (object.data != null) { writer.name("data"); ParseUtils.write(gson, writer, com.vimeo.networking.model.User.class, object.data); } if (object.paging != null) { writer.name("paging"); ParseUtils.write(gson, writer, object.paging); } } writer.endObject(); } public static UserList parseUserList(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.UserList object = new com.vimeo.networking.model.UserList(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.total = reader.nextInt(); } else { reader.skipValue(); } break; case "per_page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.perPage = reader.nextInt(); } else { reader.skipValue(); } break; case "page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.page = reader.nextInt(); } else { reader.skipValue(); } break; case "data": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.data = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.User.class); } else { reader.skipValue(); } break; case "paging": try { object.paging = ParseUtils.parsePaging(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing UserList.paging JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, UserBadge object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mText != null) { writer.name("text"); writer.value(object.mText); } if (object.mAlternateText != null) { writer.name("alt_text"); writer.value(object.mAlternateText); } if (object.mBadgeType != null) { writer.name("type"); writer.value(object.mBadgeType); } if (object.mUrl != null) { writer.name("url"); writer.value(object.mUrl); } } writer.endObject(); } public static UserBadge parseUserBadge(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.UserBadge object = new com.vimeo.networking.model.UserBadge(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "text": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mText = reader.nextString(); } else { reader.skipValue(); } break; case "alt_text": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mAlternateText = reader.nextString(); } else { reader.skipValue(); } break; case "type": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mBadgeType = reader.nextString(); } else { reader.skipValue(); } break; case "url": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mUrl = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Quota object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("sd"); writer.value(object.sd); writer.name("hd"); writer.value(object.hd); } writer.endObject(); } public static Quota parseQuota(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Quota object = new com.vimeo.networking.model.Quota(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "sd": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.sd = reader.nextBoolean(); } else { reader.skipValue(); } break; case "hd": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.hd = reader.nextBoolean(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Connection object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("extra_total"); writer.value(object.extraTotal); writer.name("viewable_total"); writer.value(object.viewableTotal); if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.options != null) { writer.name("options"); ParseUtils.write(gson, writer, java.lang.String.class, object.options); } writer.name("total"); writer.value(object.total); writer.name("main_total"); writer.value(object.mainTotal); } writer.endObject(); } public static Connection parseConnection(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Connection object = new com.vimeo.networking.model.Connection(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "extra_total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.extraTotal = reader.nextInt(); } else { reader.skipValue(); } break; case "viewable_total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.viewableTotal = reader.nextInt(); } else { reader.skipValue(); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "options": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.options = ParseUtils.parseArray(gson, reader, java.lang.String.class); } else { reader.skipValue(); } break; case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.total = reader.nextInt(); } else { reader.skipValue(); } break; case "main_total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.mainTotal = reader.nextInt(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Privacy object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.comments != null) { writer.name("comments"); Stag.writeToAdapter(gson, com.vimeo.networking.model.Privacy.PrivacyValue.class, writer, object.comments); } if (object.view != null) { writer.name("view"); Stag.writeToAdapter(gson, com.vimeo.networking.model.Privacy.PrivacyValue.class, writer, object.view); } if (object.embed != null) { writer.name("embed"); writer.value(object.embed); } writer.name("add"); writer.value(object.add); writer.name("download"); writer.value(object.download); } writer.endObject(); } public static Privacy parsePrivacy(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Privacy object = new com.vimeo.networking.model.Privacy(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "comments": try { object.comments = Stag.readFromAdapter(gson, com.vimeo.networking.model.Privacy.PrivacyValue.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Privacy.comments JSON!", exception); } break; case "view": try { object.view = Stag.readFromAdapter(gson, com.vimeo.networking.model.Privacy.PrivacyValue.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Privacy.view JSON!", exception); } break; case "embed": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.embed = reader.nextString(); } else { reader.skipValue(); } break; case "add": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.add = reader.nextBoolean(); } else { reader.skipValue(); } break; case "download": if(jsonToken == com.google.gson.stream.JsonToken.BOOLEAN) { object.download = reader.nextBoolean(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, VideoList object) throws IOException { writer.beginObject(); if (object == null) { return; } else { writer.name("total"); writer.value(object.total); writer.name("per_page"); writer.value(object.perPage); writer.name("page"); writer.value(object.page); if (object.data != null) { writer.name("data"); ParseUtils.write(gson, writer, com.vimeo.networking.model.Video.class, object.data); } if (object.paging != null) { writer.name("paging"); ParseUtils.write(gson, writer, object.paging); } } writer.endObject(); } public static VideoList parseVideoList(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.VideoList object = new com.vimeo.networking.model.VideoList(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "total": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.total = reader.nextInt(); } else { reader.skipValue(); } break; case "per_page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.perPage = reader.nextInt(); } else { reader.skipValue(); } break; case "page": if(jsonToken == com.google.gson.stream.JsonToken.NUMBER) { object.page = reader.nextInt(); } else { reader.skipValue(); } break; case "data": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.data = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.Video.class); } else { reader.skipValue(); } break; case "paging": try { object.paging = ParseUtils.parsePaging(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing VideoList.paging JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, SearchFacet object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.mOptions != null) { writer.name("options"); ParseUtils.write(gson, writer, com.vimeo.networking.model.search.FacetOption.class, object.mOptions); } if (object.mName != null) { writer.name("name"); writer.value(object.mName); } } writer.endObject(); } public static SearchFacet parseSearchFacet(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.search.SearchFacet object = new com.vimeo.networking.model.search.SearchFacet(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "options": if(jsonToken == com.google.gson.stream.JsonToken.BEGIN_ARRAY) { object.mOptions = ParseUtils.parseArray(gson, reader, com.vimeo.networking.model.search.FacetOption.class); } else { reader.skipValue(); } break; case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.mName = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Group object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.user != null) { writer.name("user"); ParseUtils.write(gson, writer, object.user); } if (object.createdTime != null) { writer.name("created_time"); Stag.writeToAdapter(gson, java.util.Date.class, writer, object.createdTime); } if (object.groupDescription != null) { writer.name("group_description"); writer.value(object.groupDescription); } if (object.link != null) { writer.name("link"); writer.value(object.link); } if (object.metadata != null) { writer.name("metadata"); ParseUtils.write(gson, writer, object.metadata); } if (object.uri != null) { writer.name("uri"); writer.value(object.uri); } if (object.name != null) { writer.name("name"); writer.value(object.name); } if (object.pictureCollection != null) { writer.name("picture_collection"); ParseUtils.write(gson, writer, object.pictureCollection); } if (object.privacy != null) { writer.name("privacy"); ParseUtils.write(gson, writer, object.privacy); } } writer.endObject(); } public static Group parseGroup(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Group object = new com.vimeo.networking.model.Group(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "user": try { object.user = ParseUtils.parseUser(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Group.user JSON!", exception); } break; case "created_time": try { object.createdTime = Stag.readFromAdapter(gson, java.util.Date.class, reader); } catch(Exception exception) { throw new IOException("Error parsing Group.createdTime JSON!", exception); } break; case "group_description": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.groupDescription = reader.nextString(); } else { reader.skipValue(); } break; case "link": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.link = reader.nextString(); } else { reader.skipValue(); } break; case "metadata": try { object.metadata = ParseUtils.parseMetadata(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Group.metadata JSON!", exception); } break; case "uri": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.uri = reader.nextString(); } else { reader.skipValue(); } break; case "name": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.name = reader.nextString(); } else { reader.skipValue(); } break; case "picture_collection": try { object.pictureCollection = ParseUtils.parsePictureCollection(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Group.pictureCollection JSON!", exception); } break; case "privacy": try { object.privacy = ParseUtils.parsePrivacy(gson, reader); } catch(Exception exception) { throw new IOException("Error parsing Group.privacy JSON!", exception); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } public static void write(Gson gson, JsonWriter writer, Email object) throws IOException { writer.beginObject(); if (object == null) { return; } else { if (object.email != null) { writer.name("email"); writer.value(object.email); } } writer.endObject(); } public static Email parseEmail(Gson gson, JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if(reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); com.vimeo.networking.model.Email object = new com.vimeo.networking.model.Email(); while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "email": if(jsonToken == com.google.gson.stream.JsonToken.STRING) { object.email = reader.nextString(); } else { reader.skipValue(); } break; default: reader.skipValue(); break; } } reader.endObject(); return object; } }
05d3f41f9c4983088b2aa1372f4e9f4032dde277
2026a165824d24dff458f7ebc57604cab90a15b2
/sources/kuwait/com/targetlogistics/common/Utils$12.java
a57013d57510512cdf49924715320e1d2b01253a
[]
no_license
pavankvch/TargetApp
fce893f3b4441ec0b6c0b91adf4c49ded1515ada
9ba41e2776f1a9124adf3572e75acfe3aca8c06d
refs/heads/master
2020-04-08T05:24:23.816065
2018-11-25T18:13:45
2018-11-25T18:13:45
159,059,083
0
0
null
null
null
null
UTF-8
Java
false
false
184
java
package kuwait.com.targetlogistics.common; import com.google.gson.reflect.TypeToken; import java.util.List; class Utils$12 extends TypeToken<List<String>> { Utils$12() { } }
c8b122e9cb8a16874190a99f1a288a4950a3fdd8
414ee9af7ad993f6159e955eb64e4b732c757a68
/plugins/org.reclipse.structure.inference.annotations/src/org/reclipse/structure/inference/annotations/AnnotationsFactory.java
dc402a79b362a9e922ed80a0cf2aac71a08a84cf
[ "Apache-2.0" ]
permissive
CloudScale-Project/StaticSpotter
699b7008d4cf3a8cfe6745551a48c77a18f58a42
e1473a5b6026860eab9b488086287401930fa48c
refs/heads/master
2020-05-07T20:45:22.725306
2015-02-17T10:54:05
2015-02-17T10:54:05
30,912,563
1
0
null
null
null
null
UTF-8
Java
false
false
3,338
java
/** * <copyright> * </copyright> * * $Id$ */ package org.reclipse.structure.inference.annotations; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see org.reclipse.structure.inference.annotations.AnnotationsPackage * @generated */ public interface AnnotationsFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ AnnotationsFactory eINSTANCE = org.reclipse.structure.inference.annotations.impl.AnnotationsFactoryImpl.init(); /** * Returns a new object of class '<em>ASG Annotation</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>ASG Annotation</em>'. * @generated */ ASGAnnotation createASGAnnotation(); /** * Returns a new object of class '<em>Temporary Annotation</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Temporary Annotation</em>'. * @generated */ TemporaryAnnotation createTemporaryAnnotation(); /** * Returns a new object of class '<em>Set Instance Annotation</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Set Instance Annotation</em>'. * @generated */ SetInstanceAnnotation createSetInstanceAnnotation(); /** * Returns a new object of class '<em>Annotation Set</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Annotation Set</em>'. * @generated */ AnnotationSet createAnnotationSet(); /** * Returns a new object of class '<em>Set Result Set</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Set Result Set</em>'. * @generated */ SetResultSet createSetResultSet(); /** * Returns a new object of class '<em>Annotation Engine</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Annotation Engine</em>'. * @generated */ AnnotationEngine createAnnotationEngine(); /** * Returns a new object of class '<em>Satisfied Attribute Constraint</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Satisfied Attribute Constraint</em>'. * @generated */ SatisfiedAttributeConstraint createSatisfiedAttributeConstraint(); /** * Returns a new object of class '<em>Satisfied Specification Constraint</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Satisfied Specification Constraint</em>'. * @generated */ SatisfiedSpecificationConstraint createSatisfiedSpecificationConstraint(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ AnnotationsPackage getAnnotationsPackage(); } //AnnotationsFactory
293803dd13be21c2a5c6a098b0cfb6619ef31f59
c0975e55b59bd69370d3a45f95c7c1d59a05985d
/src/com/javarush/test/level37/lesson04/big01/male/MaleFactory.java
580e5733b15afc084aa744dd20c5dcb7286c62fd
[]
no_license
kaiv2000/JavaRushHomeWork
97f4a865e81227004696e8ea1b8a38f74fcc5d43
5a49c64ee78029529e70f1ff05e6263eb4493217
refs/heads/master
2021-01-20T20:44:50.305918
2017-03-04T17:28:03
2017-03-04T17:28:03
50,733,744
0
0
null
null
null
null
UTF-8
Java
false
false
453
java
package com.javarush.test.level37.lesson04.big01.male; import com.javarush.test.level37.lesson04.big01.AbstractFactory; import com.javarush.test.level37.lesson04.big01.Human; public class MaleFactory implements AbstractFactory { public Human getPerson(int age){ if (age <= KidBoy.MAX_AGE) return new KidBoy(); else if (age > KidBoy.MAX_AGE && age <= TeenBoy.MAX_AGE ) return new TeenBoy(); else return new Man(); } }
b8554f824b43f3dcc99320a09892953b2a1b3be3
5e9f8477a15dc2e70e6778fb41bb35c17be895af
/hbase-it/src/test/java/org/apache/hadoop/hbase/IntegrationTestMetaReplicas.java
f682ea17bacf4eecf203f5d84a766b89fd3b3db8
[ "Apache-2.0", "CC-BY-3.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-protobuf" ]
permissive
xiangel/hbase-1.1.5
1e3c957b36ed0db4d57bf54dfc58dd2101b9e363
05303681eec49d98346fcefa53d8bc3c98b463b1
refs/heads/master
2021-01-12T09:38:05.530194
2016-12-12T01:03:39
2016-12-12T01:03:39
76,210,271
0
1
Apache-2.0
2023-03-20T11:47:18
2016-12-12T01:00:32
Java
UTF-8
Java
false
false
4,275
java
/** * 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.hadoop.hbase; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.TestMetaWithReplicas; import org.apache.hadoop.hbase.regionserver.StorefileRefresherChore; import org.apache.hadoop.hbase.testclassification.IntegrationTests; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; import org.apache.hadoop.util.ToolRunner; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; /** * An integration test that starts the cluster with three replicas for the meta * It then creates a table, flushes the meta, kills the server holding the primary. * After that a client issues put/get requests on the created table - the other * replicas of the meta would be used to get the location of the region of the created * table. */ @Category(IntegrationTests.class) public class IntegrationTestMetaReplicas { static final Log LOG = LogFactory.getLog(IntegrationTestMetaReplicas.class); /** * Util to get at the cluster. */ private static IntegrationTestingUtility util; @BeforeClass public static void setUp() throws Exception { // Set up the integration test util if (util == null) { util = new IntegrationTestingUtility(); } util.getConfiguration().setInt(HConstants.META_REPLICAS_NUM, 3); util.getConfiguration().setInt( StorefileRefresherChore.REGIONSERVER_STOREFILE_REFRESH_PERIOD, 1000); // Make sure there are three servers. util.initializeCluster(3); ZooKeeperWatcher zkw = util.getZooKeeperWatcher(); Configuration conf = util.getConfiguration(); String baseZNode = conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT, HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT); String primaryMetaZnode = ZKUtil.joinZNode(baseZNode, conf.get("zookeeper.znode.metaserver", "meta-region-server")); // check that the data in the znode is parseable (this would also mean the znode exists) byte[] data = ZKUtil.getData(zkw, primaryMetaZnode); ServerName.parseFrom(data); waitUntilZnodeAvailable(1); waitUntilZnodeAvailable(2); } @AfterClass public static void teardown() throws Exception { //Clean everything up. util.restoreCluster(); util = null; } private static void waitUntilZnodeAvailable(int replicaId) throws Exception { String znode = util.getZooKeeperWatcher().getZNodeForReplica(replicaId); int i = 0; while (i < 1000) { if (ZKUtil.checkExists(util.getZooKeeperWatcher(), znode) == -1) { Thread.sleep(100); i++; } else break; } if (i == 1000) throw new IOException("znode for meta replica " + replicaId + " not available"); } @Test public void testShutdownHandling() throws Exception { // This test creates a table, flushes the meta (with 3 replicas), kills the // server holding the primary meta replica. Then it does a put/get into/from // the test table. The put/get operations would use the replicas to locate the // location of the test table's region TestMetaWithReplicas.shutdownMetaAndDoValidations(util); } public static void main(String[] args) throws Exception { setUp(); new IntegrationTestMetaReplicas().testShutdownHandling(); teardown(); } }
e59c897c3714cf93bf8b5ac94cdd7d8685b64043
b604c09c8cccd8d448d1c1ca61566867a99f5cb5
/src/main/java/com/goit/gojavaonline/controllers/DishController.java
710303a677c53cd5f73ea84a169813e0f4241813
[]
no_license
IgorSinchuk/Module6.2
8ea75722f75f5239004c8d8b0ba85b051ba0bef4
6f44d82481fa1edcca13c7f938d923518e5de46c
refs/heads/master
2021-06-07T19:21:03.418807
2016-11-04T12:09:12
2016-11-04T12:09:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,550
java
package com.goit.gojavaonline.controllers; import com.goit.gojavaonline.model.*; import com.goit.gojavaonline.model.dao.DishDao; import com.goit.gojavaonline.model.dao.DishIngredientDao; import com.goit.gojavaonline.model.dao.StorageDao; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; public class DishController { private DishDao dishDao; private StorageDao storageIngredientDao; private DishIngredientDao dishIngredientDao; @Transactional public void initDishes() { List<DishIngredient> ingredients1 = new ArrayList<>(); // ingredients1.add(); // ingredients1.add(IngredientHelper.convert(storageIngredientDao.getIngredientFromStorage("carrot").getIngredient())); // ingredients1.add(IngredientHelper.convert(storageIngredientDao.getIngredientFromStorage("rice").getIngredient())); // ingredients1.add(IngredientHelper.convert(storageIngredientDao.getIngredientFromStorage("oil").getIngredient())); // ingredients1.add(IngredientHelper.convert(storageIngredientDao.getIngredientFromStorage("onion").getIngredient())); Dish plov = new Dish(); plov.setName("Plov"); plov.setCategory(DishCategory.MAIN_DISH); plov.setPrice(5.0F); plov.setWeight(300F); dishDao.save(plov); addDishIngredient(plov, "meat", 5); addDishIngredient(plov, "rice", 5); addDishIngredient(plov, "carrot", 5); addDishIngredient(plov, "oil", 1); addDishIngredient(plov, "onion", 2); Dish salad = new Dish(); salad.setName("Salad"); salad.setCategory(DishCategory.SNACK); salad.setPrice(2.0F); salad.setWeight(100F); dishDao.save(salad); addDishIngredient(salad, "tomato", 10); Dish potato = new Dish(); potato.setName("Potato"); potato.setCategory(DishCategory.MAIN_DISH); potato.setPrice(3.0F); potato.setWeight(200F); dishDao.save(potato); addDishIngredient(potato, "potato", 3); } @Transactional public List<Dish> getAllDishes() { return dishDao.findAll(); } @Transactional public Dish getDishByName(String name) { return dishDao.findByName(name); } @Transactional public void deleteDish(Dish dish) { dishDao.deleteDish(dish); } @Transactional public void removeAll() { dishIngredientDao.removeAll(); dishDao.removeAll(); } public void setDishDao(DishDao dishDao) { this.dishDao = dishDao; } public void setStorageIngredientDao(StorageDao storageIngredientDao) { this.storageIngredientDao = storageIngredientDao; } public void setDishIngredientDao(DishIngredientDao dishIngredientDao) { this.dishIngredientDao = dishIngredientDao; } private void addDishIngredient(Dish dish, String ingredientName, Integer quantity) { IngredientsStorage ingredientFromStorage = storageIngredientDao.getIngredientFromStorage(ingredientName); if (ingredientFromStorage == null) { throw new IllegalStateException("Database has no the requested ingredient [" + ingredientName + "]"); } DishIngredient dishIngredient = new DishIngredient(); dishIngredient.setIngredient(ingredientFromStorage.getIngredient()); dishIngredient.setDish(dish); dishIngredient.setQuantity(quantity); dishIngredientDao.save(dishIngredient); } }
f6d1b393c27d8052df585756ffde66b5bed874a2
4ddf269f3a033c1cb04142367f324025594ab175
/picture_library/src/main/java/com/yalantis/ucrop/view/OverlayView.java
28b57291446e8ba8d555fd35fa41c2026fe76cb5
[]
no_license
neighborW/RfGuarApp
56303adf5e4a6fdb1bd64512b4c3672fb1eddf3e
97ebfef8d7225cb83e88364ece6312c832ac8e71
refs/heads/main
2023-06-25T16:31:53.145792
2021-07-29T00:04:34
2021-07-29T00:04:34
365,379,765
0
0
null
null
null
null
UTF-8
Java
false
false
25,836
java
package com.yalantis.ucrop.view; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.RectF; import android.graphics.Region; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.animation.OvershootInterpolator; import androidx.annotation.ColorInt; import androidx.annotation.IntDef; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import com.luck.picture.lib.R; import com.yalantis.ucrop.callback.OverlayViewChangeListener; import com.yalantis.ucrop.util.RectUtils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by Oleksii Shliama (https://github.com/shliama). * <p/> * This view is used for drawing the overlay on top of the image. It may have frame, crop guidelines and dimmed area. * This must have LAYER_TYPE_SOFTWARE to draw itself properly. */ public class OverlayView extends View { public static final int FREESTYLE_CROP_MODE_DISABLE = 0; public static final int FREESTYLE_CROP_MODE_ENABLE = 1; public static final int FREESTYLE_CROP_MODE_ENABLE_WITH_PASS_THROUGH = 2; public static final boolean DEFAULT_DRAG_FRAME = true; public static final boolean DEFAULT_SHOW_CROP_FRAME = true; public static final boolean DEFAULT_SHOW_CROP_GRID = true; public static final boolean DEFAULT_CIRCLE_DIMMED_LAYER = false; public static final int DEFAULT_FREESTYLE_CROP_MODE = FREESTYLE_CROP_MODE_DISABLE; public static final int DEFAULT_CROP_GRID_ROW_COUNT = 2; public static final int DEFAULT_CROP_GRID_COLUMN_COUNT = 2; private final RectF mCropViewRect = new RectF(); private final RectF mTempRect = new RectF(); protected int mThisWidth, mThisHeight; protected float[] mCropGridCorners; protected float[] mCropGridCenter; private int mCropGridRowCount, mCropGridColumnCount; private float mTargetAspectRatio; private float[] mGridPoints = null; private boolean mShowCropFrame, mShowCropGrid; private boolean mCircleDimmedLayer; private int mDimmedColor; private int mDimmedBorderColor; private final Path mCircularPath = new Path(); private final Paint mDimmedStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Paint mCropGridPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Paint mCropFramePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Paint mCropFrameCornersPaint = new Paint(Paint.ANTI_ALIAS_FLAG); @FreestyleMode private int mFreestyleCropMode = DEFAULT_FREESTYLE_CROP_MODE; private float mPreviousTouchX = -1, mPreviousTouchY = -1; private int mCurrentTouchCornerIndex = -1; private final int mTouchPointThreshold; private final int mCropRectMinSize; private final int mCropRectCornerTouchAreaLineLength; private int mStrokeWidth = 1; private boolean mIsDragFrame = DEFAULT_DRAG_FRAME; private ValueAnimator smoothAnimator; private OverlayViewChangeListener mCallback; private boolean mShouldSetupCropBounds; { mTouchPointThreshold = getResources().getDimensionPixelSize(R.dimen.ucrop_default_crop_rect_corner_touch_threshold); mCropRectMinSize = getResources().getDimensionPixelSize(R.dimen.ucrop_default_crop_rect_min_size); mCropRectCornerTouchAreaLineLength = getResources().getDimensionPixelSize(R.dimen.ucrop_default_crop_rect_corner_touch_area_line_length); } public OverlayView(Context context) { this(context, null); } public OverlayView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public OverlayView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public OverlayViewChangeListener getOverlayViewChangeListener() { return mCallback; } public void setOverlayViewChangeListener(OverlayViewChangeListener callback) { mCallback = callback; } @NonNull public RectF getCropViewRect() { return mCropViewRect; } @Deprecated /*** * Please use the new method {@link #getFreestyleCropMode() getFreestyleCropMode} method as we have more than 1 freestyle crop mode. */ public boolean isFreestyleCropEnabled() { return mFreestyleCropMode == FREESTYLE_CROP_MODE_ENABLE; } @Deprecated /*** * Please use the new method {@link #setFreestyleCropMode setFreestyleCropMode} method as we have more than 1 freestyle crop mode. */ public void setFreestyleCropEnabled(boolean freestyleCropEnabled) { mFreestyleCropMode = freestyleCropEnabled ? FREESTYLE_CROP_MODE_ENABLE : FREESTYLE_CROP_MODE_DISABLE; } public boolean isDragFrame() { return mIsDragFrame; } public void setDragFrame(boolean mIsDragFrame) { this.mIsDragFrame = mIsDragFrame; } /** * Setter for {@link #mDimmedColor} variable. * * @param strokeWidth */ public void setDimmedStrokeWidth(int strokeWidth) { mStrokeWidth = strokeWidth; if (mDimmedStrokePaint != null) { mDimmedStrokePaint.setStrokeWidth(mStrokeWidth); } } @FreestyleMode public int getFreestyleCropMode() { return mFreestyleCropMode; } public void setFreestyleCropMode(@FreestyleMode int mFreestyleCropMode) { this.mFreestyleCropMode = mFreestyleCropMode; postInvalidate(); } /** * Setter for {@link #mCircleDimmedLayer} variable. * * @param circleDimmedLayer - set it to true if you want dimmed layer to be an circle */ public void setCircleDimmedLayer(boolean circleDimmedLayer) { mCircleDimmedLayer = circleDimmedLayer; } /** * Setter for crop grid rows count. * Resets {@link #mGridPoints} variable because it is not valid anymore. */ public void setCropGridRowCount(@IntRange(from = 0) int cropGridRowCount) { mCropGridRowCount = cropGridRowCount; mGridPoints = null; } /** * Setter for crop grid columns count. * Resets {@link #mGridPoints} variable because it is not valid anymore. */ public void setCropGridColumnCount(@IntRange(from = 0) int cropGridColumnCount) { mCropGridColumnCount = cropGridColumnCount; mGridPoints = null; } /** * Setter for {@link #mShowCropFrame} variable. * * @param showCropFrame - set to true if you want to see a crop frame rectangle on top of an image */ public void setShowCropFrame(boolean showCropFrame) { mShowCropFrame = showCropFrame; } /** * Setter for {@link #mShowCropGrid} variable. * * @param showCropGrid - set to true if you want to see a crop grid on top of an image */ public void setShowCropGrid(boolean showCropGrid) { mShowCropGrid = showCropGrid; } /** * Setter for {@link #mDimmedColor} variable. * * @param dimmedColor - desired color of dimmed area around the crop bounds */ public void setDimmedColor(@ColorInt int dimmedColor) { mDimmedColor = dimmedColor; } /** * Setter for crop frame stroke width */ public void setCropFrameStrokeWidth(@IntRange(from = 0) int width) { mCropFramePaint.setStrokeWidth(width); } /** * Setter for crop grid stroke width */ public void setCropGridStrokeWidth(@IntRange(from = 0) int width) { mCropGridPaint.setStrokeWidth(width); } /** * Setter for {@link #mDimmedColor} variable. * * @param dimmedBorderColor - desired color of dimmed area around the crop bounds */ public void setDimmedBorderColor(@ColorInt int dimmedBorderColor) { mDimmedBorderColor = dimmedBorderColor; if (mDimmedStrokePaint != null) { mDimmedStrokePaint.setColor(mDimmedBorderColor); } } /** * Setter for crop frame color */ public void setCropFrameColor(@ColorInt int color) { mCropFramePaint.setColor(color); } /** * Setter for crop grid color */ public void setCropGridColor(@ColorInt int color) { mCropGridPaint.setColor(color); } /** * This method sets aspect ratio for crop bounds. * * @param targetAspectRatio - aspect ratio for image crop (e.g. 1.77(7) for 16:9) */ public void setTargetAspectRatio(final float targetAspectRatio) { mTargetAspectRatio = targetAspectRatio; if (mThisWidth > 0) { setupCropBounds(); postInvalidate(); } else { mShouldSetupCropBounds = true; } } /** * This method setups crop bounds rectangles for given aspect ratio and view size. * {@link #mCropViewRect} is used to draw crop bounds - uses padding. */ public void setupCropBounds() { int height = (int) (mThisWidth / mTargetAspectRatio); if (height > mThisHeight) { int width = (int) (mThisHeight * mTargetAspectRatio); int halfDiff = (mThisWidth - width) / 2; mCropViewRect.set(getPaddingLeft() + halfDiff, getPaddingTop(), getPaddingLeft() + width + halfDiff, getPaddingTop() + mThisHeight); } else { int halfDiff = (mThisHeight - height) / 2; mCropViewRect.set(getPaddingLeft(), getPaddingTop() + halfDiff, getPaddingLeft() + mThisWidth, getPaddingTop() + height + halfDiff); } if (mCallback != null) { mCallback.onCropRectUpdated(mCropViewRect); } updateGridPoints(); } private void updateGridPoints() { mCropGridCorners = RectUtils.getCornersFromRect(mCropViewRect); mCropGridCenter = RectUtils.getCenterFromRect(mCropViewRect); mGridPoints = null; mCircularPath.reset(); mCircularPath.addCircle(mCropViewRect.centerX(), mCropViewRect.centerY(), Math.min(mCropViewRect.width(), mCropViewRect.height()) / 2.f, Path.Direction.CW); } protected void init() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { setLayerType(LAYER_TYPE_SOFTWARE, null); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed) { left = getPaddingLeft(); top = getPaddingTop(); right = getWidth() - getPaddingRight(); bottom = getHeight() - getPaddingBottom(); mThisWidth = right - left; mThisHeight = bottom - top; if (mShouldSetupCropBounds) { mShouldSetupCropBounds = false; setTargetAspectRatio(mTargetAspectRatio); } } } /** * Along with image there are dimmed layer, crop bounds and crop guidelines that must be drawn. */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawDimmedLayer(canvas); drawCropGrid(canvas); } @Override public boolean onTouchEvent(MotionEvent event) { if (mCropViewRect.isEmpty() || mFreestyleCropMode == FREESTYLE_CROP_MODE_DISABLE) { return false; } float x = event.getX(); float y = event.getY(); if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) { if (smoothAnimator != null) { smoothAnimator.cancel(); } mCurrentTouchCornerIndex = getCurrentTouchIndex(x, y); boolean shouldHandle = mCurrentTouchCornerIndex != -1 && mCurrentTouchCornerIndex != 4; if (!shouldHandle) { mPreviousTouchX = -1; mPreviousTouchY = -1; } else if (mPreviousTouchX < 0) { mPreviousTouchX = x; mPreviousTouchY = y; } return shouldHandle; } if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE) { if (event.getPointerCount() == 1 && mCurrentTouchCornerIndex != -1) { x = Math.min(Math.max(x, getPaddingLeft()), getWidth() - getPaddingRight()); y = Math.min(Math.max(y, getPaddingTop()), getHeight() - getPaddingBottom()); updateCropViewRect(x, y); mPreviousTouchX = x; mPreviousTouchY = y; return true; } } if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) { mPreviousTouchX = -1; mPreviousTouchY = -1; mCurrentTouchCornerIndex = -1; if (mCallback != null) { mCallback.onCropRectUpdated(mCropViewRect); } smoothToCenter(); } return false; } /** * * The order of the corners is: * 0------->1 * ^ | * | 4 | * | v * 3<-------2 */ private void updateCropViewRect(float touchX, float touchY) { mTempRect.set(mCropViewRect); switch (mCurrentTouchCornerIndex) { // resize rectangle case 0: // 是否可拖动裁剪框 if (isDragFrame()) { mTempRect.set(touchX, touchY, mCropViewRect.right, mCropViewRect.bottom); } break; case 1: // 是否可拖动裁剪框 if (isDragFrame()) { mTempRect.set(mCropViewRect.left, touchY, touchX, mCropViewRect.bottom); } break; case 2: // 是否可拖动裁剪框 if (isDragFrame()) { mTempRect.set(mCropViewRect.left, mCropViewRect.top, touchX, touchY); } break; case 3: // 是否可拖动裁剪框 if (isDragFrame()) { mTempRect.set(touchX, mCropViewRect.top, mCropViewRect.right, touchY); } break; // move rectangle case 4: mTempRect.offset(touchX - mPreviousTouchX, touchY - mPreviousTouchY); if (mTempRect.left > getLeft() && mTempRect.top > getTop() && mTempRect.right < getRight() && mTempRect.bottom < getBottom()) { mCropViewRect.set(mTempRect); updateGridPoints(); postInvalidate(); } return; } boolean changeHeight = mTempRect.height() >= mCropRectMinSize; boolean changeWidth = mTempRect.width() >= mCropRectMinSize; mCropViewRect.set( changeWidth ? mTempRect.left : mCropViewRect.left, changeHeight ? mTempRect.top : mCropViewRect.top, changeWidth ? mTempRect.right : mCropViewRect.right, changeHeight ? mTempRect.bottom : mCropViewRect.bottom); if (changeHeight || changeWidth) { updateGridPoints(); postInvalidate(); } } /** * * The order of the corners in the float array is: * 0------->1 * ^ | * | 4 | * | v * 3<-------2 * * @return - index of corner that is being dragged */ private int getCurrentTouchIndex(float touchX, float touchY) { int closestPointIndex = -1; double closestPointDistance = mTouchPointThreshold; for (int i = 0; i < 8; i += 2) { double distanceToCorner = Math.sqrt(Math.pow(touchX - mCropGridCorners[i], 2) + Math.pow(touchY - mCropGridCorners[i + 1], 2)); if (distanceToCorner < closestPointDistance) { closestPointDistance = distanceToCorner; closestPointIndex = i / 2; } } if (mFreestyleCropMode == FREESTYLE_CROP_MODE_ENABLE && closestPointIndex < 0 && mCropViewRect.contains(touchX, touchY)) { return 4; } // for (int i = 0; i <= 8; i += 2) { // // double distanceToCorner; // if (i < 8) { // corners // distanceToCorner = Math.sqrt(Math.pow(touchX - mCropGridCorners[i], 2) // + Math.pow(touchY - mCropGridCorners[i + 1], 2)); // } else { // center // distanceToCorner = Math.sqrt(Math.pow(touchX - mCropGridCenter[0], 2) // + Math.pow(touchY - mCropGridCenter[1], 2)); // } // if (distanceToCorner < closestPointDistance) { // closestPointDistance = distanceToCorner; // closestPointIndex = i / 2; // } // } return closestPointIndex; } /** * This method draws dimmed area around the crop bounds. * * @param canvas - valid canvas object */ protected void drawDimmedLayer(@NonNull Canvas canvas) { canvas.save(); if (mCircleDimmedLayer) { canvas.clipPath(mCircularPath, Region.Op.DIFFERENCE); } else { canvas.clipRect(mCropViewRect, Region.Op.DIFFERENCE); } canvas.drawColor(mDimmedColor); canvas.restore(); if (mCircleDimmedLayer) { // Draw 1px stroke to fix antialias canvas.drawCircle(mCropViewRect.centerX(), mCropViewRect.centerY(), Math.min(mCropViewRect.width(), mCropViewRect.height()) / 2.f, mDimmedStrokePaint); } } /** * This method draws crop bounds (empty rectangle) * and crop guidelines (vertical and horizontal lines inside the crop bounds) if needed. * * @param canvas - valid canvas object */ protected void drawCropGrid(@NonNull Canvas canvas) { if (mShowCropGrid) { if (mGridPoints == null && !mCropViewRect.isEmpty()) { mGridPoints = new float[(mCropGridRowCount) * 4 + (mCropGridColumnCount) * 4]; int index = 0; for (int i = 0; i < mCropGridRowCount; i++) { mGridPoints[index++] = mCropViewRect.left; mGridPoints[index++] = (mCropViewRect.height() * (((float) i + 1.0f) / (float) (mCropGridRowCount + 1))) + mCropViewRect.top; mGridPoints[index++] = mCropViewRect.right; mGridPoints[index++] = (mCropViewRect.height() * (((float) i + 1.0f) / (float) (mCropGridRowCount + 1))) + mCropViewRect.top; } for (int i = 0; i < mCropGridColumnCount; i++) { mGridPoints[index++] = (mCropViewRect.width() * (((float) i + 1.0f) / (float) (mCropGridColumnCount + 1))) + mCropViewRect.left; mGridPoints[index++] = mCropViewRect.top; mGridPoints[index++] = (mCropViewRect.width() * (((float) i + 1.0f) / (float) (mCropGridColumnCount + 1))) + mCropViewRect.left; mGridPoints[index++] = mCropViewRect.bottom; } } if (mGridPoints != null) { canvas.drawLines(mGridPoints, mCropGridPaint); } } if (mShowCropFrame) { canvas.drawRect(mCropViewRect, mCropFramePaint); } if (mFreestyleCropMode != FREESTYLE_CROP_MODE_DISABLE) { canvas.save(); mTempRect.set(mCropViewRect); mTempRect.inset(mCropRectCornerTouchAreaLineLength, -mCropRectCornerTouchAreaLineLength); canvas.clipRect(mTempRect, Region.Op.DIFFERENCE); mTempRect.set(mCropViewRect); mTempRect.inset(-mCropRectCornerTouchAreaLineLength, mCropRectCornerTouchAreaLineLength); canvas.clipRect(mTempRect, Region.Op.DIFFERENCE); canvas.drawRect(mCropViewRect, mCropFrameCornersPaint); canvas.restore(); } } /** * This method extracts all needed values from the styled attributes. * Those are used to configure the view. */ @SuppressWarnings("deprecation") protected void processStyledAttributes(@NonNull TypedArray a) { mCircleDimmedLayer = a.getBoolean(R.styleable.ucrop_UCropView_ucrop_circle_dimmed_layer, DEFAULT_CIRCLE_DIMMED_LAYER); mDimmedColor = a.getColor(R.styleable.ucrop_UCropView_ucrop_dimmed_color, getResources().getColor(R.color.ucrop_color_default_dimmed)); mDimmedStrokePaint.setColor(mDimmedBorderColor); mDimmedStrokePaint.setStyle(Paint.Style.STROKE); mDimmedStrokePaint.setStrokeWidth(mStrokeWidth); initCropFrameStyle(a); mShowCropFrame = a.getBoolean(R.styleable.ucrop_UCropView_ucrop_show_frame, DEFAULT_SHOW_CROP_FRAME); initCropGridStyle(a); mShowCropGrid = a.getBoolean(R.styleable.ucrop_UCropView_ucrop_show_grid, DEFAULT_SHOW_CROP_GRID); } /** * This method setups Paint object for the crop bounds. */ @SuppressWarnings("deprecation") private void initCropFrameStyle(@NonNull TypedArray a) { int cropFrameStrokeSize = a.getDimensionPixelSize(R.styleable.ucrop_UCropView_ucrop_frame_stroke_size, getResources().getDimensionPixelSize(R.dimen.ucrop_default_crop_frame_stoke_width)); int cropFrameColor = a.getColor(R.styleable.ucrop_UCropView_ucrop_frame_color, getResources().getColor(R.color.ucrop_color_default_crop_frame)); mCropFramePaint.setStrokeWidth(cropFrameStrokeSize); mCropFramePaint.setColor(cropFrameColor); mCropFramePaint.setStyle(Paint.Style.STROKE); mCropFrameCornersPaint.setStrokeWidth(cropFrameStrokeSize * 3); mCropFrameCornersPaint.setColor(cropFrameColor); mCropFrameCornersPaint.setStyle(Paint.Style.STROKE); } /** * This method setups Paint object for the crop guidelines. */ @SuppressWarnings("deprecation") private void initCropGridStyle(@NonNull TypedArray a) { int cropGridStrokeSize = a.getDimensionPixelSize(R.styleable.ucrop_UCropView_ucrop_grid_stroke_size, getResources().getDimensionPixelSize(R.dimen.ucrop_default_crop_grid_stoke_width)); int cropGridColor = a.getColor(R.styleable.ucrop_UCropView_ucrop_grid_color, getResources().getColor(R.color.ucrop_color_default_crop_grid)); mCropGridPaint.setStrokeWidth(cropGridStrokeSize); mCropGridPaint.setColor(cropGridColor); mCropGridRowCount = a.getInt(R.styleable.ucrop_UCropView_ucrop_grid_row_count, DEFAULT_CROP_GRID_ROW_COUNT); mCropGridColumnCount = a.getInt(R.styleable.ucrop_UCropView_ucrop_grid_column_count, DEFAULT_CROP_GRID_COLUMN_COUNT); } @Retention(RetentionPolicy.SOURCE) @IntDef({FREESTYLE_CROP_MODE_DISABLE, FREESTYLE_CROP_MODE_ENABLE, FREESTYLE_CROP_MODE_ENABLE_WITH_PASS_THROUGH}) public @interface FreestyleMode { } /** * 平滑移动至中心 */ private void smoothToCenter() { Point centerPoint = new Point((getRight() + getLeft()) / 2, (getTop() + getBottom()) / 2); final int offsetY = (int) (centerPoint.y - mCropViewRect.centerY()); final int offsetX = (int) (centerPoint.x - mCropViewRect.centerX()); final RectF before = new RectF(mCropViewRect); RectF after = new RectF(mCropViewRect); after.offset(offsetX, offsetY); if (smoothAnimator != null) { smoothAnimator.cancel(); } smoothAnimator = ValueAnimator.ofFloat(0, 1); smoothAnimator.setDuration(1000); smoothAnimator.setInterpolator(new OvershootInterpolator()); smoothAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { float lastAnimationValue = 0f; @Override public void onAnimationUpdate(ValueAnimator animation) { float x = offsetX * (float) animation.getAnimatedValue(); float y = offsetY * (float) animation.getAnimatedValue(); mCropViewRect.set(new RectF( before.left + x, before.top + y, before.right + x, before.bottom + y )); updateGridPoints(); postInvalidate(); if (mCallback != null) { mCallback.postTranslate( offsetX * ((float) animation.getAnimatedValue() - lastAnimationValue), offsetY * ((float) animation.getAnimatedValue() - lastAnimationValue) ); } lastAnimationValue = (float) animation.getAnimatedValue(); } }); smoothAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (mCallback != null) { mCallback.onCropRectUpdated(mCropViewRect); } } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); smoothAnimator.start(); } }
50a484006a5765eeb025039bd80337bfedf91dac
48f2fe20e023dd840740c754e581d861b1c167e7
/app/src/main/java/br/ufop/wagner/mybabywagner/TrocarFralda.java
c6b0e2a33e6c47a13ea2381058e8b81ffa90bf09
[]
no_license
wagnerlinharesm/MyBaby
b262d58b742794f1b8976f239784f090647c3eb2
7d64c798fdcd44f39c794bce50f5f13a7489822b
refs/heads/master
2021-01-16T07:24:42.048914
2020-02-25T15:32:16
2020-02-25T15:32:16
243,023,428
0
0
null
null
null
null
UTF-8
Java
false
false
1,690
java
package br.ufop.wagner.mybabywagner; import android.annotation.SuppressLint; import android.os.Parcel; import android.os.Parcelable; import java.io.Serializable; @SuppressLint("ParcelCreator") public class TrocarFralda extends Atividades implements Serializable,Parcelable { public String getFralda() { return fralda; } public void setFralda(String fralda) { this.fralda = fralda; } private String fralda; public TrocarFralda(String dataDeInicio, String dataFinal, String horaInicial, String anotacao, String tipo, String fralda) { super(dataDeInicio, dataFinal, horaInicial, anotacao,"Fralda", R.drawable.fraldas); this.fralda = fralda; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(getDataDeInicio()); dest.writeString(getDataFinal()); dest.writeString(getHoraInicial()); dest.writeString(getAnotacao()); dest.writeString(getTipo()); dest.writeInt(getImageView()); dest.writeString(fralda); } protected TrocarFralda(Parcel in) { super(in.readString(),in.readString(),in.readString(), in.readString(),in.readString(),in.readInt()); this.fralda = in.readString(); } public static final Creator<TrocarFralda> CREATOR = new Creator<TrocarFralda>() { @Override public TrocarFralda createFromParcel(Parcel in) { return new TrocarFralda(in); } @Override public TrocarFralda[] newArray(int size) { return new TrocarFralda[size]; } }; }
df992f36065f9ad3fab8c51df73e615f8146f6e9
c5cc4272c673f56dcc583ac5573910a10ba04043
/app/src/main/java/com/amazonaws/youruserpools/ChangePasswordActivity.java
3db71a95b959215ed378d607d39a996fc6f1abb7
[]
no_license
sheli90610/old-sensorapp-ver35
c5f6424a013a24642d9e97f62d28d4799abb4084
11e628e6923a899d37cd105737e375ec3a3a0d52
refs/heads/master
2020-04-16T20:39:50.675875
2019-01-15T18:39:07
2019-01-15T18:39:07
165,903,581
0
0
null
null
null
null
UTF-8
Java
false
false
7,748
java
/* * Copyright 2013-2017 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.youruserpools; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GenericHandler; import com.simran.powermanagement.R; public class ChangePasswordActivity extends AppCompatActivity { private EditText currPassword; private EditText newPassword; private Button changeButton; private AlertDialog userDialog; private ProgressDialog waitDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_change_password); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); Toolbar toolbar = findViewById(R.id.toolbarChangePass); toolbar.setTitle(""); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); TextView main_title = findViewById(R.id.change_password_toolbar_title); main_title.setText("Change password"); init(); } private void init() { currPassword = findViewById(R.id.editTextChangePassCurrPass); currPassword.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if(s.length() == 0) { TextView label = findViewById(R.id.textViewChangePassCurrPassLabel); label.setText(currPassword.getHint()); currPassword.setBackground(getDrawable(R.drawable.text_border_selector)); } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { TextView label = findViewById(R.id.textViewChangePassCurrPassMessage); label.setText(""); } @Override public void afterTextChanged(Editable s) { if(s.length() == 0) { TextView label = findViewById(R.id.textViewChangePassCurrPassLabel); label.setText(""); } } }); newPassword = findViewById(R.id.editTextChangePassNewPass); newPassword.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if(s.length() == 0) { TextView label = findViewById(R.id.textViewChangePassNewPassLabel); label.setText(newPassword.getHint()); newPassword.setBackground(getDrawable(R.drawable.text_border_selector)); } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { TextView label = findViewById(R.id.textViewChangePassNewPassMessage); label.setText(""); } @Override public void afterTextChanged(Editable s) { if(s.length() == 0) { TextView label = findViewById(R.id.textViewChangePassNewPassLabel); label.setText(""); } } }); changeButton = findViewById(R.id.change_pass_button); changeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changePassword(); } }); } private void changePassword() { String cPass = currPassword.getText().toString(); if(cPass == null || cPass.length() < 1) { TextView label = findViewById(R.id.textViewChangePassCurrPassMessage); label.setText(currPassword.getHint()+" cannot be empty"); currPassword.setBackground(getDrawable(R.drawable.text_border_error)); return; } String nPass = newPassword.getText().toString(); if(nPass == null || nPass.length() < 1) { TextView label = findViewById(R.id.textViewChangePassNewPassMessage); label.setText(newPassword.getHint()+" cannot be empty"); newPassword.setBackground(getDrawable(R.drawable.text_border_error)); return; } showWaitDialog("Changing password..."); AppHelper.getPool().getUser(AppHelper.getCurrUser()).changePasswordInBackground(cPass, nPass, callback); } GenericHandler callback = new GenericHandler() { @Override public void onSuccess() { closeWaitDialog(); //showDialogMessage("Success!","Password has been changed",true); Toast.makeText(getApplicationContext(),"Your password was changed",Toast.LENGTH_LONG).show(); clearInput(); } @Override public void onFailure(Exception exception) { closeWaitDialog(); newPassword.setBackground(getDrawable(R.drawable.text_border_error)); currPassword.setBackground(getDrawable(R.drawable.text_border_error)); showDialogMessage("Password change failed", AppHelper.formatException(exception), false); } }; private void clearInput() { currPassword.setText(""); newPassword.setText(""); } private void showDialogMessage(String title, String body, final boolean exitActivity) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(title).setMessage(body).setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { userDialog.dismiss(); if (exitActivity) { onBackPressed(); } } catch (Exception e) { onBackPressed(); } } }); userDialog = builder.create(); userDialog.show(); } private void showWaitDialog(String message) { closeWaitDialog(); waitDialog = new ProgressDialog(this); waitDialog.setTitle(message); waitDialog.show(); } private void closeWaitDialog() { try { waitDialog.dismiss(); } catch (Exception e) { // Wait dialog is already closed or does not exist } } }
33829af685673dd1015ef2d566c563e9875a7089
db6e498dd76a6ce78d83e1e7801674783230a90d
/thirdlib/base-protocol/protocol/src/main/java/pb4client/MerchantShipExchangeRt.java
d2d6428468303ed96162299f2cdeecc70cd2788c
[]
no_license
daxingyou/game-4
3d78fb460c4b18f711be0bb9b9520d3e8baf8349
2baef6cebf5eb0991b1f5c632c500b522c41ab20
refs/heads/master
2023-03-19T15:57:56.834881
2018-10-10T06:35:57
2018-10-10T06:35:57
null
0
0
null
null
null
null
UTF-8
Java
false
true
18,524
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: client2server.proto package pb4client; /** * Protobuf type {@code client2server.MerchantShipExchangeRt} */ public final class MerchantShipExchangeRt extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:client2server.MerchantShipExchangeRt) MerchantShipExchangeRtOrBuilder { // Use MerchantShipExchangeRt.newBuilder() to construct. private MerchantShipExchangeRt(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MerchantShipExchangeRt() { rt_ = 0; srcProtoId_ = 0; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MerchantShipExchangeRt( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; rt_ = input.readInt32(); break; } case 16: { bitField0_ |= 0x00000002; srcProtoId_ = input.readInt32(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pb4client.War2GamePkt.internal_static_client2server_MerchantShipExchangeRt_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return pb4client.War2GamePkt.internal_static_client2server_MerchantShipExchangeRt_fieldAccessorTable .ensureFieldAccessorsInitialized( pb4client.MerchantShipExchangeRt.class, pb4client.MerchantShipExchangeRt.Builder.class); } private int bitField0_; public static final int RT_FIELD_NUMBER = 1; private int rt_; /** * <code>required int32 rt = 1;</code> */ public boolean hasRt() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required int32 rt = 1;</code> */ public int getRt() { return rt_; } public static final int SRCPROTOID_FIELD_NUMBER = 2; private int srcProtoId_; /** * <pre> * 如果本次兑换激活了惊喜 这个ID表示惊喜ID * </pre> * * <code>optional int32 srcProtoId = 2;</code> */ public boolean hasSrcProtoId() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <pre> * 如果本次兑换激活了惊喜 这个ID表示惊喜ID * </pre> * * <code>optional int32 srcProtoId = 2;</code> */ public int getSrcProtoId() { return srcProtoId_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (!hasRt()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeInt32(1, rt_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeInt32(2, srcProtoId_); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, rt_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, srcProtoId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof pb4client.MerchantShipExchangeRt)) { return super.equals(obj); } pb4client.MerchantShipExchangeRt other = (pb4client.MerchantShipExchangeRt) obj; boolean result = true; result = result && (hasRt() == other.hasRt()); if (hasRt()) { result = result && (getRt() == other.getRt()); } result = result && (hasSrcProtoId() == other.hasSrcProtoId()); if (hasSrcProtoId()) { result = result && (getSrcProtoId() == other.getSrcProtoId()); } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasRt()) { hash = (37 * hash) + RT_FIELD_NUMBER; hash = (53 * hash) + getRt(); } if (hasSrcProtoId()) { hash = (37 * hash) + SRCPROTOID_FIELD_NUMBER; hash = (53 * hash) + getSrcProtoId(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static pb4client.MerchantShipExchangeRt parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pb4client.MerchantShipExchangeRt parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pb4client.MerchantShipExchangeRt parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pb4client.MerchantShipExchangeRt parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pb4client.MerchantShipExchangeRt parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static pb4client.MerchantShipExchangeRt parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static pb4client.MerchantShipExchangeRt parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static pb4client.MerchantShipExchangeRt parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static pb4client.MerchantShipExchangeRt parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static pb4client.MerchantShipExchangeRt parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static pb4client.MerchantShipExchangeRt parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static pb4client.MerchantShipExchangeRt parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(pb4client.MerchantShipExchangeRt prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code client2server.MerchantShipExchangeRt} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:client2server.MerchantShipExchangeRt) pb4client.MerchantShipExchangeRtOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return pb4client.War2GamePkt.internal_static_client2server_MerchantShipExchangeRt_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return pb4client.War2GamePkt.internal_static_client2server_MerchantShipExchangeRt_fieldAccessorTable .ensureFieldAccessorsInitialized( pb4client.MerchantShipExchangeRt.class, pb4client.MerchantShipExchangeRt.Builder.class); } // Construct using pb4client.MerchantShipExchangeRt.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); rt_ = 0; bitField0_ = (bitField0_ & ~0x00000001); srcProtoId_ = 0; bitField0_ = (bitField0_ & ~0x00000002); return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return pb4client.War2GamePkt.internal_static_client2server_MerchantShipExchangeRt_descriptor; } public pb4client.MerchantShipExchangeRt getDefaultInstanceForType() { return pb4client.MerchantShipExchangeRt.getDefaultInstance(); } public pb4client.MerchantShipExchangeRt build() { pb4client.MerchantShipExchangeRt result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public pb4client.MerchantShipExchangeRt buildPartial() { pb4client.MerchantShipExchangeRt result = new pb4client.MerchantShipExchangeRt(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.rt_ = rt_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.srcProtoId_ = srcProtoId_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof pb4client.MerchantShipExchangeRt) { return mergeFrom((pb4client.MerchantShipExchangeRt)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(pb4client.MerchantShipExchangeRt other) { if (other == pb4client.MerchantShipExchangeRt.getDefaultInstance()) return this; if (other.hasRt()) { setRt(other.getRt()); } if (other.hasSrcProtoId()) { setSrcProtoId(other.getSrcProtoId()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { if (!hasRt()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { pb4client.MerchantShipExchangeRt parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (pb4client.MerchantShipExchangeRt) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private int rt_ ; /** * <code>required int32 rt = 1;</code> */ public boolean hasRt() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required int32 rt = 1;</code> */ public int getRt() { return rt_; } /** * <code>required int32 rt = 1;</code> */ public Builder setRt(int value) { bitField0_ |= 0x00000001; rt_ = value; onChanged(); return this; } /** * <code>required int32 rt = 1;</code> */ public Builder clearRt() { bitField0_ = (bitField0_ & ~0x00000001); rt_ = 0; onChanged(); return this; } private int srcProtoId_ ; /** * <pre> * 如果本次兑换激活了惊喜 这个ID表示惊喜ID * </pre> * * <code>optional int32 srcProtoId = 2;</code> */ public boolean hasSrcProtoId() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <pre> * 如果本次兑换激活了惊喜 这个ID表示惊喜ID * </pre> * * <code>optional int32 srcProtoId = 2;</code> */ public int getSrcProtoId() { return srcProtoId_; } /** * <pre> * 如果本次兑换激活了惊喜 这个ID表示惊喜ID * </pre> * * <code>optional int32 srcProtoId = 2;</code> */ public Builder setSrcProtoId(int value) { bitField0_ |= 0x00000002; srcProtoId_ = value; onChanged(); return this; } /** * <pre> * 如果本次兑换激活了惊喜 这个ID表示惊喜ID * </pre> * * <code>optional int32 srcProtoId = 2;</code> */ public Builder clearSrcProtoId() { bitField0_ = (bitField0_ & ~0x00000002); srcProtoId_ = 0; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:client2server.MerchantShipExchangeRt) } // @@protoc_insertion_point(class_scope:client2server.MerchantShipExchangeRt) private static final pb4client.MerchantShipExchangeRt DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new pb4client.MerchantShipExchangeRt(); } public static pb4client.MerchantShipExchangeRt getDefaultInstance() { return DEFAULT_INSTANCE; } @java.lang.Deprecated public static final com.google.protobuf.Parser<MerchantShipExchangeRt> PARSER = new com.google.protobuf.AbstractParser<MerchantShipExchangeRt>() { public MerchantShipExchangeRt parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MerchantShipExchangeRt(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MerchantShipExchangeRt> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MerchantShipExchangeRt> getParserForType() { return PARSER; } public pb4client.MerchantShipExchangeRt getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
06eb4045e1c152986e1d63b61125853668e850f3
c992cc664787167313fb4d317f172e8b057b1f5b
/modules/core/src/main/java/io/jmix/core/impl/jpql/QueryVariableContext.java
b1bd35259829916c733f244397d61ff9d7a3ee16
[ "Apache-2.0" ]
permissive
alexbudarov/jmix
42628ce00a2a67bac7f4113a7e642d5a67c38197
23272dc3d6cb1f1a9826edbe888b3c993ab22d85
refs/heads/master
2020-12-19T15:57:38.886284
2020-01-23T10:06:16
2020-01-23T10:06:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,124
java
/* * Copyright 2019 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jmix.core.impl.jpql; import io.jmix.core.commons.util.Preconditions; import io.jmix.core.impl.jpql.model.JpqlEntityModel; import io.jmix.core.impl.jpql.model.VirtualJpqlEntityModel; import io.jmix.core.impl.jpql.tree.QueryNode; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class QueryVariableContext { private Map<String, JpqlEntityModel> entityVariableName2entity = new HashMap<>(); private QueryNode node; private List<QueryVariableContext> children = new ArrayList<>(); private JpqlEntityModel entity; private boolean propagateVariablesUpstairs = true; private QueryVariableContext parent = null; public QueryVariableContext(DomainModel model, QueryNode node) { Preconditions.checkNotNullArgument(model); Preconditions.checkNotNullArgument(node); this.node = node; this.entity = new VirtualJpqlEntityModel(); } public boolean isPropagateVariablesUpstairs() { return propagateVariablesUpstairs; } public void setPropagateVariablesUp(boolean propagateVariablesUpstairs) { this.propagateVariablesUpstairs = propagateVariablesUpstairs; } public JpqlEntityModel getEntityByVariableName(String entityVariableName) { JpqlEntityModel result = entityVariableName2entity.get(entityVariableName); if (result != null) { return result; } return parent == null ? null : parent.getEntityByVariableName(entityVariableName); } public JpqlEntityModel getEntityByVariableNameHierarchically(String entityVariableName) { JpqlEntityModel result = entityVariableName2entity.get(entityVariableName); if (result != null) { return result; } if (children != null) { for (QueryVariableContext child : children) { JpqlEntityModel childModel = child.getEntityByVariableNameHierarchically(entityVariableName); if (childModel != null) { return childModel; } } } return null; } /** * Internal method to register entity variables found in query * * @param variableName - found entity variable name * @param entity entity model */ public void addEntityVariable(String variableName, JpqlEntityModel entity) { if (variableName == null) { throw new JPA2RecognitionException("No entity variable name passed"); } if (entity == null) { throw new JPA2RecognitionException("No entity passed"); } if (entityVariableName2entity.containsKey(variableName)) throw new JPA2RecognitionException( String.format("The identification variable '%s' cannot be declared more than once", variableName)); entityVariableName2entity.put(variableName, entity); } public QueryVariableContext getContextByCaretPosition(int caretPosition) { if (!node.contains(caretPosition)) { return null; } for (QueryVariableContext child : children) { QueryVariableContext childResult = child.getContextByCaretPosition(caretPosition); if (childResult != null) return childResult; } return this; } public void addChild(QueryVariableContext child) { if (child == null) { throw new NullPointerException("No child passed"); } if (child.getParent() != null) { throw new IllegalArgumentException("Child has parent already"); } child.setParent(this); children.add(child); } public JpqlEntityModel getEntity() { return entity; } public void setEntity(JpqlEntityModel entity) { this.entity = entity; } private QueryVariableContext getParent() { return parent; } private void setParent(QueryVariableContext parent) { this.parent = parent; } public String getVariableNameByEntity(String entityName) { if (entityName == null) throw new NullPointerException("No entity name passed"); for (Map.Entry<String, JpqlEntityModel> entry : entityVariableName2entity.entrySet()) { if (entityName.equals(entry.getValue().getName())) { return entry.getKey(); } } return parent == null ? null : parent.getVariableNameByEntity(entityName); } }
6411ece8bb31b6d4239e3d666c1a82f2b1c72245
bb4a20bc6ffbe519cb93c255df13c5444d403fce
/week4/FirstApplication/applicationchat/src/main/java/kr/study/applicationchat/ChatActivity.java
3e7f47c8a54812bacc36cd06cf047b048082f25b
[]
no_license
KyoYoon/KUAI40-AndroidProjects
93b6dbb9831df079cab534e226d502ac127f114f
9ec41d94e10e267a686ecc7d75617326a612a879
refs/heads/master
2021-01-25T13:07:44.684410
2018-03-23T07:22:06
2018-03-23T07:22:06
123,533,960
1
0
null
null
null
null
UTF-8
Java
false
false
5,700
java
package kr.study.applicationchat; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import org.w3c.dom.Text; import java.util.Calendar; public class ChatActivity extends AppCompatActivity implements View.OnClickListener { private EditText mInputMessage; private Button mSendMessage; private LinearLayout mMessageLog; private TextView mCpuMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); // widget을 변수에 연결 // 사용자 입력필드 mInputMessage = (EditText) findViewById(R.id.input_message); // SEND 버튼 mSendMessage = (Button) findViewById(R.id.send_messsage); // 입력된 내용을 표시하는 레이아웃 mMessageLog = (LinearLayout) findViewById(R.id.message_log); // 컴퓨터가 보낸 메시지를 표시하는 텍스트뷰 mCpuMessage = (TextView) findViewById(R.id.cpu_message); // 버튼에 리스너 연결 mSendMessage.setOnClickListener(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } @Override public void onClick(View view) { // SEND 버튼을 클릭했을 때 if (view.equals(mSendMessage)) { // 입력한 값을 가져온다. String inputText = mInputMessage.getText().toString(); String answer; // 새로운 TextView 를 생성한다. TextView userMessage = new TextView(this); // TextView에 입력한 값을 넣는다. userMessage.setText(inputText); userMessage.setGravity(Gravity.END); // 오른쪽 끝에 맞춤 // TextView 를 View의 맨 뒤에 설정한다. mMessageLog.addView(userMessage, 0); // 내가 입력한 내용에 맞춰 컴퓨터가 응답한다. if (inputText.contains("hello")) { answer = "안녕하세요."; } else if (inputText.contains("tired")) { answer = "힘드셨지요."; } else if (inputText.contains("luck")) { double random = Math.random() * 5.1d; if (random < 1d) { answer = "몹시 나쁨"; } else if (random < 2d) { answer = "나쁨"; } else if (random < 3d) { answer = "보통"; } else if (random < 4d) { answer = "대박"; } else { answer = "운수대통"; } } else if (inputText.contains("time")) { Calendar cal = Calendar.getInstance(); int hour = cal.get(Calendar.HOUR); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); answer = String.format("현재시각은 %1$d시 %2$d분 %3$d초입니다.",hour,minute,second); } else { answer = "좋은 말씀입니다."; } // 내부 클래스엣 참조하기 위해서 final 로 선언한다. final TextView cpuMessage = new TextView(this); cpuMessage.setText(answer); cpuMessage.setGravity(Gravity.START); mInputMessage.setText(""); TranslateAnimation userMessageAnimation = new TranslateAnimation(mMessageLog.getWidth(), 0, 0, 0); userMessageAnimation.setDuration(1000); // 1 second userMessageAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { mMessageLog.addView(cpuMessage, 0); TranslateAnimation cpuAnimation = new TranslateAnimation(-mMessageLog.getWidth(), 0, 0, 0); cpuAnimation.setDuration(1000); cpuMessage.setAnimation(cpuAnimation); } @Override public void onAnimationRepeat(Animation animation) { } }); userMessage.startAnimation(userMessageAnimation); } } @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_chat, 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); } }
3dd5c3080c88b90715b7a21e2e4ef744501ecc81
772035006049839a30dec653457931c269aa844c
/Data Structures/BST/BST.java
d25b82d03c66f680f27169b9f39071e07c487ce0
[]
no_license
ceeeztheday/SchoolWork
6843ad3aa742dbc0f4f6a81eaf2c8d4ee148e9cc
c7f07c3e870e67a343ebc47bc9dc6b64afef6119
refs/heads/master
2022-12-21T04:43:32.385816
2020-09-18T16:17:27
2020-09-18T16:17:27
295,881,263
0
0
null
null
null
null
UTF-8
Java
false
false
1,850
java
// The BST class that represents binary search trees import java.util.*; public class BST { // instance variables private BSTNode m_root; private int m_size; // constructor public BST() { m_root = null; m_size = 0; } // add a value into the tree public void add(int v) { // TODO: implement this method using a non-recursive solution BSTNode node = new BSTNode(v); if (m_root == null) { m_root = node; m_size++; return; } BSTNode current = m_root; BSTNode parent = null; while (current != null) { if (v == current.getInfo()) return; parent = current; if (v < current.getInfo()) current = current.getLeft(); else current = current.getRight(); } if (v < parent.getInfo()) parent.setLeft(node); else parent.setRight(node); m_size++; } // print the tree content using in-order traveral public void inOrder() { // TODO: implement this method using a non-recursive solution if (m_root == null) return; Stack<BSTNode> stack = new Stack<BSTNode>(); BSTNode current = m_root; while (true) { if (current != null) { stack.push(current); current = current.getLeft(); } else { if (stack.isEmpty()) break; current = stack.pop(); System.out.print(current.getInfo() + " "); current = current.getRight(); } } } // get the size of the tree public int size() { return m_size; } // empty the tree public void clear() { m_root = null; m_size = 0; } }
e6657479d995f050dab8d1c86725deb579aa8b9e
38c94f05803cb878d5c0eb4df780f6d07dd04013
/graph-relation-service/src/main/java/com/relationservice/dto/LearnRelationRawDataDTO.java
1fdba1f63562ac2d6865f80de25f8d42dd36bb78
[]
no_license
wojtasfi/tutoro_project
74a86d7fcc724f164117044d6577aeb5150d9ff5
8a0d10065a0c8f60eec0e32bb5642f9336ccf619
refs/heads/master
2020-03-27T16:17:44.716035
2018-03-30T13:20:52
2018-03-30T13:20:52
146,772,180
0
0
null
null
null
null
UTF-8
Java
false
false
745
java
package com.relationservice.dto; import lombok.*; import java.time.LocalDate; /** * Created by wojciech on 28.06.17. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @ToString public class LearnRelationRawDataDTO { private Long teacherId; private String teacherName; private String teacherLastName; private String teacherUsername; private String teacherEmail; private String teacherSkype; private Long studentId; private String studentName; private String studentLastName; private String studentUsername; private String studentEmail; private String studentSkype; private String skill; private Long skillId; private LocalDate startDate; private LocalDate endDate; }
152d7dfa866c1bd504da4955a452d0deb8d1dfbd
9e2ab5cdac96f203e0a6014419ee50f87fdf9075
/src/main/java/org/skcorg/springsecurity/service/impl/DefaultCalendarService.java
dcb2a8519758dc394092dfd82fc5a0464b145778
[]
no_license
sumit-chandna/spring-security
89d85a8cf9c4d288cc91d94da9812976e11ca995
306401f1f3954bd201b6037161708f30d064179c
refs/heads/master
2021-01-10T21:52:33.708765
2015-09-25T09:58:14
2015-09-25T09:58:14
42,714,770
0
0
null
2015-09-23T12:21:47
2015-09-18T10:17:50
Java
UTF-8
Java
false
false
2,315
java
package org.skcorg.springsecurity.service.impl; import java.util.List; import org.skcorg.springsecurity.domain.CalendarUser; import org.skcorg.springsecurity.domain.Event; import org.skcorg.springsecurity.repositories.EventRepository; import org.skcorg.springsecurity.repositories.UserRepository; import org.skcorg.springsecurity.service.CalendarService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * A default implementation of {@link CalendarService} that delegates to * {@link EventDao} and {@link CalendarUserDao}. * * @author Sumit Chandna * */ @Service @Transactional public class DefaultCalendarService implements CalendarService { @Autowired private UserRepository userRepository; @Autowired private EventRepository eventRepository; public void setUserRepository(final UserRepository userRepository) { this.userRepository = userRepository; } public void setEventRepository(final EventRepository eventRepository) { this.eventRepository = eventRepository; } public UserRepository getUserRepository() { return userRepository; } public EventRepository getEventRepository() { return eventRepository; } @Override public Event getEvent(final int eventId) { return eventRepository.getEvent(eventId); } @Override public Event createEvent(final Event event) { Event pevent = eventRepository.save(event); return null != pevent.getId() ? pevent : null; } @Override public List<Event> findForUser(final int userId) { return eventRepository.findEventForUser(userId); } @Override public List<Event> getEvents() { return eventRepository.findAll(); } @Override public CalendarUser getUser(final int id) { return userRepository.getUser(id); } @Override public CalendarUser findUserByEmail(final String email) { return userRepository.findUserByEmail(email); } @Override public List<CalendarUser> findUsersByEmail(final String partialEmail) { return userRepository.findUsersByEmail(partialEmail); } @Override public CalendarUser createUser(final CalendarUser user) { CalendarUser calendarUser = userRepository.save(user); if (null != calendarUser.getId()) { return calendarUser; } return null; } }
f1ac1b7d62b3afc4fd9030f793b5b4e6eb39a237
f0a92681ae4a3b122b952a47e80ab73999e023ce
/app/src/main/java/com/example/pagebook/ui/fragments/notification/adapter/NotificationsRecyclerViewAdapter.java
c553c76283291f1987e35231545732791add89fd
[]
no_license
adzeo/pagebook-android
fe2e44d8c8844d6fecf55541668a884f8faa38d9
516f67b9fe4a5750b36ce91ee67899637c9fe99a
refs/heads/main
2023-02-25T01:21:55.062039
2021-02-01T08:22:19
2021-02-01T08:22:19
331,970,732
0
0
null
null
null
null
UTF-8
Java
false
false
1,805
java
package com.example.pagebook.ui.fragments.notification.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.pagebook.R; import com.example.pagebook.models.Notification; import java.util.List; public class NotificationsRecyclerViewAdapter extends RecyclerView.Adapter<NotificationsRecyclerViewAdapter.ViewHolder> { private final List<Notification> mNotificationsDataList; public NotificationsRecyclerViewAdapter(List<Notification> notificationsDataList) { this.mNotificationsDataList = notificationsDataList; } @NonNull @Override public NotificationsRecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notification_item, parent, false); return new NotificationsRecyclerViewAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull NotificationsRecyclerViewAdapter.ViewHolder holder, int position) { Notification notification = mNotificationsDataList.get(position); holder.tvNotification.setText(notification.getMessage()); } @Override public int getItemCount() { return mNotificationsDataList == null ? 0 : mNotificationsDataList.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { private final TextView tvNotification; private final View rootView; public ViewHolder(View view) { super(view); rootView = view; tvNotification = view.findViewById(R.id.tv_notification_text); } } }
bab30f16b5ba2455c8e812604a6542022862e92c
3d5e832552d72c55266994332917e7080906a48a
/cyberwire-master2/app/src/main/java/org/opensourcecurrency/hack/model/com/test/liubaiyu/AspectTest.java
a134419ef179331d56585a5c7294caf3d1a7c485
[]
no_license
PaulGao96/ADP
162075be2f17069d67a5683c79c7db4bc58aced6
83d35866ff10aed544243178514c56793380e8d2
refs/heads/master
2021-01-20T05:27:28.097590
2017-06-28T13:52:51
2017-06-28T13:52:51
89,785,988
0
1
null
null
null
null
UTF-8
Java
false
false
1,023
java
package org.opensourcecurrency.hack.model.com.test.liubaiyu; import android.util.Log; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import java.util.Arrays; /** * Created by Cooper on 2017/5/19 0019. */ @Aspect public class AspectTest { private static final String TAG = "tag"; @Pointcut("execution(* org.opensourcecurrency.hack.Send.onReceive(..))") public void test(){} @Before("test()") public void permissionCheck(JoinPoint point) { System.out.println("@Before:模拟权限检查..."); System.out.println("@Before:目标方法为:" + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName()); System.out.println("@Before:参数为:" + Arrays.toString(point.getArgs())); System.out.println("@Before:被织入的目标对象为:" + point.getTarget()); } }
5ffe6d4f5f5b373225276e402a758873c1274872
c369b2b6d67de0c70304d6e47099768970b7f15c
/app/src/main/java/com/example/loginui/ExerciseActivity.java
acbd8b1337250193c33c577767f46ef6e20c23e0
[]
no_license
Temitope3665/MyBMICalculator
709cf5521ac2132fbcd774662d94f197e7d36ba6
7b13b779be2eca792050882b5e28a9a44a068f46
refs/heads/master
2023-02-27T11:24:44.534039
2021-02-07T05:29:03
2021-02-07T05:29:03
336,711,070
0
0
null
null
null
null
UTF-8
Java
false
false
4,848
java
package com.example.loginui; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import androidx.viewpager2.widget.ViewPager2; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.media.Image; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import com.google.android.material.button.MaterialButton; import java.util.ArrayList; import java.util.List; public class ExerciseActivity extends AppCompatActivity { private OnboardingAdapter onboardingAdapter; private LinearLayout layoutOnboardingIndicators; private MaterialButton buttonOnboardingAction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exercise); layoutOnboardingIndicators = findViewById(R.id.layoutOnboardingIndicators); buttonOnboardingAction = findViewById(R.id.buttonOnboardingAction); setupOnboardingItems(); final ViewPager2 onBoardingViewPager = findViewById(R.id.onboardingViewPager); onBoardingViewPager.setAdapter(onboardingAdapter); setupOnboardingIndicators(); setCurrentOnboardingIndicator(0); onBoardingViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override public void onPageSelected(int position) { super.onPageSelected(position); setCurrentOnboardingIndicator(position); } }); buttonOnboardingAction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(onBoardingViewPager.getCurrentItem() + 1 < onboardingAdapter.getItemCount()) { onBoardingViewPager.setCurrentItem(onBoardingViewPager.getCurrentItem() + 1); } else { startActivity(new Intent(ExerciseActivity.this, ExerciseCountDown.class)); finish(); } } }); } private void setupOnboardingItems() { List<OnboardingItem> onboardingItems = new ArrayList<>(); OnboardingItem itemExerciseTime = new OnboardingItem(); itemExerciseTime.setTitle("Exercise Activity"); itemExerciseTime.setDescription("This activity allows you to set a time yourself for any exercises you want to perform.\n Have fun dearie!"); itemExerciseTime.setImage(R.drawable.hometraining); OnboardingItem itemAreYouReady = new OnboardingItem(); itemAreYouReady.setTitle("Are you ready ?"); itemAreYouReady.setDescription("Get your exercise material right now and begin your activity for today"); itemAreYouReady.setImage(R.drawable.areyouready); onboardingItems.add(itemExerciseTime); onboardingItems.add(itemAreYouReady); onboardingAdapter = new OnboardingAdapter(onboardingItems); } private void setupOnboardingIndicators(){ ImageView[] indicators = new ImageView[onboardingAdapter.getItemCount()]; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); layoutParams.setMargins(8, 0, 8, 0); for (int i = 0; i < indicators.length; i++) { indicators[i] = new ImageView(getApplicationContext()); indicators[i].setImageDrawable(ContextCompat.getDrawable( getApplicationContext(), R.drawable.onboarding_indicator_inactive )); indicators[i].setLayoutParams(layoutParams); layoutOnboardingIndicators.addView(indicators[i]); } } @SuppressLint("SetTextI18n") private void setCurrentOnboardingIndicator(int index){ int childCount = layoutOnboardingIndicators.getChildCount(); for (int i = 0; i < childCount; i++) { ImageView imageView = (ImageView)layoutOnboardingIndicators.getChildAt(i); if (i == index) { imageView.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(), R.drawable.onboarding_indicator_active) ); } else { imageView.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(), R.drawable.onboarding_indicator_inactive) ); } } if (index == onboardingAdapter.getItemCount()-1){ buttonOnboardingAction.setText("Start"); } else { buttonOnboardingAction.setText("Next"); } } }
6138d12a3a1842e7e61f8a3ee9aa4b15470c50ef
f99fe5e7d5e839628bc9d304c9618fb943050661
/app/src/main/java/com/example/hp/ibm4a/MainActivity.java
db9acaa70fa6a2f95333b0713313d4de0107ccf0
[]
no_license
Abhishek257/hungry-panda
db681c1d19c6d568eb4353ccc929349d7ef3c993
d96bd2a1716bc2c0ea9ee6c9a622a707bcc39ab3
refs/heads/master
2021-07-06T22:50:08.301575
2017-10-04T14:25:04
2017-10-04T14:25:04
105,776,725
0
0
null
null
null
null
UTF-8
Java
false
false
2,924
java
package com.example.hp.ibm4a; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends Activity { SQLiteDatabase db; EditText id,pass; Button login,signup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); login= (Button) findViewById(R.id.button4); signup= (Button) findViewById(R.id.button5); id= (EditText) findViewById(R.id.login); pass= (EditText) findViewById(R.id.pass); database obj=new database(getApplicationContext(),"PANDA",null,3); db= obj.getReadableDatabase(); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String a= id.getText().toString(); String b=pass.getText().toString(); Cursor c=db.rawQuery("Select Pass from Register where User='" +a+ "'", null); if(c.moveToNext()) { String pa=c.getString(0); if(pa.equals(b)) { Toast.makeText(getApplicationContext(), "Logged in", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, second.class); startActivity(i); } else { Toast.makeText(getApplicationContext(),"Not a valid login Id/Passward",Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(),"Not a valid login Id/Passward",Toast.LENGTH_SHORT).show(); } } }); signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(MainActivity.this, Signup.class); startActivity(i); } }); /*TimerTask task = new TimerTask() { @Override public void run() { Intent i = new Intent(MainActivity.this, second.class); startActivity(i); finishscreen(); } }; Timer t = new Timer(); t.schedule(task, 2500);*/ } /* private void finishscreen() { this.finish(); }*/ }
5d0694d11900d21920f67cd82f9c4905888a91f0
7a730d3f6b0ea83556f20517812be51184d9db1b
/src/main/java/com/springapp/mvc/HttpClientUtil.java
6595887788ca62db75cc47924b3602f3ca8b64b3
[]
no_license
dingdaxia123/springMvc
4923716c3b3bebde16aaa812e8f70f9f65048c0b
e1126cb05aacf6d21f4067545c9d73474d776012
refs/heads/master
2021-08-28T12:09:58.395620
2017-12-12T06:54:20
2017-12-12T06:54:20
113,842,683
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
1,824
java
package com.springapp.mvc; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.apache.http.NameValuePair; import org.apache.http.util.EntityUtils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Created by dinghy on 2017/8/21. */ public class HttpClientUtil { public String doPost(String url , Map<String,String> map , String charset){ HttpClient httpClient = null; HttpPost httpPost = null; String result = null; try{ httpClient = new SSLClient(); httpPost = new HttpPost(url); //ÉèÖòÎÊý List<NameValuePair> list = new ArrayList<NameValuePair>(); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<String,String> entry = (Map.Entry<String,String>)iterator.next(); list.add(new BasicNameValuePair(entry.getKey() , entry.getValue())); } if(list.size()>0){ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list , charset); httpPost.setEntity(entity); } HttpResponse response = httpClient.execute(httpPost); if(response != null){ HttpEntity resEntity = response.getEntity(); if(resEntity != null){ result = EntityUtils.toString(resEntity,charset); } } }catch (Exception e){ e.printStackTrace(); } return result; } }
cb36292147f189d019394d9d26db48d6173c7a2e
ca030864a3a1c24be6b9d1802c2353da4ca0d441
/classes8.dex_source_from_JADX/com/facebook/messaging/xma/ui/XMALongClickHelper.java
ab6e5400d680e57bdc4dfff20ebf6a93c1996fda
[]
no_license
pxson001/facebook-app
87aa51e29195eeaae69adeb30219547f83a5b7b1
640630f078980f9818049625ebc42569c67c69f7
refs/heads/master
2020-04-07T20:36:45.758523
2018-03-07T09:04:57
2018-03-07T09:04:57
124,208,458
4
0
null
null
null
null
UTF-8
Java
false
false
2,042
java
package com.facebook.messaging.xma.ui; import android.content.Context; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import com.facebook.inject.InjectorLike; import javax.annotation.Nullable; import javax.inject.Inject; /* compiled from: ti */ public class XMALongClickHelper { private GestureDetector f1606a; @Nullable public LongClickListener f1607b; public boolean f1608c; public boolean f1609d; /* compiled from: ti */ public interface LongClickListener { void mo69a(); } /* compiled from: ti */ class C01701 extends SimpleOnGestureListener { final /* synthetic */ XMALongClickHelper f1605a; C01701(XMALongClickHelper xMALongClickHelper) { this.f1605a = xMALongClickHelper; } public boolean onDown(MotionEvent motionEvent) { this.f1605a.f1608c = false; return false; } public void onLongPress(MotionEvent motionEvent) { if (this.f1605a.f1607b != null) { this.f1605a.f1608c = true; if (this.f1605a.f1609d) { this.f1605a.f1607b.mo69a(); } } } } public static XMALongClickHelper m1799b(InjectorLike injectorLike) { return new XMALongClickHelper((Context) injectorLike.getInstance(Context.class)); } @Inject public XMALongClickHelper(Context context) { this.f1606a = new GestureDetector(context, new C01701(this)); } public final boolean m1800a(MotionEvent motionEvent) { this.f1606a.onTouchEvent(motionEvent); if (motionEvent.getAction() == 0) { this.f1609d = true; } if (this.f1607b == null || !this.f1608c) { return false; } return true; } public final void m1801b(MotionEvent motionEvent) { if (motionEvent.getAction() == 0) { this.f1609d = false; } } }
4b12459df4440f4cd6a1bd43807cb99a087e6f60
0234d8446f205d2cb350e5c85b9a97855b59daa9
/src/main/java/com/banyexitou/bak/templatemethod/frame/MyFrame.java
cd1bed480bbbb54976e90c5d080f515adee65c00
[]
no_license
948424097/design_patterns
004807760556248d539d750a52b1f86681e85d3a
db66e070b3159a14040fcba3f0548d366898fc2e
refs/heads/master
2022-12-16T00:20:24.988203
2020-09-21T10:01:28
2020-09-21T10:01:28
285,510,364
0
0
null
null
null
null
UTF-8
Java
false
false
533
java
package com.banyexitou.bak.templatemethod.frame; import java.awt.*; import javax.swing.*; public class MyFrame extends JFrame { public MyFrame(String title) { super(title); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(300,300); this.setVisible(true); } public void paint(Graphics graphics) { super.paint(graphics); String msg = "I rule!!"; graphics.drawString(msg, 100, 100); } public static void main(String[] args) { MyFrame myFrame = new MyFrame("Head First Design Patterns"); } }
[ "qweqweqwe123" ]
qweqweqwe123
ad5c81c154e5738731ed82f939711e60a2a29cb3
b67462d6eb7f3ada79c691834415736747ae7be2
/topaz-datalayer-testsuite/src/main/java/com/ilyamur/topaz/datalayer/testsuite/service/DatabaseInitialization.java
4edfc9300229bbb14ef07ca6ab613834a06a3c15
[]
no_license
MuravevIV/topaz-datalayer
06d8e5ca344bd42cc61f8397a492f220a7a0fa60
28bfcbf4f99aaafb744338bce14efe24f6870acc
refs/heads/master
2023-06-24T04:19:56.249881
2022-04-21T22:00:36
2022-04-21T22:00:36
65,752,748
3
0
null
2023-06-14T22:51:44
2016-08-15T17:53:29
Java
UTF-8
Java
false
false
119
java
package com.ilyamur.topaz.datalayer.testsuite.service; public interface DatabaseInitialization { void apply(); }
b9d5c79db40bba72c54982b5f13a43d34dce1167
d5f462ae4f5e6dcbf32efeedf6bb1718046687e0
/jsmsis/src/main/java/controller/EnderecoBean.java
a61684361d3d875da540fd4ff7688caab0fa8194
[]
no_license
jsilvamoises/jsmsis
45bc46a8325b7dc991fd7954a6836fe2c0a18b24
8d973bf22cafc3b27318881b9afc96f084a7b674
refs/heads/master
2021-01-25T07:34:06.831034
2015-07-09T16:27:22
2015-07-09T16:27:22
38,025,719
0
0
null
null
null
null
UTF-8
Java
false
false
1,757
java
/* * 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 controller; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import model.Endereco; import repository.EnderecoRepository; /** * * @author MOISES */ @ManagedBean @ViewScoped public class EnderecoBean implements Serializable{ private Endereco endereco; private Endereco enderecoSelecionado; private List<Endereco> enderecos = new ArrayList<>(); private final EnderecoRepository repository; public EnderecoBean() { endereco = new Endereco(); enderecoSelecionado = new Endereco(); repository = new EnderecoRepository(); } public void save(){ repository.save(endereco); } public void delete(){ repository.remove(endereco); } public void pesquisarTodos(){ enderecos = repository.getEntities(); } public Endereco getEndereco() { return endereco; } public void setEndereco(Endereco endereco) { this.endereco = endereco; } public Endereco getEnderecoSelecionado() { return enderecoSelecionado; } public void setEnderecoSelecionado(Endereco enderecoSelecionado) { this.enderecoSelecionado = enderecoSelecionado; } public List<Endereco> getEnderecos() { return enderecos; } public void setEnderecos(List<Endereco> enderecos) { this.enderecos = enderecos; } }
4a342cc259443b13cacd6b224afe45b74ee5318e
3632e75f96ee846003fceeaf523f81abb3770d5f
/src/main/java/com/example/demo/exception/GlobalExceptionHandler.java
2adc191a83bb21fa9f425c1726f875b564757a08
[]
no_license
SxunS/miaosha
8f6b87238e7327c1abd77a424994c6c24c0d58be
a96e42226f477abdbd34972e98a59e86ce052ff2
refs/heads/master
2020-03-28T17:35:02.970248
2018-10-12T00:47:20
2018-10-12T00:47:20
148,804,141
0
0
null
null
null
null
UTF-8
Java
false
false
1,535
java
package com.example.demo.exception; import com.example.demo.result.CodeMsg; import com.example.demo.result.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.validation.BindException; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @ControllerAdvice @ResponseBody public class GlobalExceptionHandler { private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(Exception.class) public Result<String> bindExceptionHandler(Exception e){ LOG.error("Exception在GlobalExceptionHandler中被捕获 ----> ",e); if (e instanceof BindException) { List<ObjectError> allErrors = ((BindException)e).getAllErrors(); StringBuilder errorMsgs = new StringBuilder(); for (ObjectError allError : allErrors) { errorMsgs.append(allError.getDefaultMessage()); } return Result.error(CodeMsg.BIND_ERROR.filterMsg(errorMsgs.toString())); }else if (e instanceof GlobalException){ GlobalException globalException = (GlobalException) e; CodeMsg codeMsg = globalException.getCodeMsg(); return Result.error(codeMsg); }else { return Result.error(CodeMsg.SERVER_ERROR); } } }
b29715edde69ac3a2b787705c683ba835daf2309
2ed5bf1ea4e0858795ca2705ce8541c07b9e8600
/app/src/main/java/com/example/zero/ailatrieuphu/LuatChoiActivity.java
62b16b16c2916d7080a7ec320f2e1599070d429f
[]
no_license
zero4897hn/AiLaTrieuPhu
e36d76126bc66c915d7a05bd45cf4bf66c7d703a
4a605ea2f9e0cc6883ed4c64ae332d08689bb52f
refs/heads/master
2020-03-26T21:38:06.772637
2018-09-07T14:55:37
2018-09-07T14:55:37
145,399,492
3
0
null
null
null
null
UTF-8
Java
false
false
11,216
java
package com.example.zero.ailatrieuphu; import android.content.DialogInterface; import android.content.Intent; import android.media.MediaPlayer; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.example.zero.media.EffectPlayer; import com.example.zero.media.SoundTrackPlayer; import com.example.zero.setting.GameSetting; import java.util.Timer; import java.util.TimerTask; public class LuatChoiActivity extends AppCompatActivity { TextView txtCau15, txtCau10, txtCau05; TextView txtNoiDung; ImageButton btn5050, btnGoiDien, btnKhanGia; Button btnChuyenTiep, btnChoiLuon; SoundTrackPlayer playerTheme; EffectPlayer playerVoices, playerMain; Timer timer; int page = 1; int imagePosition; boolean isStarted = false; Animation animation = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_luat_choi); addControls(); addEvents(); playerTheme.startPlayerNonStop(R.raw.explain_the_rules); setTextOnChatBox(1); } private void setTextOnChatBox(int page) { switch (page) { case 1: txtCau05.setBackgroundResource(0); txtCau10.setBackgroundResource(0); txtCau15.setBackgroundResource(0); if (timer != null) timer.cancel(); playerVoices.stopPlayer(); playerVoices.startPlayerAtOnce(R.raw.explain_the_rules_page_1_voices); btnChuyenTiep.setText("Chuyển tiếp"); btnChoiLuon.setText("Chơi luôn"); txtNoiDung.setText("Có tất cả 15 câu hỏi đang chờ đợi bạn."); break; case 2: txtCau05.setBackgroundResource(0); txtCau10.setBackgroundResource(0); txtCau15.setBackgroundResource(0); if (timer != null) timer.cancel(); playerVoices.stopPlayer(); playerVoices.startPlayerAtOnce(R.raw.explain_the_rules_page_2_voices); btnChuyenTiep.setText("Chuyển tiếp"); btnChoiLuon.setText("Chơi luôn"); txtNoiDung.setText("Và có 3 mốc quan trọng cần phải vượt qua, đó là 5, 10 và 15."); if (GameSetting.amThanhHieuUng) { timer = new Timer(); imagePosition = 0; timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { imagePosition++; if (imagePosition == 1) { txtCau05.setBackgroundResource(R.drawable.selected_option); txtCau10.setBackgroundResource(0); txtCau15.setBackgroundResource(0); } else if (imagePosition == 2) { txtCau05.setBackgroundResource(0); txtCau10.setBackgroundResource(R.drawable.selected_option); txtCau15.setBackgroundResource(0); } else { txtCau05.setBackgroundResource(0); txtCau10.setBackgroundResource(0); txtCau15.setBackgroundResource(R.drawable.selected_option); imagePosition = 0; timer.cancel(); } } }); } }, 1800, 300); } else { txtCau05.setBackgroundResource(R.drawable.selected_option); txtCau10.setBackgroundResource(R.drawable.selected_option); txtCau15.setBackgroundResource(R.drawable.selected_option); } break; case 3: txtCau05.setBackgroundResource(0); txtCau10.setBackgroundResource(0); txtCau15.setBackgroundResource(0); if (timer != null) timer.cancel(); playerVoices.stopPlayer(); playerVoices.startPlayerAtOnce(R.raw.explain_the_rules_page_3_voices); btnChuyenTiep.setText("Chuyển tiếp"); btnChoiLuon.setText("Chơi luôn"); txtNoiDung.setText("Bạn cũng như những người chơi khác đến với chúng tôi, có 3 sự trợ giúp, đó là 50 : 50, Gọi điện thoại cho người thân, hoặc Hỏi ý kiến khán giả trong trường quay."); if (GameSetting.amThanhHieuUng) { animation = AnimationUtils.loadAnimation(LuatChoiActivity.this, R.anim.scale_button); timer = new Timer(); imagePosition = 0; timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { imagePosition++; if (imagePosition == 1) btn5050.startAnimation(animation); else if (imagePosition == 2) btnGoiDien.startAnimation(animation); else { btnKhanGia.startAnimation(animation); imagePosition = 0; timer.cancel(); } } }); } }, 3200, 1300); } break; case 4: txtCau05.setBackgroundResource(0); txtCau10.setBackgroundResource(0); txtCau15.setBackgroundResource(0); if (timer != null) timer.cancel(); playerVoices.stopPlayer(); playerVoices.startPlayerAtOnce(R.raw.explain_the_rules_page_4_voices); btnChuyenTiep.setText("Chưa rõ"); btnChoiLuon.setText("Tôi đã rõ"); txtNoiDung.setText("Bạn đã nắm rõ luật của chương trình chưa?"); break; } } private void addEvents() { btnChuyenTiep.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { page++; if (page > 4) page = 1; setTextOnChatBox(page); } }); btnChoiLuon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (timer != null) timer.cancel(); AlertDialog.Builder builder = new AlertDialog.Builder(LuatChoiActivity.this); builder.setTitle("Xác nhận chơi"); builder.setMessage("Bạn đã sẵn sàng chơi với chúng tôi chưa?"); builder.setPositiveButton("Đã sẵn sàng", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { playerVoices.stopPlayer(); playerTheme.stopPlayer(); if (GameSetting.amThanhHieuUng) { btnChoiLuon.setEnabled(false); btnChuyenTiep.setEnabled(false); txtNoiDung.setText("Người chơi đã sẵn sàng, và chúng ta bắt đầu đi tìm Ai là triệu phú."); isStarted = true; playerMain.startPlayerWithOnCompleteListener(R.raw.ready_to_play, new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { playerMain.stopPlayer(); onBackPressed(); Intent intent = new Intent(LuatChoiActivity.this, CauHoiActivity.class); startActivity(intent); } }); } else { Toast.makeText(LuatChoiActivity.this, "Người chơi đã sẵn sàng, và chúng ta bắt đầu đi tìm Ai là triệu phú.", Toast.LENGTH_LONG).show(); onBackPressed(); Intent intent = new Intent(LuatChoiActivity.this, CauHoiActivity.class); startActivity(intent); } dialogInterface.cancel(); } }); builder.setNegativeButton("Chưa sẵn sàng", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); } }); builder.show(); } }); } private void addControls() { btn5050 = findViewById(R.id.btn5050); btnGoiDien = findViewById(R.id.btnGoiDien); btnKhanGia = findViewById(R.id.btnKhanGia); txtCau05 = findViewById(R.id.txtCau05); txtCau10 = findViewById(R.id.txtCau10); txtCau15 = findViewById(R.id.txtCau15); txtNoiDung = findViewById(R.id.txtNoiDung); btnChuyenTiep = findViewById(R.id.btnChuyenTiep); btnChoiLuon = findViewById(R.id.btnChoiLuon); playerTheme = new SoundTrackPlayer(LuatChoiActivity.this); playerVoices = new EffectPlayer(LuatChoiActivity.this); playerMain = new EffectPlayer(LuatChoiActivity.this); } @Override protected void onPause() { playerTheme.stopPlayer(); playerVoices.stopPlayer(); playerMain.pausePlayer(); super.onPause(); } @Override protected void onResume() { super.onResume(); playerTheme.startPlayerNonStop(R.raw.explain_the_rules); playerMain.continuePlayer(); } }
0dcce8b38005cff32c57b16beca868f387a5967d
97966039b9ee0e4b7a57fed438effa0d04738423
/PaymentSolutionBackEnd/src/com/omnia/pie/cm/web/rest/param/TerminalRequestPieDb.java
d58b8d070fda7651e6c3201de7141682f96ac5bf
[]
no_license
hamzzah91/Payment-Solution-BackEnd
ce71ba70a28dda51352942b49eb84658cc439d7c
ee3a67ada61a0cb0c3d94650add26291bc7f7d84
refs/heads/master
2020-03-28T06:16:55.607992
2018-09-07T13:14:34
2018-09-07T13:14:34
147,824,768
0
0
null
null
null
null
UTF-8
Java
false
false
2,156
java
package com.omnia.pie.cm.web.rest.param; import com.fasterxml.jackson.annotation.JsonProperty; public class TerminalRequestPieDb { @JsonProperty("Terminal") protected TerminalPermissions terminalPermissions; @JsonProperty("TerminalId") protected String terminalId; @JsonProperty("TerminalLocation") protected String terminalLocation; @JsonProperty("TerminalCity") protected String terminalCity; @JsonProperty("CurrencyCode") protected String currencyCode; @JsonProperty("SerialNumber") protected String serialNumber; @JsonProperty("MerchantId") protected String merchantId; @JsonProperty("AcquiringInstitutionId") protected String acquiringInstitutionId; public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public String getAcquiringInstitutionId() { return acquiringInstitutionId; } public void setAcquiringInstitutionId(String acquiringInstitutionId) { this.acquiringInstitutionId = acquiringInstitutionId; } public TerminalPermissions getTerminalPermissions() { return terminalPermissions; } public void setTerminalPermissions(TerminalPermissions terminalPermissions) { this.terminalPermissions = terminalPermissions; } public String getTerminalId() { return terminalId; } public void setTerminalId(String terminalId) { this.terminalId = terminalId; } public String getTerminalLocation() { return terminalLocation; } public void setTerminalLocation(String terminalLocation) { this.terminalLocation = terminalLocation; } public String getTerminalCity() { return terminalCity; } public void setTerminalCity(String terminalCity) { this.terminalCity = terminalCity; } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } }
c080e1f2124b8c6edb31c2fce9c5d42c8229c081
cddc302c6e0e2940bc3af5bd2d880a6b9a5698dc
/aplicacoes/gpa/src/main/java/ufc/quixada/npi/gpa/model/ProjetoReprovadoRelatorio.java
81e84e08d73ca51c74a37f398c8f667687b53926
[]
no_license
lcld99/gpa-pesquisa
359910be51e68f04c932ab55c0204cc9215d53e1
2d90b6994261323ea822917aa3feb524fab2ff1a
refs/heads/master
2023-04-29T23:41:26.713441
2017-07-05T19:24:57
2017-07-05T19:24:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
978
java
package ufc.quixada.npi.gpa.model; import java.util.Date; public class ProjetoReprovadoRelatorio { private Long id; private String nomeProjeto; private String nomeCoordenador; private Date dataDeSubimissao; private Date dataDeAvaliacao; public String getNomeProjeto() { return nomeProjeto; } public void setNomeProjeto(String nome) { this.nomeProjeto = nome; } public String getNomeCoordenador() { return nomeCoordenador; } public void setNomeCoordenador(String nomeCoordenador) { this.nomeCoordenador = nomeCoordenador; } public Date getDataDeSubimissao() { return dataDeSubimissao; } public void setDataDeSubimissao(Date subimissao) { this.dataDeSubimissao = subimissao; } public Date getDataDeAvaliacao() { return dataDeAvaliacao; } public void setDataDeAvaliacao(Date dataDeAvaliacao) { this.dataDeAvaliacao = dataDeAvaliacao; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
9e7283c0ea45204a071afaf860fdf77f90a2b88d
c1689a0de383245360cbf4eceb9f74c42c10d3cc
/BolsaTrabajoWeb/src/com/proyecto/persistencia/dao/avisoDAO.java
1dcf350d36489f1d3008e09d417c0d7d394c6194
[]
no_license
kgg835/tecsup-proyectoweb-bolsatrabajo
cf0b4ee760ae6dce38c50359b1a91b932e22714c
ccdfb190db5ca95ce698fdd37ec0600356241554
refs/heads/master
2016-09-01T18:49:11.870028
2013-08-23T03:57:37
2013-08-23T03:57:37
33,839,975
0
0
null
null
null
null
UTF-8
Java
false
false
555
java
package com.proyecto.persistencia.dao; import java.util.Collection; import java.util.Date; import com.proyecto.exception.DAOExcepcion; import com.proyecto.modelo.Aviso; import com.proyecto.modelo.MostrarAviso; public interface avisoDAO { public Aviso insertar(Aviso vo) throws DAOExcepcion; public Collection<Aviso> listarAvisos() throws DAOExcepcion; public Collection<MostrarAviso> mostrar_aviso(int cod_aviso) throws DAOExcepcion; public Collection<Aviso> Buscar_aviso(String area,String palabra,int dias) throws DAOExcepcion; }
[ "[email protected]@851d154f-5051-faa0-1c04-ff979f6fe470" ]
[email protected]@851d154f-5051-faa0-1c04-ff979f6fe470
cab2889939a749edd20fb59e25f17165599e95a5
8f8b5f8b802f83c614ad78af032fe9936e5ffb6e
/enterprise-web-services-camel/.svn/pristine/41/41d70f2e2eeeab12208ff290b004cd0eec907cb4.svn-base
7da5e9fea9a0efb0d51b11d543fcb8475598b3c8
[]
no_license
praveen4students/hmh_backup
1b8d54bfa241f5a6412ef2423f1547d6262a530c
45630529b61126976ee0663d9f78b60690a65df7
refs/heads/master
2022-01-05T12:09:18.641190
2019-05-01T18:30:30
2019-05-01T18:30:30
114,189,899
0
0
null
null
null
null
UTF-8
Java
false
false
1,708
package hmh.sap.rfc.wrapper; import javax.xml.bind.annotation.XmlRootElement; import hmh.sap.rfc.Bapi_Mpgd_GaType; @XmlRootElement(name = "Bapi_Mpgd_GaType") public class Bapi_Mpgd_GaType_Wrapper { private Bapi_Mpgd_GaType instance; public void setInstance(Bapi_Mpgd_GaType instance) { this.instance = instance; } public Bapi_Mpgd_GaType_Wrapper() {} public Bapi_Mpgd_GaType_Wrapper(Bapi_Mpgd_GaType instance) { this.instance = instance; } // // delegate methods // public String getPlng_Matl_External() { return instance.getPlng_Matl_External(); } public void setPlng_Matl_Version(String Plng_Matl_Version) { instance.setPlng_Matl_Version(Plng_Matl_Version); } public String getPlant() { return instance.getPlant(); } public void setPlng_Matl_External(String Plng_Matl_External) { instance.setPlng_Matl_External(Plng_Matl_External); } public String getPlng_Matl() { return instance.getPlng_Matl(); } public void setPlant(String Plant) { instance.setPlant(Plant); } public String getPlng_Matl_Guid() { return instance.getPlng_Matl_Guid(); } public void setPlng_Matl_Guid(String Plng_Matl_Guid) { instance.setPlng_Matl_Guid(Plng_Matl_Guid); } public void setConvfactor(String Convfactor) { instance.setConvfactor(Convfactor); } public String getPlng_Plant() { return instance.getPlng_Plant(); } public void setPlng_Plant(String Plng_Plant) { instance.setPlng_Plant(Plng_Plant); } public String getConvfactor() { return instance.getConvfactor(); } public String getPlng_Matl_Version() { return instance.getPlng_Matl_Version(); } public void setPlng_Matl(String Plng_Matl) { instance.setPlng_Matl(Plng_Matl); } }
cf8e46d8760b4f2e6e698cb5b1202e1cd6379dce
3152917130ef5578f0b8546b1d83ed0fdc6704b0
/gomint-server/src/main/java/io/gomint/server/inventory/item/ItemHoneyCombBlock.java
5447880f3e94ea32a97a254b9d2c38eefc73be1f
[ "BSD-3-Clause" ]
permissive
Janmm14/GoMint
730eb515ab89d9b253c897c64e50e5a836841475
026cc4856f88ae17ec43632c7ff7aec9f66acaee
refs/heads/master
2021-12-20T21:14:27.147339
2021-01-29T16:35:54
2021-01-29T16:35:54
104,573,627
0
0
NOASSERTION
2021-01-29T16:46:32
2017-09-23T14:29:11
Java
UTF-8
Java
false
false
473
java
package io.gomint.server.inventory.item; import io.gomint.inventory.item.ItemType; import io.gomint.server.registry.RegisterInfo; /** * @author KingAli * @version 1.0 */ @RegisterInfo(sId = "minecraft:honeycomb_block") public class ItemHoneyCombBlock extends ItemStack< io.gomint.inventory.item.ItemHoneyCombBlock> implements io.gomint.inventory.item.ItemHoneyCombBlock { @Override public ItemType itemType() { return ItemType.HONEYCOMBBLOCK; } }
b8b38cf61aeaabbbcc2a4c5e497d706c1b22ef06
d9e5b7c22636df20449da0132953762407cb02ba
/app/src/main/java/com/example/simos/advantage_movies_app/MoviesList/MovieListInterface.java
04a2b1d39ebc284b8f26e741996497a85adc1f6e
[]
no_license
syiordan/Movies-App
3f8cb9a432e8f9cbbe6f0bba2569435569e90209
7cbd49e2c38e4f6fb54cedd9825c9128013b653d
refs/heads/master
2020-04-21T18:40:05.954236
2019-02-08T18:25:21
2019-02-08T18:25:21
169,778,894
1
0
null
null
null
null
UTF-8
Java
false
false
861
java
package com.example.simos.advantage_movies_app.MoviesList; import android.content.Context; import com.example.simos.advantage_movies_app.Retrofit.Movie_Object; import java.util.ArrayList; import java.util.List; public interface MovieListInterface { interface Model { interface OnFinishedListener { void onFinished(List<Movie_Object> movieArrayList); void onFailure(Throwable t); } void getMovieList(OnFinishedListener onFinishedListener,String movie, int pageNo); } interface View { void update_list_data(List<Movie_Object> movieArrayList); } interface Presenter { void onDestroy(); void getMoreData(int pageNo,String query); void requestDataFromServer(String query); } }
aac5434cbfe07bd7db95b6d8177447c81912c27e
11b15a29429af7d8dd792b0c93dd09ea1f30dffb
/3o Periodo/Programacao Orientada a Objetos/Arquivos da Materia/RespostasExercicios/ExercicioVetorAleatorio1.java
e2be96c7c0dbff1696263a90dcc9a6ae0a8418a7
[]
no_license
antonmr/UNISUAM
171b6c95b9752acd8180fade4ec320a98ef7cc29
06959c9c3264ec500753e3720fd813cb2125b633
refs/heads/master
2021-01-11T11:07:05.050542
2018-11-28T04:00:09
2018-11-28T04:00:09
36,993,279
0
0
null
2015-06-06T19:55:07
2015-06-06T19:55:06
null
UTF-8
Java
false
false
534
java
/* Escreva um programa em Java que armazene em um vetor quinze números aleatórios (cada um deles é um valor de 0.0 até 1.0). Após isso, o programa deve imprimir todos os valores armazenados. */ class ExercicioVetorAleatorio1 { public static void main(String[] args) { double[] vet; int i; vet = new double[15]; for(i = 0; i < vet.length; i++) vet[i] = Math.random(); for(i = 0; i < vet.length; i++) System.out.println("vet[" + i + "] = " + vet[i]); } }
8406e5ce0731cf429b778d19e0b83abe5eb1343b
68af74a0377cbb175c43d2f66f3f5a0158440433
/src/main/java/com/vho/javalowlevel/concurrency/retryer/StopStrategy.java
21200a4861d06c469368abc192fd4c321815a330
[]
no_license
hotienvu/java-lowlevel
b8b3abc6634d66e88fdcc222d2d7136aeac381d8
f865fc7e15c94ba9476644c0ea38157a7b0e672d
refs/heads/master
2023-03-11T18:28:23.386101
2021-02-26T03:56:51
2021-02-26T03:56:51
314,743,719
0
0
null
null
null
null
UTF-8
Java
false
false
146
java
package com.vho.javalowlevel.concurrency.retryer; public interface StopStrategy { boolean shouldStop(Attempt attempt); String getReason(); }
0b6e0e20b497b85edc6a67293e68221ab7a46d4e
26acffbb575a07dbacfd6685aa6cdb90c718a1cc
/src/com/speakeasy/skyengine/utils/Logger.java
ccc3116e23dab2dd88c5e789abd1bfbe2feef545
[ "Artistic-2.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
speakeasy/SKYEngine
8e0f6838b070b193ef61d4f2321333ec02f40f2c
4805aed0cddf31cbecba19b34c62b86c18246f22
refs/heads/master
2021-01-10T03:45:33.261701
2016-12-23T16:48:36
2016-12-23T16:48:36
50,658,018
0
0
null
null
null
null
UTF-8
Java
false
false
233
java
package com.speakeasy.skyengine.utils; public class Logger { public static final boolean logging = true; public static void log(String text) { if (logging) { System.out.println(text); } } }
[ "SpeaKeasY@SpeaKeasYSKY" ]
SpeaKeasY@SpeaKeasYSKY
c1ea6fcfaf9b7e990d99f9c73515a03eda845927
e1ffb09e187e050580284aa93ca25cb0abc797dc
/app/src/main/java/com/example/hansi/finalproject/SinglePostActivity.java
74be97b9036f6790bba841f2a46b873aec18c7e6
[]
no_license
hiphophamster/propertyapp
4d6e199960fa35b7d750d4e24229c4fc7db28ab2
8d37a1b2a0bf8d8906bf9ae299845212f0b8726d
refs/heads/master
2020-03-20T18:25:30.793773
2018-06-22T03:37:25
2018-06-22T03:37:25
137,587,316
0
0
null
null
null
null
UTF-8
Java
false
false
2,927
java
package com.example.hansi.finalproject; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; public class SinglePostActivity extends AppCompatActivity { private ImageView singelImage; private TextView singleTitle, singleDesc; String post_key = null; private DatabaseReference mDatabase; private Button deleteBtn; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_post); singelImage = (ImageView)findViewById(R.id.singleImageview); singleTitle = (TextView)findViewById(R.id.singleTitle); singleDesc = (TextView)findViewById(R.id.singleDesc); mDatabase = FirebaseDatabase.getInstance().getReference().child("HappyHomes"); post_key = getIntent().getExtras().getString("Post ID"); deleteBtn = (Button)findViewById(R.id.deleteBtn); mAuth = FirebaseAuth.getInstance(); deleteBtn.setVisibility(View.INVISIBLE); deleteBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDatabase.child(post_key).removeValue(); Intent mainintent = new Intent(SinglePostActivity.this, MainActivity.class); startActivity(mainintent); } }); mDatabase.child(post_key).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String post_title = (String) dataSnapshot.child("location").getValue(); String post_desc = (String) dataSnapshot.child("desc").getValue(); String post_image = (String) dataSnapshot.child("imageUrl").getValue(); String post_uid = (String) dataSnapshot.child("uid").getValue(); singleTitle.setText(post_title); singleDesc.setText(post_desc); Picasso.get().load(post_image).into(singelImage); if (mAuth.getCurrentUser().getUid().equals(post_uid)) { deleteBtn.setVisibility(View.VISIBLE); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); }}
4dd0f826b6a26df867778c2cdcaff30dbf848b63
36f64eafdf7d702a31a472070d5bea7a7f6dec96
/src/test/java/bellintegrator/training/integration/IntegrationTestOffice.java
874e52da910fd4c5798c9c550cb2daa98ba774f4
[]
no_license
Nemoi2/training_project
cbf04ac87a13995c458be1fb73cec641de42f38a
a14fdb8a06f835c808702240669dd7c016b1768b
refs/heads/master
2021-07-11T14:06:34.495325
2020-01-31T14:33:00
2020-01-31T14:33:00
209,031,370
0
0
null
null
null
null
UTF-8
Java
false
false
5,031
java
package bellintegrator.training.integration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class IntegrationTestOffice { @Autowired private MockMvc mockMvc; @Test public void getOfficeSuccessTest() throws Exception { this.mockMvc.perform(get("/api/office/1")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("{\"data\":{\"id\":1,\"name\":\"Gaz_Penza\"," + "\"address\":\"st. Moscow 1\",\"phone\":null,\"isActive\":true}}"))); } @Test public void getOfficeFailTest() throws Exception { this.mockMvc.perform(get("/api/office/4")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString ("error\":\"Ошибка Сервера: Not found office with id is 4"))); } @Test public void addOfficeSuccessTest() throws Exception { this.mockMvc.perform(post("/api/office/save").contentType(MediaType.APPLICATION_JSON_VALUE) .content("{\"orgId\":\"1\",\"name\":\"name\",\"address\":\"address\",\"phone\":\"1\"," + "\"isActive\":\"false\"}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("{\"data\":{\"result\":\"success\"}}"))); } @Test public void addOfficeFailTest() throws Exception { this.mockMvc.perform(post("/api/office/save").contentType(MediaType.APPLICATION_JSON_VALUE) .content("{\"name\":\"name\",\"address\":\"address\",\"phone\":\"1\",\"isActive\":\"false\"}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("{\"error\":\"Ошибка Сервера:" + " addOffice.officesView.orgId: must not be null\"}"))); } @Test public void updateOfficeSuccessTest() throws Exception { this.mockMvc.perform(post("/api/office/update").contentType(MediaType.APPLICATION_JSON_VALUE) .content("{\"id\":\"3\",\"name\":\"name\",\"address\":\"address\",\"phone\":\"1\"," + "\"isActive\":\"false\"}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("{\"data\":{\"result\":\"success\"}}"))); } @Test public void updateOfficeFailTest() throws Exception { this.mockMvc.perform(post("/api/office/update").contentType(MediaType.APPLICATION_JSON_VALUE) .content("{\"id\":\"5\",\"name\":\"name\",\"address\":\"address\",\"phone\":\"1\"," + "\"isActive\":\"false\"}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("{\"error\":\"Ошибка Сервера:" + " Not found office with id is 5\"}"))); } @Test public void officesSuccessTest() throws Exception { this.mockMvc.perform(post("/api/office/list").contentType(MediaType.APPLICATION_JSON_VALUE) .content("{\"orgId\":\"1\"}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("{\"data\":[{\"id\":1,\"name\":\"Gaz_Penza\"," + "\"isActive\":true},{\"id\":2,\"name\":\"Gaz_Saratov\",\"isActive\":true}]"))); } @Test public void officesFailTest() throws Exception { this.mockMvc.perform(post("/api/office/list").contentType(MediaType.APPLICATION_JSON_VALUE) .content("{\"name\":\"name\",\"isActive\":\"false\"}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("{\"error\":\"Ошибка Сервера:" + " offices.officesView.orgId: must not be null\"}"))); } }
4d704ac919fc6399265263a097c037166da7875d
18da19c1f502f6b39185de0e78d67c4b7b0a09dd
/chat/network/src/main/java/ru/geekbrains/net/MessageSocketThread.java
0f50a6cf4362f660fe5f42acbc72b14a03423fd4
[]
no_license
oshokin/GB_Java_Sem_1_Chap_3
c66eb6241ecda679e9691413042526336f0e07f9
30747599a583941d1c625950d8a1f71f90791ae8
refs/heads/master
2022-12-04T07:20:21.239801
2020-08-31T19:46:52
2020-08-31T19:46:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,042
java
package ru.geekbrains.net; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; public class MessageSocketThread extends Thread { private Socket socket; private MessageSocketThreadListener listener; private DataInputStream in; private DataOutputStream out; private boolean isClosed = false; public MessageSocketThread (MessageSocketThreadListener listener, String name, Socket socket) { super(name); this.socket = socket; this.listener = listener; start(); } @Override public void run() { try { in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); listener.onSocketReady(this); while (!isInterrupted()) { if (!isClosed) { listener.onMessageReceived(this, in.readUTF()); } } } catch (IOException e) { close(); System.out.println(e); } finally { close(); } } public void sendMessage(String message) { try { if (!socket.isConnected() || socket.isClosed() || isClosed) { listener.onException(this, new RuntimeException("Socked closed or not initialized")); return; } if (!isClosed) { out.writeUTF(message); } } catch (IOException e) { close(); listener.onException(this, e); } } public synchronized void close() { isClosed = true; interrupt(); try { if (out != null) { out.close(); } in.close(); } catch (IOException e) { e.printStackTrace(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } listener.onSocketClosed(this); } }
faa4a8eaa2e426388dd9e99642d38a45c695b853
73bfcad4ad5e76df3ee5cb0ec687764527b7c4ab
/src/main/java/com/kodilla/ecommerce/repository/UserEntityRepository.java
4903c74a4c87d152b7dccea8c8f2493b006aee14
[]
no_license
interceptor2048/project-jdp-1906-01
81820dbad95271a1019d9144b14bd876c3aec184
51441d4890ebb01b06709c992e4bbccfa005ddfa
refs/heads/master
2020-06-05T09:09:10.291203
2019-07-15T21:19:26
2019-07-15T21:19:26
192,387,310
2
4
null
2019-07-15T21:19:27
2019-06-17T17:05:39
Java
UTF-8
Java
false
false
436
java
package com.kodilla.ecommerce.repository; import com.kodilla.ecommerce.domain.UserEntity; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface UserEntityRepository extends CrudRepository<UserEntity, Long> { @Override UserEntity save(UserEntity order); Optional<UserEntity> findByUserName(String userName); }
0418dece447a18fa1d72736c3d0d0ee66c02ff74
36cda83983ad64922206fc9932518dea47b04a90
/NewMapelito/src/com/liu/newmapelito/domain/observer/Presenter.java
0c69b7187ee72ea06aa413a227d9b7d842ac5f3a
[]
no_license
JesperNordlund/NewMapelito
2445873894332f76bbdc038b8b23ef2008e7d9db
7d0894b1661a02fd14db3647981b534d022422c3
refs/heads/master
2021-04-30T04:57:20.736204
2018-02-28T14:07:36
2018-02-28T14:07:36
121,404,447
0
0
null
null
null
null
UTF-8
Java
false
false
983
java
package com.liu.newmapelito.domain.observer; import com.liu.newmapelito.domain.Mapelito; import com.liu.newmapelito.domain.Observer; import com.liu.newmapelito.domain.State; import com.liu.newmapelito.domain.Subject; import com.liu.newmapelito.ui.views.AddMapObjectView; import com.liu.newmapelito.ui.views.BrowsingView; public class Presenter implements Observer{ private Subject subject; private static Presenter instance; public static synchronized Presenter getInstance(){ if(instance == null){ instance = new Presenter(); } return instance; } @Override public void update() { if(Mapelito.getInstance().getState().equals(State.addMapObject));{ AddMapObjectView.getInstance().show(); } if(Mapelito.getInstance().getState().equals(State.browsingState)) { BrowsingView.getInstance().show(); } } @Override public void setSubject(Subject sub) { subject = sub; } }
2a4d248b228aa9e9c5c15686a276b66d7b006f32
2d2082fa614ab2b85d12240359d56015214dd6e2
/src/oaidtb/boosters/MulticlassExtensibleBooster.java
f6690a5a00c65c5be5475d91ef01a42f6fc38df4
[]
no_license
sdvillal/oaidtb
6e43f3cfa3566effedb6617d48cb16bbb8842daa
207abef8b384d2583555aa8bb129034ae5b06de1
refs/heads/master
2020-03-27T21:47:43.881211
2018-09-03T08:44:04
2018-09-03T08:44:04
147,176,133
0
0
null
null
null
null
ISO-8859-10
Java
false
false
2,402
java
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * MulticlassExtensibleBooster.java * Copyright (C) 2002 Santiago David Villalba * */ package oaidtb.boosters; import weka.core.Instance; /** * Interface for boosters which can handle binary nominal problems and can * be extended to the multiclass case using a "one-per-class" approach. * * @author <a href="mailto:[email protected]">Santiago David Villalba Bartolom&eacute;</a> * @version $Revision: 1.0 $ */ public interface MulticlassExtensibleBooster{ /** * Must the booster use its own train data copy? * * @param b True if the booster must use its own train data copy. */ void setUseOwnTrainData(boolean b); /** * Return the class predicted (<0 == class 0 and >0 == class 1) and the * confidence of this prediction (its absolute value). * * @param instance The instance to be classified * * @return The class predicted and its confidence. * * @throws Exception if the instance canīt be classified succesfully. */ double confidenceAndSign(Instance instance) throws Exception; /** * Return the class predicted (<0 == class 0 and >0 == class 1) and the * confidence of this prediction (its absolute value) of the classifier indicated. * Similar to Booster.distributionForInstance(instance,classifierIndex). * * @param instance The instance to be classified * @param classifierIndex The classifier's index * * @return The class predicted and its confidence. * * @throws Exception if an error happens. */ double confidenceAndSign(Instance instance, int classifierIndex) throws Exception; }
08b86024ff5de1f06b804c07e6109139613507a2
b3a208cb72e1b450bca8645c9a8e468f99c192da
/robot/src/main/java/com/liberty/robot/LocalRunner.java
395c7f0c1539273c8df2b00d24e2ee77aedb7c73
[]
no_license
dimitrkovalsky/raspberry-robot
5517f31b0f2b2eb90275d1c0eae06cf56266d531
b4a04669dc5fd7a431fcf6d87e6eb5eb116f3265
refs/heads/master
2021-01-23T15:27:50.975788
2015-12-11T15:45:19
2015-12-11T15:45:19
35,216,544
3
0
null
null
null
null
UTF-8
Java
false
false
689
java
package com.liberty.robot; import com.liberty.robot.common.Config; import com.liberty.robot.helpers.ConsoleParser; import com.liberty.robot.helpers.Initializer; import java.io.IOException; /** * User: Dimitr * Date: 21.11.2015 * Time: 18:19 */ public class LocalRunner { public static void main(String[] args) throws IOException { String[] params = {"--ip", "localhost"}; ConsoleParser consoleParser = new ConsoleParser(); if(consoleParser.parse(params)) { System.out.println(Config.show()); } else { System.exit(1); } Initializer initializer = new Initializer(); initializer.initialize(); } }
b8b9ebe0b8a7f63e11776481bd1493e20ca25f24
11ec978d93ea1daf721fa7d47c6da11a7a82b461
/src/test/java/test/clyde/rabbitMqTest/Tester.java
ca6ff25c8df2054130b59403b9c7b54d770e24b2
[]
no_license
germondc/demo-rabbitMq
4c7cb4f23874d8d7303b2f8bb051d2dd08ce8526
d9a68bdcd3251e94d8b7dab18518fc3597883cd0
refs/heads/master
2020-05-16T04:59:46.618220
2019-04-22T13:53:49
2019-04-22T13:53:49
182,797,894
0
0
null
null
null
null
UTF-8
Java
false
false
783
java
package test.clyde.rabbitMqTest; 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.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import test.clyde.rabbitMqTest.Application; import test.clyde.rabbitMqTest.Sender; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @DirtiesContext public class Tester { @Autowired private Sender sender; @Test public void testMessage() { sender.send("wtf"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }
3109584e3265b091f8b2297078a7ac62af6d4d99
43b6de079e043c3d9be20d7ea4d5ac3b7e185e47
/src/main/java/tw/teddysoft/clean/domain/model/kanbanboard/stage/event/SwimLaneCreated.java
08667ca171fb18608b3df84f8598d38734f3afe4
[]
no_license
he89302/study_kanbanboard
3d178acb82e8a8518d3ffc64c836f05d9cbdb27b
35bb80385084e85c0cb8d610760e64f47fbf15b1
refs/heads/master
2022-02-24T05:30:07.713572
2019-10-18T17:10:56
2019-10-18T17:10:56
216,071,558
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
package tw.teddysoft.clean.domain.model.kanbanboard.stage.event; import tw.teddysoft.clean.domain.model.AbstractDomainEvent; public class SwimLaneCreated extends AbstractDomainEvent { public SwimLaneCreated(String id, String name) { super(id, name); } }