hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e00f7c5fd70c597e368ed2c2fc5415361a6b706
2,513
java
Java
aura-impl/src/main/java/org/auraframework/impl/java/type/converter/LocalizedStringToBigDecimalConverter.java
augustyakaravat/aura
98d7ba491172c7ea44cbbf74be5eb858040c9c46
[ "Apache-2.0" ]
587
2015-01-01T00:42:17.000Z
2022-01-23T00:14:13.000Z
aura-impl/src/main/java/org/auraframework/impl/java/type/converter/LocalizedStringToBigDecimalConverter.java
augustyakaravat/aura
98d7ba491172c7ea44cbbf74be5eb858040c9c46
[ "Apache-2.0" ]
156
2015-02-06T17:56:21.000Z
2019-02-27T05:19:11.000Z
aura-impl/src/main/java/org/auraframework/impl/java/type/converter/LocalizedStringToBigDecimalConverter.java
augustyakaravat/aura
98d7ba491172c7ea44cbbf74be5eb858040c9c46
[ "Apache-2.0" ]
340
2015-01-13T14:13:38.000Z
2022-03-21T04:05:29.000Z
26.734043
101
0.66932
401
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.impl.java.type.converter; import java.math.BigDecimal; import java.util.Locale; import javax.inject.Inject; import org.auraframework.adapter.LocalizationAdapter; import org.auraframework.annotations.Annotations.ServiceComponent; import org.auraframework.impl.java.type.LocalizedConverter; import org.auraframework.service.LocalizationService; import org.auraframework.util.AuraLocale; import org.springframework.context.annotation.Lazy; /** * Used by aura.impl.java.type.JavaLocalizedTypeUtil; */ @ServiceComponent public class LocalizedStringToBigDecimalConverter implements LocalizedConverter<String, BigDecimal> { @Inject @Lazy LocalizationAdapter localizationAdapter; @Inject @Lazy LocalizationService localizationService; @Override public BigDecimal convert(String value, AuraLocale locale) { if (value == null || value.isEmpty()) { return null; } if (locale == null) { locale = localizationAdapter.getAuraLocale(); } try { Locale loc = locale.getNumberLocale(); return localizationService.parseBigDecimal(value, loc); } catch (Exception e) { return convert(value); } } @Override public BigDecimal convert(String value) { if (value == null || value.isEmpty()) { return null; } try { return new BigDecimal(value); } catch (NumberFormatException ex) { // fail gracefully, we don't want to bubble an exception here return null; } } @Override public Class<String> getFrom() { return String.class; } @Override public Class<BigDecimal> getTo() { return BigDecimal.class; } @Override public Class<?>[] getToParameters() { return null; } }
3e00f820e80bfe204098fc8bb3b6a894d6ee470f
1,134
java
Java
src/main/java/cn/edu/hust/domain/Top10CategorySession.java
xinwei12/UserActionAnalyzePlatform
16701b6eba08bbf27894fa9cf75fda3bd4e3c9e4
[ "Apache-2.0" ]
795
2018-06-21T14:32:50.000Z
2022-03-25T07:47:07.000Z
src/main/java/cn/edu/hust/domain/Top10CategorySession.java
sumingyue/UserActionAnalyzePlatform
16701b6eba08bbf27894fa9cf75fda3bd4e3c9e4
[ "Apache-2.0" ]
12
2018-06-26T04:04:23.000Z
2022-02-11T02:21:15.000Z
src/main/java/cn/edu/hust/domain/Top10CategorySession.java
sumingyue/UserActionAnalyzePlatform
16701b6eba08bbf27894fa9cf75fda3bd4e3c9e4
[ "Apache-2.0" ]
350
2018-06-26T00:09:15.000Z
2022-03-24T06:01:11.000Z
21.396226
86
0.645503
402
package cn.edu.hust.domain; import java.io.Serializable; public class Top10CategorySession implements Serializable{ private Long taskId; private Long categoryId; private String sessionId; private Long clickCount; public Top10CategorySession() { } public void set(Long taskId, Long categoryId, String sessionId, Long clickCount) { this.taskId = taskId; this.categoryId = categoryId; this.sessionId = sessionId; this.clickCount = clickCount; } public Long getTaskId() { return taskId; } public void setTaskId(Long taskId) { this.taskId = taskId; } public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Long getClickCount() { return clickCount; } public void setClickCount(Long clickCount) { this.clickCount = clickCount; } }
3e00f859d8edd950c0e4a17fcda10f637eb596ed
3,727
java
Java
org/apache/xml/utils/ElemDesc.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
2
2021-07-16T10:43:25.000Z
2021-12-15T13:54:10.000Z
org/apache/xml/utils/ElemDesc.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
1
2021-10-12T22:24:55.000Z
2021-10-12T22:24:55.000Z
org/apache/xml/utils/ElemDesc.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
null
null
null
19.310881
88
0.30051
403
/* */ package org.apache.xml.utils; /* */ /* */ import java.util.Hashtable; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ class ElemDesc /* */ { /* 32 */ Hashtable m_attrs = null; /* */ /* */ /* */ /* */ int m_flags; /* */ /* */ /* */ /* */ static final int EMPTY = 2; /* */ /* */ /* */ /* */ static final int FLOW = 4; /* */ /* */ /* */ /* */ static final int BLOCK = 8; /* */ /* */ /* */ /* */ static final int BLOCKFORM = 16; /* */ /* */ /* */ /* */ static final int BLOCKFORMFIELDSET = 32; /* */ /* */ /* */ /* */ static final int CDATA = 64; /* */ /* */ /* */ /* */ static final int PCDATA = 128; /* */ /* */ /* */ /* */ static final int RAW = 256; /* */ /* */ /* */ /* */ static final int INLINE = 512; /* */ /* */ /* */ static final int INLINEA = 1024; /* */ /* */ /* */ static final int INLINELABEL = 2048; /* */ /* */ /* */ static final int FONTSTYLE = 4096; /* */ /* */ /* */ static final int PHRASE = 8192; /* */ /* */ /* */ static final int FORMCTRL = 16384; /* */ /* */ /* */ static final int SPECIAL = 32768; /* */ /* */ /* */ static final int ASPECIAL = 65536; /* */ /* */ /* */ static final int HEADMISC = 131072; /* */ /* */ /* */ static final int HEAD = 262144; /* */ /* */ /* */ static final int LIST = 524288; /* */ /* */ /* */ static final int PREFORMATTED = 1048576; /* */ /* */ /* */ static final int WHITESPACESENSITIVE = 2097152; /* */ /* */ /* */ static final int ATTRURL = 2; /* */ /* */ /* */ static final int ATTREMPTY = 4; /* */ /* */ /* */ /* */ ElemDesc(int flags) { /* 119 */ this.m_flags = flags; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ boolean is(int flags) { /* 142 */ return ((this.m_flags & flags) != 0); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ void setAttr(String name, int flags) { /* 155 */ if (null == this.m_attrs) { /* 156 */ this.m_attrs = new Hashtable(); /* */ } /* 158 */ this.m_attrs.put(name, new Integer(flags)); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ boolean isAttrFlagSet(String name, int flags) { /* 175 */ if (null != this.m_attrs) { /* */ /* 177 */ Integer _flags = (Integer)this.m_attrs.get(name); /* */ /* 179 */ if (null != _flags) /* */ { /* 181 */ return ((_flags.intValue() & flags) != 0); /* */ } /* */ } /* */ /* 185 */ return false; /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/xml/utils/ElemDesc.class * Java compiler version: 1 (45.3) * JD-Core Version: 1.1.3 */
3e00f9e6e5047857b93d2ed908d6b948a7f200fb
1,239
java
Java
qaDocker/src-gen/xtext/qactor/qADocker/Reaction.java
sabbio93/QDocker
dabc8492ccfb2267070122ad03263c7e464ba051
[ "MIT" ]
null
null
null
qaDocker/src-gen/xtext/qactor/qADocker/Reaction.java
sabbio93/QDocker
dabc8492ccfb2267070122ad03263c7e464ba051
[ "MIT" ]
null
null
null
qaDocker/src-gen/xtext/qactor/qADocker/Reaction.java
sabbio93/QDocker
dabc8492ccfb2267070122ad03263c7e464ba051
[ "MIT" ]
null
null
null
27.533333
85
0.626312
404
/** * generated by Xtext 2.10.0 */ package xtext.qactor.qADocker; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Reaction</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link xtext.qactor.qADocker.Reaction#getAlarms <em>Alarms</em>}</li> * </ul> * * @see xtext.qactor.qADocker.QADockerPackage#getReaction() * @model * @generated */ public interface Reaction extends EObject { /** * Returns the value of the '<em><b>Alarms</b></em>' containment reference list. * The list contents are of type {@link xtext.qactor.qADocker.AlarmEvent}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Alarms</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Alarms</em>' containment reference list. * @see xtext.qactor.qADocker.QADockerPackage#getReaction_Alarms() * @model containment="true" * @generated */ EList<AlarmEvent> getAlarms(); } // Reaction
3e00fc874912d7ca0965097086f66cf95f98ed43
2,220
java
Java
app/src/main/java/com/chenmaunion/app/cmdriver/ui/activity/OrderDetailActivity.java
wangwenwang/CMDriver_Android
5a9c56367dd40ff2b21c4b329885c4e8a0791a7a
[ "MIT" ]
1
2019-12-12T16:35:05.000Z
2019-12-12T16:35:05.000Z
app/src/main/java/com/chenmaunion/app/cmdriver/ui/activity/OrderDetailActivity.java
wangwenwang/CMDriver_Android
5a9c56367dd40ff2b21c4b329885c4e8a0791a7a
[ "MIT" ]
null
null
null
app/src/main/java/com/chenmaunion/app/cmdriver/ui/activity/OrderDetailActivity.java
wangwenwang/CMDriver_Android
5a9c56367dd40ff2b21c4b329885c4e8a0791a7a
[ "MIT" ]
null
null
null
46.25
113
0.767117
405
package com.chenmaunion.app.cmdriver.ui.activity; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import com.chenmaunion.app.cmdriver.R; import com.chenmaunion.app.cmdriver.adapter.DBOrderDetailSimpleAdapter; import com.chenmaunion.app.cmdriver.bean.order.Order; import com.chenmaunion.app.cmdriver.databinding.ActivityOrderdetailBinding; import com.chenmaunion.app.cmdriver.ui.base.BaseActivity; import com.chenmaunion.app.cmdriver.viewmodel.DBModel_Order; import com.chenmaunion.app.cmdriver.viewmodel.DBModel_OrderDetail; import com.kaidongyuan.app.basemodule.interfaces.AsyncHttpCallback; import com.kaidongyuan.app.basemodule.ui.fragmentactivity.BaseToastDialogFragmentActivity; import com.kaidongyuan.app.basemodule.widget.SlidingTitleView; /** * ${PEOJECT_NAME} * Created by Administrator on 2017/2/9. */ public class OrderDetailActivity extends BaseActivity { private String order_id,ispay; public DBOrderDetailSimpleAdapter orderDetailSimpleAdapter; public SlidingTitleView titleView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent=getIntent(); if (intent.hasExtra("ispay")&&intent.hasExtra("order_id")){ order_id=intent.getStringExtra("order_id"); ispay=intent.getStringExtra("ispay"); }else { finish(); } ActivityOrderdetailBinding binding= DataBindingUtil.setContentView(this, R.layout.activity_orderdetail); binding.setModel(new DBModel_OrderDetail(this,order_id,ispay)); LinearLayoutManager manager=new LinearLayoutManager(OrderDetailActivity.this); manager.setOrientation(LinearLayoutManager.VERTICAL); binding.recyclerviewDetails.setLayoutManager(manager); orderDetailSimpleAdapter=new DBOrderDetailSimpleAdapter(); binding.recyclerviewDetails.setAdapter(orderDetailSimpleAdapter); binding.titleOrderdetailActivtiy.setMode(SlidingTitleView.MODE_BACK); binding.titleOrderdetailActivtiy.setText("订单详情"); } }
3e00fcaf8898caee515db0fbe080c621d17744a7
3,574
java
Java
app/examples/animal/forest/chat/NetworkActivity.java
isabella232/chat-examples-java
db4e276afaaeeedb273f2e50269b93e029d8660b
[ "MIT" ]
7
2019-07-26T16:27:12.000Z
2021-12-14T08:24:44.000Z
app/examples/animal/forest/chat/NetworkActivity.java
pubnub/chat-examples-java
db4e276afaaeeedb273f2e50269b93e029d8660b
[ "MIT" ]
4
2019-06-29T11:34:12.000Z
2020-09-29T20:06:10.000Z
app/examples/animal/forest/chat/NetworkActivity.java
isabella232/chat-examples-java
db4e276afaaeeedb273f2e50269b93e029d8660b
[ "MIT" ]
10
2019-07-03T06:26:31.000Z
2021-06-24T21:02:14.000Z
35.386139
105
0.682429
406
package animal.forest.chat; import android.app.Activity; import android.content.Context; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.preference.PreferenceManager; import android.widget.Toast; import animal.forest.chat.services.NetworkReceiver; public class NetworkActivity extends Activity { public static final String WIFI = "Wi-Fi"; public static final String ANY = "Any"; private static final String URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort;=newest"; // Whether there is a Wi-Fi connection. private static boolean wifiConnected = false; // Whether there is a mobile connection. private static boolean mobileConnected = false; // Whether the display should be refreshed. public static boolean refreshDisplay = true; // The user's current network preference setting. public static String sPref = null; // The BroadcastReceiver that tracks network connectivity changes. private NetworkReceiver receiver = new NetworkReceiver(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Registers BroadcastReceiver to track network connection changes. IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); receiver = new NetworkReceiver(); this.registerReceiver(receiver, filter); } @Override public void onDestroy() { super.onDestroy(); // Unregisters BroadcastReceiver when app is destroyed. if (receiver != null) { this.unregisterReceiver(receiver); } } // Refreshes the display if the network connection and the // pref settings allow it. @Override public void onStart() { super.onStart(); // Gets the user's network preference settings SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // Retrieves a string value for the preferences. The second parameter // is the default value to use if a preference value is not found. sPref = sharedPrefs.getString("listPref", "Wi-Fi"); updateConnectedFlags(); if (refreshDisplay) { loadPage(); } } // Checks the network connection and sets the wifiConnected and mobileConnected // variables accordingly. public void updateConnectedFlags() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeInfo = connMgr.getActiveNetworkInfo(); if (activeInfo != null && activeInfo.isConnected()) { wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI; mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE; } else { wifiConnected = false; mobileConnected = false; } } // Uses AsyncTask subclass to download the XML feed from stackoverflow.com. public void loadPage() { if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected)) || ((sPref.equals(WIFI)) && (wifiConnected))) { // AsyncTask subclass Toast.makeText(this, "new DownloadXmlTask().execute(URL);", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "showErrorPage();", Toast.LENGTH_SHORT).show(); } } }
3e00fd584c1abc68909d75dfe4a9310f542f3077
9,627
java
Java
app/src/main/java/uca/ruiz/antonio/tfgapp/ui/adapter/PacienteAdapter.java
toninoes/tfg-heridas-rest-cliente-android
53fffcc7e6a2c29a330fbceae3a67541b662c680
[ "MIT" ]
7
2018-10-24T15:37:23.000Z
2021-03-26T09:02:40.000Z
app/src/main/java/uca/ruiz/antonio/tfgapp/ui/adapter/PacienteAdapter.java
toninoes/tfg-heridas-rest-cliente-android
53fffcc7e6a2c29a330fbceae3a67541b662c680
[ "MIT" ]
null
null
null
app/src/main/java/uca/ruiz/antonio/tfgapp/ui/adapter/PacienteAdapter.java
toninoes/tfg-heridas-rest-cliente-android
53fffcc7e6a2c29a330fbceae3a67541b662c680
[ "MIT" ]
1
2020-04-04T04:23:41.000Z
2020-04-04T04:23:41.000Z
41.49569
109
0.604965
407
package uca.ruiz.antonio.tfgapp.ui.adapter; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import es.dmoral.toasty.Toasty; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import uca.ruiz.antonio.tfgapp.R; import uca.ruiz.antonio.tfgapp.data.Preferencias; import uca.ruiz.antonio.tfgapp.data.api.io.MyApiAdapter; import uca.ruiz.antonio.tfgapp.data.api.mapping.ApiError; import uca.ruiz.antonio.tfgapp.data.api.model.Paciente; import uca.ruiz.antonio.tfgapp.ui.activity.PacienteActivity; import uca.ruiz.antonio.tfgapp.ui.activity.PacienteNewEditActivity; import uca.ruiz.antonio.tfgapp.ui.activity.ProcesosActivity; import uca.ruiz.antonio.tfgapp.utils.Pref; import static android.content.ContentValues.TAG; public class PacienteAdapter extends RecyclerView.Adapter<PacienteAdapter.ViewHolder> { private ArrayList<Paciente> mDataSet; private Context context; // Obtener referencias de los componentes visuales para cada elemento // es decir, referencias de los EditText, TextView, Button... public static class ViewHolder extends RecyclerView.ViewHolder { private LinearLayout ll_item; private TextView tv_titulo; private TextView tv_subtitulo; private ImageButton ib_delete; private ImageButton ib_edit; private ImageButton ib_asistir; public ViewHolder(View v) { super(v); ll_item = (LinearLayout) v.findViewById(R.id.ll_item); tv_titulo = (TextView) v.findViewById(R.id.tv_titulo); tv_subtitulo = (TextView) v.findViewById(R.id.tv_subtitulo); ib_delete = (ImageButton) v.findViewById(R.id.ib_delete); ib_delete.setVisibility(View.GONE); // no borrar usuarios (desactivarlos) ib_edit = (ImageButton) v.findViewById(R.id.ib_edit); ib_asistir = (ImageButton) v.findViewById(R.id.ib_asistir); if(Preferencias.get(v.getContext()).getBoolean("ROLE_SANITARIO", false)) ib_asistir.setVisibility(View.VISIBLE); } } public PacienteAdapter(Context context) { this.context = context; mDataSet = new ArrayList<>(); } public void setDataSet(ArrayList<Paciente> dataSet) { mDataSet = dataSet; notifyDataSetChanged(); } // Encargado de crear los nuevos objetos ViewHolder necesarios para los elementos de la // colección. El LayoutManager invoca este metodo para renderizar cada elemento del RecyclerView @Override public PacienteAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { View elemento = LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.elemento_listado_crud, viewGroup, false); return new ViewHolder(elemento); } // Encargado de actualizar los datos de un ViewHolder ya existente. Reemplaza el contenido de // cada view, para cada elemento de la lista. @Override public void onBindViewHolder(final ViewHolder holder, int position) { // obtenemos un elemento del dataset según su posición // reemplazamos el contenido de los views según tales datos Paciente paciente = mDataSet.get(position); holder.tv_titulo.setText(paciente.getLastnameComaAndFirstname()); holder.tv_subtitulo.setText(paciente.getDni()); // click sobre cada elemento holder.ll_item.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int pos = holder.getAdapterPosition(); Paciente paciente = mDataSet.get(pos); Intent intent = new Intent(context, PacienteActivity.class); intent.putExtra("paciente", paciente); context.startActivity(intent); } }); // para borrar el elemento holder.ib_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(context); // Establecer un título para el diálogo de alerta builder.setTitle(R.string.seleccione_opcion); // Preguntar si desea realizar la acción builder.setMessage(R.string.quiere_borrar); // Establecer listener para el click de los botones de diálogo de alerta DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch(which){ case DialogInterface.BUTTON_POSITIVE: // Usuario confirma la acción int pos = holder.getAdapterPosition(); Paciente paciente = mDataSet.get(pos); borrarPaciente(paciente.getId(), pos); break; case DialogInterface.BUTTON_NEGATIVE: // Usuario no confirma la acción dialog.cancel(); break; } } }; // Establecer el mensaje sobre el botón BUTTON_POSITIVE builder.setPositiveButton(R.string.si, dialogClickListener); // Establecer el mensaje sobre el botón BUTTON_NEGATIVE builder.setNegativeButton(R.string.no,dialogClickListener); AlertDialog dialog = builder.create(); // Mostrar el diálogo de alerta dialog.show(); } }); // para editar un elemento holder.ib_edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int pos = holder.getAdapterPosition(); Paciente paciente = mDataSet.get(pos); Intent intent = new Intent(context, PacienteNewEditActivity.class); intent.putExtra("paciente", paciente); context.startActivity(intent); } }); // ver/añadir/editar procesos de un paciente dado holder.ib_asistir.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int pos = holder.getAdapterPosition(); Paciente paciente = mDataSet.get(pos); Intent intent = new Intent(context, ProcesosActivity.class); intent.putExtra("paciente", paciente); context.startActivity(intent); } }); } // Indica el número de elementos de la colección de datos. @Override public int getItemCount() { // si es despues de filtrar, aqui hay que hacer cosas diferentes, // calculando entonces el tamaño del dataset tras el filtrado. return mDataSet.size(); } private void borrarPaciente(final long id, final int pos) { Call<String> call = MyApiAdapter.getApiService().borrarPaciente(id, Pref.getToken()); call.enqueue(new Callback<String>() { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { if(response.isSuccessful()) { mDataSet.remove(pos); notifyItemRemoved(pos); Toasty.success(context, context.getString(R.string.borrado_registro), Toast.LENGTH_SHORT, true).show(); } else { if (response.errorBody().contentType().subtype().equals("json")) { ApiError apiError = ApiError.fromResponseBody(response.errorBody()); if (apiError != null) { Toasty.error(context, apiError.getMessage(), Toast.LENGTH_LONG, true).show(); Log.d(TAG, apiError.getPath() + " " + apiError.getMessage()); } } else { try { Log.d(TAG, response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } } @Override public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { if (t instanceof IOException) { Toasty.warning(context, context.getString(R.string.error_conexion_red), Toast.LENGTH_LONG, true).show(); } else { Toasty.error(context, context.getString(R.string.error_conversion), Toast.LENGTH_LONG, true).show(); Log.d(TAG, context.getString(R.string.error_conversion)); } } }); } }
3e00fda4e6fcf0161ce7023dda52e4e15a731516
5,463
java
Java
spackleLib/src/main/java/com/twofortyfouram/spackle/ResourceUtil.java
twofortyfouram-private/android-monorepo
4023d30d5b44b2fd15206c3435829e999e7bbd02
[ "Apache-2.0" ]
5
2019-04-08T21:58:11.000Z
2022-01-12T15:02:30.000Z
spackleLib/src/main/java/com/twofortyfouram/spackle/ResourceUtil.java
twofortyfouram/android-monorepo
f17241cb8f622cd48e0f37a44609e871391292fa
[ "Apache-2.0" ]
null
null
null
spackleLib/src/main/java/com/twofortyfouram/spackle/ResourceUtil.java
twofortyfouram/android-monorepo
f17241cb8f622cd48e0f37a44609e871391292fa
[ "Apache-2.0" ]
null
null
null
36.42
97
0.640124
408
/* * android-spackle * https://github.com/twofortyfouram/android-monorepo * Copyright (C) 2008–2018 two forty four a.m. LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.twofortyfouram.spackle; import android.content.Context; import android.content.res.TypedArray; import androidx.annotation.*; import net.jcip.annotations.ThreadSafe; import java.util.NoSuchElementException; import static com.twofortyfouram.assertion.Assertions.assertNotEmpty; import static com.twofortyfouram.assertion.Assertions.assertNotNull; /** * Utilities for interaction with Android application resources. */ @ThreadSafe public final class ResourceUtil { /** * Gets the first position of an element in a typed array. * * @param context Application context. * @param arrayId resource ID of the array. * @param elementId resource ID of the element in the array to find. If this id is repeated, * only * position of the first instance will be returned. * @return position of the {@code elementId} in the array. * @throws NoSuchElementException if {@code elementId} is not in the array. */ public static int getPositionForIdInArray(@NonNull final Context context, @ArrayRes final int arrayId, @AnyRes final int elementId) { assertNotNull(context, "context"); //$NON-NLS-1$ TypedArray array = null; try { array = context.getResources().obtainTypedArray(arrayId); for (int x = 0; x < array.length(); x++) { if (array.getResourceId(x, 0) == elementId) { return x; } } } finally { if (null != array) { array.recycle(); array = null; } } throw new NoSuchElementException(); } /** * Gets the resource ID of an element in a typed array. * * @param context Application context. * @param arrayId resource ID of the array. * @param position position in the array to retrieve. * @return resource id of element in {@code position}. * @throws IndexOutOfBoundsException if {@code position} is not in the array. */ public static int getResourceIdForPositionInArray(@NonNull final Context context, @ArrayRes final int arrayId, final int position) { assertNotNull(context, "context"); //$NON-NLS-1$ TypedArray stateArray = null; try { stateArray = context.getResources().obtainTypedArray(arrayId); final int selectedResourceId = stateArray.getResourceId(position, 0); if (0 == selectedResourceId) { throw new IndexOutOfBoundsException(); } return selectedResourceId; } finally { if (null != stateArray) { stateArray.recycle(); stateArray = null; } } } /** * Returns a resource from a string name, rather than an integer ID. * * @param context Application context. * @param resourceName Name of the resource to retrieve. * @return The value mapping to {@code resourceName}. * @throws android.content.res.Resources.NotFoundException if the resource doesn't exist. */ public static boolean getBoolean(@NonNull final Context context, @NonNull final String resourceName) { assertNotNull(context, "context"); //$NON-NLS-1$ assertNotEmpty(resourceName, "resourceName"); //$NON-NLS-1$ @BoolRes final int id = context.getResources().getIdentifier(resourceName, "bool", context.getPackageName()); //$NON-NLS-1$ return context.getResources().getBoolean(id); } /** * Returns a resource from a string name, rather than an integer ID. * * @param context Application context. * @param resourceName Name of the resource to retrieve. * @return The value mapping to {@code resourceName}. * @throws android.content.res.Resources.NotFoundException if the resource doesn't exist. */ @NonNull public static String getString(@NonNull final Context context, @NonNull final String resourceName) { assertNotNull(context, "context"); //$NON-NLS-1$ assertNotEmpty(resourceName, "resourceName"); //$NON-NLS-1$ @StringRes final int id = context.getResources().getIdentifier(resourceName, "string", context.getPackageName()); //$NON-NLS-1$ return context.getResources().getString(id); } /** * Private constructor prevents instantiation. * * @throws UnsupportedOperationException because this class cannot be instantiated. */ private ResourceUtil() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } }
3e00fde7345421201802ca351874c2094128a5b0
457
java
Java
odl/sina-gossip/impl/src/main/java/org/opendaylight/sina/impl/models/InforControllerModel.java
NguyenNghia412/kcsg
07345845ff64d722c0a6e3fa3fa08f5194f2661a
[ "Apache-2.0" ]
null
null
null
odl/sina-gossip/impl/src/main/java/org/opendaylight/sina/impl/models/InforControllerModel.java
NguyenNghia412/kcsg
07345845ff64d722c0a6e3fa3fa08f5194f2661a
[ "Apache-2.0" ]
null
null
null
odl/sina-gossip/impl/src/main/java/org/opendaylight/sina/impl/models/InforControllerModel.java
NguyenNghia412/kcsg
07345845ff64d722c0a6e3fa3fa08f5194f2661a
[ "Apache-2.0" ]
null
null
null
32.642857
86
0.757112
409
/* * Copyright © 2021 Copyright (c) 2021 Yoyodyne, Inc and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.sina.impl.models; public class InforControllerModel { public String kindController; public String ip; }
3e00fdff04fed67557ba58f72ae1bdb665476f58
1,595
java
Java
server/src/main/java/com/mola/molachat/robot/bus/RobotEventBusRegistry.java
molamolaxxx/molachat
698708a331279aaaf8dc71c912ad2658f903f49f
[ "Apache-2.0" ]
4
2019-09-24T06:57:30.000Z
2019-10-29T02:23:03.000Z
server/src/main/java/com/mola/molachat/robot/bus/RobotEventBusRegistry.java
molamolaxxx/molachat
698708a331279aaaf8dc71c912ad2658f903f49f
[ "Apache-2.0" ]
null
null
null
server/src/main/java/com/mola/molachat/robot/bus/RobotEventBusRegistry.java
molamolaxxx/molachat
698708a331279aaaf8dc71c912ad2658f903f49f
[ "Apache-2.0" ]
1
2021-08-06T01:37:49.000Z
2021-08-06T01:37:49.000Z
30.09434
101
0.70721
410
package com.mola.molachat.robot.bus; import com.mola.molachat.data.ChatterFactoryInterface; import com.mola.molachat.entity.Chatter; import com.mola.molachat.entity.RobotChatter; import com.mola.molachat.event.base.BaseEventBusRegistry; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import javax.annotation.Resource; /** * @author : molamola * @Project: molachat * @Description: * @date : 2020-12-07 15:33 **/ @Component @Slf4j public class RobotEventBusRegistry extends BaseEventBusRegistry<RobotEventBus> { @Resource private ChatterFactoryInterface chatterFactory; @Override public void register(String chatterId, RobotEventBus eventBus) { Assert.notNull(eventBus, "总线不能为空"); Assert.isTrue(!StringUtils.isEmpty(chatterId), "chatterId不能为空"); // 2、查询是否存在robot Chatter chatter = chatterFactory.select(chatterId); if (null == chatter || !(chatter instanceof RobotChatter)) { log.error("[RobotEventBusRegistry$register]chatter不存在或不为机器人, chatterId = {}", chatterId); return; } super.register(chatterId, eventBus); } /** * 获取总线 * @param chatterId * @return */ @Override public RobotEventBus getEventBus(String chatterId) { Assert.isTrue(!StringUtils.isEmpty(chatterId), "chatterId不能为空"); RobotEventBus eventBus = super.getEventBus(chatterId); Assert.notNull(eventBus, "未找到总线"); return eventBus; } }
3e00fe63f5575c505a8c5e9801e7327951c09dab
1,129
java
Java
src/buildings/Stable.java
aboueleyes/the-conqueror
b163b2df22c2cc4ec3bb8af4d5087da44e9abe0f
[ "MIT" ]
13
2021-06-30T14:54:30.000Z
2022-01-20T15:37:50.000Z
src/buildings/Stable.java
aboueleyes/the-conqueror
b163b2df22c2cc4ec3bb8af4d5087da44e9abe0f
[ "MIT" ]
2
2021-07-05T18:00:55.000Z
2022-03-12T20:50:50.000Z
src/buildings/Stable.java
aboueleyes/the-conqueror
b163b2df22c2cc4ec3bb8af4d5087da44e9abe0f
[ "MIT" ]
9
2021-06-30T17:06:38.000Z
2022-01-30T21:49:22.000Z
28.225
83
0.74845
411
package buildings; import exceptions.BuildingInCoolDownException; import exceptions.MaxLevelException; import exceptions.MaxRecruitedException; import units.Cavalry; import units.Unit; public class Stable extends MilitaryBuilding { private static final int STABLE_COST = 2500; private static final int[] STABLE_UPGRADE_COST = { 1500, 2000 }; private static final int[] STABLE_RECRUITMENT_COST = { 600, 650, 700 }; public Stable() { super(STABLE_COST, STABLE_UPGRADE_COST[0], STABLE_RECRUITMENT_COST[0]); } @Override public void upgrade() throws BuildingInCoolDownException, MaxLevelException { super.upgrade(); updateCosts(STABLE_UPGRADE_COST, STABLE_RECRUITMENT_COST); } @Override public Unit recruit() throws BuildingInCoolDownException, MaxRecruitedException { if (isCoolDown()) { throw new BuildingInCoolDownException("Building is cooling down"); } if (getCurrentRecruit() == getMaxRecruit()) { throw new MaxRecruitedException("You have reached the max recruit"); } setCurrentRecruit(getCurrentRecruit() + 1); return new Cavalry(getLevel()); } }
3e00ff2acad21265e17072c7d8f05293d7c0b44f
3,984
java
Java
src/main/java/ca/rttv/mindfuleating/mixin/PlayerEntityMixin.java
RealRTTV/Mindful-Eating-Fabrique
5241ba998ade5e59c333c182d4c850e03ca7f3b7
[ "CC0-1.0" ]
1
2021-12-21T21:51:35.000Z
2021-12-21T21:51:35.000Z
src/main/java/ca/rttv/mindfuleating/mixin/PlayerEntityMixin.java
RealRTTV/Mindful-Eating-Fabrique
5241ba998ade5e59c333c182d4c850e03ca7f3b7
[ "CC0-1.0" ]
null
null
null
src/main/java/ca/rttv/mindfuleating/mixin/PlayerEntityMixin.java
RealRTTV/Mindful-Eating-Fabrique
5241ba998ade5e59c333c182d4c850e03ca7f3b7
[ "CC0-1.0" ]
null
null
null
69.894737
373
0.760291
412
package ca.rttv.mindfuleating.mixin; import ca.rttv.mindfuleating.ExhaustionType; import ca.rttv.mindfuleating.FoodGroups; import ca.rttv.mindfuleating.MindfulEating; import ca.rttv.mindfuleating.configs.Configs; import io.netty.buffer.Unpooled; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.network.PacketByteBuf; import net.minecraft.server.network.ServerPlayerEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.Slice; @Mixin( PlayerEntity.class ) abstract class PlayerEntityMixin { PlayerEntity player = (PlayerEntity) (Object) this; // hitting check @ModifyArg( method = "attack", at = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;addExhaustion(F)V" ), index = 0 ) private float attack(float originalExhaustion) { PacketByteBuf packet = new PacketByteBuf(Unpooled.buffer()); packet.writeInt(ExhaustionType.ATTACK.bonusSheenTicks); ServerPlayNetworking.send((ServerPlayerEntity) player, MindfulEating.MindfulEatingSheenS2CPacket, packet); return FoodGroups.shouldReceiveBuffs(ExhaustionType.ATTACK) ? originalExhaustion * (1 - Configs.getJsonObject().get("exhaustionReductionAsDecimal").getAsFloat()) : originalExhaustion; } // check for when hit to take less exhaustion @ModifyArg( method = "applyDamage", at = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;addExhaustion(F)V" ), index = 0 ) private float damage(float originalExhaustion) { PacketByteBuf packet = new PacketByteBuf(Unpooled.buffer()); packet.writeInt(ExhaustionType.HURT.bonusSheenTicks); ServerPlayNetworking.send((ServerPlayerEntity) player, MindfulEating.MindfulEatingSheenS2CPacket, packet); return FoodGroups.shouldReceiveBuffs(ExhaustionType.HURT) ? originalExhaustion * (1 - Configs.getJsonObject().get("exhaustionReductionAsDecimal").getAsFloat()) : originalExhaustion; } // jumping check @ModifyArg( method = "jump", at = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;addExhaustion(F)V" ), index = 0 ) private float jumpWithSprint(float originalExhaustion) { return FoodGroups.shouldReceiveBuffs(ExhaustionType.JUMP) ? originalExhaustion * (1 - Configs.getJsonObject().get("exhaustionReductionAsDecimal").getAsFloat()) : originalExhaustion; } // this is walking @ModifyArg( method = "increaseTravelMotionStats", slice = @Slice( from = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;isClimbing()Z" ), to = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;isFallFlying()Z" ) ), at = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;addExhaustion(F)V" ) ) private float sprintingAddExhaustion(float originalExhaustion) { return FoodGroups.shouldReceiveBuffs(ExhaustionType.WALKING) ? originalExhaustion * (1 - Configs.getJsonObject().get("exhaustionReductionAsDecimal").getAsFloat()) : originalExhaustion; } // slice is epic (I had to use a slice to get a slice of the exhaustion system for water and air), this is water @ModifyArg( method = "increaseTravelMotionStats", slice = @Slice( from = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;isSwimming()Z" ), to = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;isClimbing()Z" ) ), at = @At( value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;addExhaustion(F)V" ) ) private float underwaterAddExhaustion(float originalExhaustion) { return FoodGroups.shouldReceiveBuffs(ExhaustionType.SWIMMING) ? originalExhaustion * (1 - Configs.getJsonObject().get("exhaustionReductionAsDecimal").getAsFloat()) : originalExhaustion; } }
3e00ff347d79ecb525733577dd8e25d85dd143f8
1,633
java
Java
sdk/src/test/java/com/hedera/hashgraph/sdk/ContractCreateTransactionTest.java
si618/hedera-sdk-java
ab8e7a8a2db506b2cda855b0eec67d84928bdf45
[ "Apache-2.0" ]
1
2021-05-28T18:44:20.000Z
2021-05-28T18:44:20.000Z
sdk/src/test/java/com/hedera/hashgraph/sdk/ContractCreateTransactionTest.java
si618/hedera-sdk-java
ab8e7a8a2db506b2cda855b0eec67d84928bdf45
[ "Apache-2.0" ]
null
null
null
sdk/src/test/java/com/hedera/hashgraph/sdk/ContractCreateTransactionTest.java
si618/hedera-sdk-java
ab8e7a8a2db506b2cda855b0eec67d84928bdf45
[ "Apache-2.0" ]
null
null
null
34.744681
108
0.698102
413
package com.hedera.hashgraph.sdk; import io.github.jsonSnapshot.SnapshotMatcher; import org.junit.AfterClass; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.threeten.bp.Duration; import org.threeten.bp.Instant; import java.util.Collections; public class ContractCreateTransactionTest { private static final PrivateKey unusedPrivateKey = PrivateKey.fromString( "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10"); final Instant validStart = Instant.ofEpochSecond(1554158542); @BeforeAll public static void beforeAll() { SnapshotMatcher.start(); } @AfterClass public static void afterAll() { SnapshotMatcher.validateSnapshots(); } @Test void shouldSerialize() { SnapshotMatcher.expect(new ContractCreateTransaction() .setNodeAccountIds(Collections.singletonList(AccountId.fromString("0.0.5005"))) .setTransactionId(TransactionId.withValidStart(AccountId.fromString("0.0.5006"), validStart)) .setBytecodeFileId(FileId.fromString("0.0.3003")) .setAdminKey(unusedPrivateKey) .setGas(0) .setInitialBalance(Hbar.fromTinybars(1000)) .setProxyAccountId(AccountId.fromString("0.0.1001")) .setAutoRenewPeriod(Duration.ofHours(10)) .setConstructorParameters(new byte[]{10, 11, 12, 13, 25}) .setMaxTransactionFee(Hbar.fromTinybars(100_000)) .freeze() .sign(unusedPrivateKey) .toString() ).toMatchSnapshot(); } }
3e01005a125004e2b8c98486bb719e55fca80fdd
3,565
java
Java
jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/PipelineMavenPluginNullDao.java
tneer/pipeline-maven-plugin
ea087d5e3491a815a8fcc65a2e41be2696eff2ee
[ "MIT" ]
null
null
null
jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/PipelineMavenPluginNullDao.java
tneer/pipeline-maven-plugin
ea087d5e3491a815a8fcc65a2e41be2696eff2ee
[ "MIT" ]
2
2021-02-03T19:37:14.000Z
2022-01-21T23:47:13.000Z
jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/dao/PipelineMavenPluginNullDao.java
tneer/pipeline-maven-plugin
ea087d5e3491a815a8fcc65a2e41be2696eff2ee
[ "MIT" ]
null
null
null
32.454545
253
0.738936
414
/* * The MIT License * * Copyright (c) 2016, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.pipeline.maven.dao; import org.jenkinsci.plugins.pipeline.maven.MavenArtifact; import org.jenkinsci.plugins.pipeline.maven.MavenDependency; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; /** * @author <a href="mailto:[email protected]">Cyrille Le Clerc</a> */ public class PipelineMavenPluginNullDao implements PipelineMavenPluginDao { @Override public void recordDependency(String jobFullName, int buildNumber, String groupId, String artifactId, String version, String type, String scope, boolean ignoreUpstreamTriggers, String classifier) { } @Nonnull @Override public List<MavenDependency> listDependencies(@Nonnull String jobFullName, int buildNumber) { return Collections.emptyList(); } @Override public void recordParentProject(@Nonnull String jobFullName, int buildNumber, @Nonnull String parentGroupId, @Nonnull String parentArtifactId, @Nonnull String parentVersion, boolean ignoreUpstreamTriggers) { } @Override public void recordGeneratedArtifact(String jobFullName, int buildNumber, String groupId, String artifactId, String version, String type, String baseVersion, String repositoryUrl, boolean skipDownstreamTriggers, String extension, String classifier) { } @Override public void renameJob(String oldFullName, String newFullName) { } @Override public void deleteJob(String jobFullName) { } @Override public void deleteBuild(String jobFullName, int buildNumber) { } @Nonnull @Override public List<String> listDownstreamJobs(@Nonnull String jobFullName, int buildNumber) { return Collections.emptyList(); } @Nonnull @Override public Map<String, Integer> listUpstreamJobs(String jobFullName, int buildNumber) { return Collections.emptyMap(); } @Nonnull @Override public Map<String, Integer> listTransitiveUpstreamJobs(String jobFullName, int buildNumber) { return Collections.emptyMap(); } @Override public void cleanup() { } @Nonnull @Override public List<MavenArtifact> getGeneratedArtifacts(@Nonnull String jobFullName, int buildNumber) { return Collections.emptyList(); } @Override public String toPrettyString() { return "PipelineMavenPluginNullDao"; } }
3e0100b2ad87edf6f4651789a8fc8aca48a56d46
2,376
java
Java
telemetry-http-okhttp/src/main/java/com/newrelic/telemetry/OkHttpPoster.java
zuluecho9/newrelic-telemetry-sdk-java
6264bf7f9147d7bff7d112f442b45c80902cffb1
[ "Apache-2.0" ]
26
2019-09-01T23:13:57.000Z
2022-03-01T21:46:47.000Z
telemetry-http-okhttp/src/main/java/com/newrelic/telemetry/OkHttpPoster.java
zuluecho9/newrelic-telemetry-sdk-java
6264bf7f9147d7bff7d112f442b45c80902cffb1
[ "Apache-2.0" ]
148
2019-08-27T22:14:37.000Z
2022-01-31T23:01:51.000Z
telemetry-http-okhttp/src/main/java/com/newrelic/telemetry/OkHttpPoster.java
zuluecho9/newrelic-telemetry-sdk-java
6264bf7f9147d7bff7d112f442b45c80902cffb1
[ "Apache-2.0" ]
31
2019-09-14T05:12:47.000Z
2022-01-30T09:40:07.000Z
32.547945
96
0.739899
415
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.newrelic.telemetry; import com.newrelic.telemetry.http.HttpPoster; import com.newrelic.telemetry.http.HttpResponse; import java.io.IOException; import java.net.URL; import java.time.Duration; import java.util.Map; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; /** Implementation of the HttpPoster interface using an OkHttp client. */ public class OkHttpPoster implements HttpPoster { private final OkHttpClient okHttpClient; /** Create an OkHttpPoster with a default OkHttpClient, and a connect timeout of 2 seconds. */ public OkHttpPoster() { this(Duration.ofSeconds(2)); } /** * Create an OkHttpPoster with a default OkHttpClient, with only a custom http timeout. * * @param callTimeout expected call timeout */ public OkHttpPoster(Duration callTimeout) { this(new OkHttpClient.Builder().callTimeout(callTimeout).build()); } /** * Create an OkHttpPoster with your own OkHttpClient implementation. * * @param client http client responsible for the http communication */ public OkHttpPoster(OkHttpClient client) { this.okHttpClient = client; } @Override public HttpResponse post(URL url, Map<String, String> headers, byte[] body, String mediaType) throws IOException { RequestBody requestBody = RequestBody.create(MediaType.get(mediaType), body); Request request = new Request.Builder().url(url).headers(Headers.of(headers)).post(requestBody).build(); try (okhttp3.Response response = okHttpClient.newCall(request).execute()) { return new HttpResponse( response.body() != null ? response.body().string() : null, response.code(), response.message(), response.headers().toMultimap()); } } public static MetricBatchSenderFactory metricSenderFactory() { return MetricBatchSenderFactory.fromHttpImplementation(OkHttpPoster::new); } public static SpanBatchSenderFactory spanSenderFactory() { return SpanBatchSenderFactory.fromHttpImplementation(OkHttpPoster::new); } public static EventBatchSenderFactory eventSenderFactory() { return EventBatchSenderFactory.fromHttpImplementation(OkHttpPoster::new); } }
3e0101d903fba08066c4ab97b620fbdaf9bcf73a
7,342
java
Java
aws-java-sdk-ioteventsdata/src/main/java/com/amazonaws/services/ioteventsdata/model/ListDetectorsResult.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-ioteventsdata/src/main/java/com/amazonaws/services/ioteventsdata/model/ListDetectorsResult.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-ioteventsdata/src/main/java/com/amazonaws/services/ioteventsdata/model/ListDetectorsResult.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
34.469484
146
0.63198
416
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ioteventsdata.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/ListDetectors" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListDetectorsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * A list of summary information about the detectors (instances). * </p> */ private java.util.List<DetectorSummary> detectorSummaries; /** * <p> * The token that you can use to return the next set of results, or <code>null</code> if there are no more results. * </p> */ private String nextToken; /** * <p> * A list of summary information about the detectors (instances). * </p> * * @return A list of summary information about the detectors (instances). */ public java.util.List<DetectorSummary> getDetectorSummaries() { return detectorSummaries; } /** * <p> * A list of summary information about the detectors (instances). * </p> * * @param detectorSummaries * A list of summary information about the detectors (instances). */ public void setDetectorSummaries(java.util.Collection<DetectorSummary> detectorSummaries) { if (detectorSummaries == null) { this.detectorSummaries = null; return; } this.detectorSummaries = new java.util.ArrayList<DetectorSummary>(detectorSummaries); } /** * <p> * A list of summary information about the detectors (instances). * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setDetectorSummaries(java.util.Collection)} or {@link #withDetectorSummaries(java.util.Collection)} if * you want to override the existing values. * </p> * * @param detectorSummaries * A list of summary information about the detectors (instances). * @return Returns a reference to this object so that method calls can be chained together. */ public ListDetectorsResult withDetectorSummaries(DetectorSummary... detectorSummaries) { if (this.detectorSummaries == null) { setDetectorSummaries(new java.util.ArrayList<DetectorSummary>(detectorSummaries.length)); } for (DetectorSummary ele : detectorSummaries) { this.detectorSummaries.add(ele); } return this; } /** * <p> * A list of summary information about the detectors (instances). * </p> * * @param detectorSummaries * A list of summary information about the detectors (instances). * @return Returns a reference to this object so that method calls can be chained together. */ public ListDetectorsResult withDetectorSummaries(java.util.Collection<DetectorSummary> detectorSummaries) { setDetectorSummaries(detectorSummaries); return this; } /** * <p> * The token that you can use to return the next set of results, or <code>null</code> if there are no more results. * </p> * * @param nextToken * The token that you can use to return the next set of results, or <code>null</code> if there are no more * results. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The token that you can use to return the next set of results, or <code>null</code> if there are no more results. * </p> * * @return The token that you can use to return the next set of results, or <code>null</code> if there are no more * results. */ public String getNextToken() { return this.nextToken; } /** * <p> * The token that you can use to return the next set of results, or <code>null</code> if there are no more results. * </p> * * @param nextToken * The token that you can use to return the next set of results, or <code>null</code> if there are no more * results. * @return Returns a reference to this object so that method calls can be chained together. */ public ListDetectorsResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDetectorSummaries() != null) sb.append("DetectorSummaries: ").append(getDetectorSummaries()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListDetectorsResult == false) return false; ListDetectorsResult other = (ListDetectorsResult) obj; if (other.getDetectorSummaries() == null ^ this.getDetectorSummaries() == null) return false; if (other.getDetectorSummaries() != null && other.getDetectorSummaries().equals(this.getDetectorSummaries()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDetectorSummaries() == null) ? 0 : getDetectorSummaries().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public ListDetectorsResult clone() { try { return (ListDetectorsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
3e0102c7065b8a5c0ea6edfc9ed8c934ac6a9f0f
9,929
java
Java
src/main/java/com/mmall/service/impl/ProductServiceImpl.java
zgzjj/shopmall
0cf23df4f51c32c2314c27998def561243a817c5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mmall/service/impl/ProductServiceImpl.java
zgzjj/shopmall
0cf23df4f51c32c2314c27998def561243a817c5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mmall/service/impl/ProductServiceImpl.java
zgzjj/shopmall
0cf23df4f51c32c2314c27998def561243a817c5
[ "Apache-2.0" ]
null
null
null
45.967593
166
0.678719
417
package com.mmall.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.google.common.collect.Lists; import com.mmall.common.Const; import com.mmall.common.ResponseCode; import com.mmall.common.ServerResponse; import com.mmall.dao.CategoryMapper; import com.mmall.dao.ProductMapper; import com.mmall.po.Category; import com.mmall.po.Product; import com.mmall.service.ICategoryService; import com.mmall.service.IProductService; import com.mmall.util.DateTimeUtil; import com.mmall.util.PropertiesUtil; import com.mmall.vo.ProductDetailVo; import com.mmall.vo.ProductListVo; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service("iProductService") public class ProductServiceImpl implements IProductService { private Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class); @Autowired private ProductMapper productMapper; @Autowired private CategoryMapper categoryMapper; @Autowired private ICategoryService iCategoryService; public ServerResponse productSave(Product product){ if(product != null){ if(StringUtils.isNotBlank(product.getSubImages())){ String[] subImageArray = product.getSubImages().split(","); if(subImageArray.length > 0){ product.setMainImage(subImageArray[0]); } } if(product.getId() != null){ int rowCount = productMapper.updateByPrimaryKey(product); if(rowCount > 0) { return ServerResponse.createBySuccess("更新产品成功"); } return ServerResponse.createByErrorMessage("更新产品失败"); }else { int rowCount = productMapper.insert(product); if(rowCount > 0){ return ServerResponse.createBySuccess("新增产品成功"); } return ServerResponse.createByErrorMessage("新增产品失败"); } } return ServerResponse.createByErrorMessage("新增或更新产品参数不正确"); } public ServerResponse setSaleStatus(Integer productId,Integer status){ if(productId == null || status ==null){ return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc()); } Product product = new Product(); product.setId(productId); product.setStatus(status); int rowCount = productMapper.updateByPrimaryKeySelective(product); if(rowCount > 0){ return ServerResponse.createBySuccess("修改产品状态成功"); } return ServerResponse.createByErrorMessage("修改产品状态失败"); } public ServerResponse<ProductDetailVo> manageProductDetail(Integer productId){ if(productId == null){ return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc()); } Product product =productMapper.selectByPrimaryKey(productId); if(product == null){ return ServerResponse.createByErrorMessage("产品已下架或者删除"); } ProductDetailVo productDetailVo = assembleProductDetailVo(product); return ServerResponse.createBySuccess(productDetailVo); } public ServerResponse<PageInfo> getProductList(int pageNum,int pageSize){ PageHelper.startPage(pageNum,pageSize); List<Product> productList = productMapper.selectList(); List<ProductListVo> productListVoList = Lists.newArrayList(); for(Product productItem : productList){ ProductListVo productListVo = assembleProductListVo(productItem); productListVoList.add(productListVo); } PageInfo pageResult = new PageInfo(productList); pageResult.setList(productListVoList); return ServerResponse.createBySuccess(pageResult); } public ServerResponse<PageInfo> searchProduct(String productName,Integer productId,int pageNum,int pageSize){ PageHelper.startPage(pageNum,pageSize); if(StringUtils.isNotBlank(productName)){ productName = new StringBuilder().append("%").append(productName).append("%").toString(); } List<Product> productList = productMapper.selectByNameAndProductId(productName,productId); List<ProductListVo> productListVoList = Lists.newArrayList(); for(Product productItem : productList){ ProductListVo productListVo = assembleProductListVo(productItem); productListVoList.add(productListVo); } PageInfo pageResult = new PageInfo(productList); pageResult.setList(productListVoList); return ServerResponse.createBySuccess(pageResult); } public ProductDetailVo assembleProductDetailVo(Product product){ ProductDetailVo productDetailVo = new ProductDetailVo(); productDetailVo.setId(product.getId()); productDetailVo.setSubtitle(product.getSubtitle()); productDetailVo.setPrice(product.getPrice()); productDetailVo.setMainImage(product.getMainImage()); productDetailVo.setSubImage(product.getSubImages()); productDetailVo.setCategoryId(product.getCategoryId()); productDetailVo.setDetail(product.getDetail()); productDetailVo.setName(product.getName()); productDetailVo.setStatus(product.getStatus()); productDetailVo.setStock(product.getStock()); productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/")); Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId()); if(category == null){ productDetailVo.setParentCategoryId(0); }else { productDetailVo.setParentCategoryId(category.getParentId()); } productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime())); productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime())); return productDetailVo; } public ProductListVo assembleProductListVo(Product product){ ProductListVo productListVo =new ProductListVo(); productListVo.setId(product.getId()); productListVo.setSubtitle(product.getSubtitle()); productListVo.setPrice(product.getPrice()); productListVo.setMainImage(product.getMainImage()); productListVo.setCategoryId(product.getCategoryId()); productListVo.setName(product.getName()); productListVo.setStatus(product.getStatus()); productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/")); return productListVo; } public ServerResponse<ProductDetailVo> getProductDetail(Integer productId){ if(productId == null){ return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc()); } Product product =productMapper.selectByPrimaryKey(productId); if(product == null){ return ServerResponse.createByErrorMessage("产品已下架或者删除"); } if(product.getStatus() != Const.productStatusEnum.ON_SALE.getCode()){ return ServerResponse.createByErrorMessage("产品已下架或者删除"); } ProductDetailVo productDetailVo = assembleProductDetailVo(product); return ServerResponse.createBySuccess(productDetailVo); } public ServerResponse<PageInfo> getProductByKeywordAndCategory(String keyword,Integer categoryId,int pageNum ,int pageSize,String orderBy){ if(StringUtils.isBlank(keyword) && categoryId == null){ return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc()); } List<Integer> categoryIdList = new ArrayList<>(); if(categoryId != null){ Category category = categoryMapper.selectByPrimaryKey(categoryId); if(category ==null && StringUtils.isBlank(keyword)){ //没有该分类且无关键字 PageHelper.startPage(pageNum,pageSize); List<ProductListVo> productListVoList = Lists.newArrayList(); PageInfo pageInfo = new PageInfo(productListVoList); return ServerResponse.createBySuccess(pageInfo); } categoryIdList = iCategoryService.getChildDeepCategory(categoryId).getData(); } if(StringUtils.isNotBlank(keyword)){ keyword = new StringBuilder().append("%").append(keyword).append("%").toString(); } PageHelper.startPage(pageNum,pageSize); //排序处理 if(StringUtils.isNotBlank(orderBy)){ if(Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){ String[] orderByArray = orderBy.split("_"); PageHelper.orderBy(orderByArray[0]+" "+orderByArray[1]); } } List<Product> productList = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword)?null:keyword,categoryIdList.size()==0?null:categoryIdList); List<ProductListVo> productListVoList = Lists.newArrayList(); for(Product product : productList){ ProductListVo productListVo = assembleProductListVo(product); productListVoList.add(productListVo); } PageInfo pageInfo = new PageInfo(productListVoList); return ServerResponse.createBySuccess(pageInfo); } }
3e01030e33abd4d1640033710ce533539aa584bb
2,188
java
Java
jmh/src/main/java/org/green/jmh/cab/MessageSenderBenchmark.java
anatolygudkov/green-cab
9261e846ce01ab40ed0acb5e7b0c726aab5cc0a5
[ "MIT" ]
1
2022-01-21T11:29:22.000Z
2022-01-21T11:29:22.000Z
jmh/src/main/java/org/green/jmh/cab/MessageSenderBenchmark.java
anatolygudkov/green-cab
9261e846ce01ab40ed0acb5e7b0c726aab5cc0a5
[ "MIT" ]
null
null
null
jmh/src/main/java/org/green/jmh/cab/MessageSenderBenchmark.java
anatolygudkov/green-cab
9261e846ce01ab40ed0acb5e7b0c726aab5cc0a5
[ "MIT" ]
null
null
null
30.388889
73
0.728976
418
package org.green.jmh.cab; import org.green.cab.ConsumerInterruptedException; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; @Fork(3) @Measurement(iterations = 3) @Warmup(iterations = 3) @BenchmarkMode(Mode.Throughput) public class MessageSenderBenchmark extends CabBenchmark { @Benchmark @Threads(1) public void oneMessageSenderWithCabBlocking( final CabBlockingSetup cabSetup, final Blackhole blackhole) throws ConsumerInterruptedException, InterruptedException { cabSetup.cab.send(this); } @Benchmark @Threads(2) public void twoMessageSendersWithCabBlocking( final CabBlockingSetup cabSetup, final Blackhole blackhole) throws ConsumerInterruptedException, InterruptedException { cabSetup.cab.send(this); } @Benchmark @Threads(1) public void oneMessageSenderWithCabBackingOff( final CabBackingOffSetup cabSetup, final Blackhole blackhole) throws ConsumerInterruptedException, InterruptedException { cabSetup.cab.send(this); } @Benchmark @Threads(2) public void twoMessageSendersWithCabBackingOff( final CabBackingOffSetup cabSetup, final Blackhole blackhole) throws ConsumerInterruptedException, InterruptedException { cabSetup.cab.send(this); } @Benchmark @Threads(1) public void oneMessageSenderWithCabYielding( final CabYieldingSetup cabSetup, final Blackhole blackhole) throws ConsumerInterruptedException, InterruptedException { cabSetup.cab.send(this); } @Benchmark @Threads(2) public void twoMessageSendersWithCabYielding( final CabYieldingSetup cabSetup, final Blackhole blackhole) throws ConsumerInterruptedException, InterruptedException { cabSetup.cab.send(this); } }
3e01032cf7fde35d8b9bb50f3259717b32c4c8b2
2,203
java
Java
lib/src/datafileutil/SaveObjectsParams.java
kbaseapps/proteome_comparison
f96f62941820a793124a18fe6e655da33a562033
[ "MIT" ]
1
2018-09-18T20:47:30.000Z
2018-09-18T20:47:30.000Z
lib/src/datafileutil/SaveObjectsParams.java
kbaseapps/proteome_comparison
f96f62941820a793124a18fe6e655da33a562033
[ "MIT" ]
16
2016-12-19T21:25:05.000Z
2022-02-10T16:36:17.000Z
lib/src/datafileutil/SaveObjectsParams.java
kbaseapps/proteome_comparison
f96f62941820a793124a18fe6e655da33a562033
[ "MIT" ]
16
2016-11-30T18:02:48.000Z
2020-05-08T16:42:14.000Z
25.321839
135
0.679074
419
package datafileutil; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * <p>Original spec-file type: SaveObjectsParams</p> * <pre> * Input parameters for the "save_objects" function. * Required parameters: * id - the numerical ID of the workspace. * objects - the objects to save. * * The object provenance is automatically pulled from the SDK runner. * </pre> * */ @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("com.googlecode.jsonschema2pojo") @JsonPropertyOrder({ "id", "objects" }) public class SaveObjectsParams { @JsonProperty("id") private Long id; @JsonProperty("objects") private List<ObjectSaveData> objects; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("id") public Long getId() { return id; } @JsonProperty("id") public void setId(Long id) { this.id = id; } public SaveObjectsParams withId(Long id) { this.id = id; return this; } @JsonProperty("objects") public List<ObjectSaveData> getObjects() { return objects; } @JsonProperty("objects") public void setObjects(List<ObjectSaveData> objects) { this.objects = objects; } public SaveObjectsParams withObjects(List<ObjectSaveData> objects) { this.objects = objects; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperties(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return ((((((("SaveObjectsParams"+" [id=")+ id)+", objects=")+ objects)+", additionalProperties=")+ additionalProperties)+"]"); } }
3e01033690c041b16fcfff0a98d14ee6eaf8f634
3,836
java
Java
projects/connector-manager/source/javatests/com/google/enterprise/connector/mock/jcr/MockJcrQuery.java
KalibriCuga/google-enterprise-connector-manager
49b8cd008b6604f8cf3d8660fda23dcfb3245e24
[ "Apache-2.0" ]
11
2015-04-06T19:32:10.000Z
2021-12-07T13:08:33.000Z
projects/connector-manager/source/javatests/com/google/enterprise/connector/mock/jcr/MockJcrQuery.java
KalibriCuga/google-enterprise-connector-manager
49b8cd008b6604f8cf3d8660fda23dcfb3245e24
[ "Apache-2.0" ]
1
2015-08-05T21:46:18.000Z
2015-08-05T21:46:18.000Z
projects/connector-manager/source/javatests/com/google/enterprise/connector/mock/jcr/MockJcrQuery.java
KalibriCuga/google-enterprise-connector-manager
49b8cd008b6604f8cf3d8660fda23dcfb3245e24
[ "Apache-2.0" ]
6
2015-04-24T20:06:35.000Z
2020-02-04T02:49:25.000Z
31.966667
80
0.726799
420
// Copyright (C) 2006-2008 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.enterprise.connector.mock.jcr; import com.google.enterprise.connector.mock.MockRepositoryDateTime; import com.google.enterprise.connector.mock.MockRepositoryDocument; import com.google.enterprise.connector.mock.MockRepositoryDocumentStore; import java.util.List; import javax.jcr.Node; import javax.jcr.query.Query; import javax.jcr.query.QueryResult; /** * MockJcrQuery implements the corresponding JCR interface. This implementation * temporarily violates the explicit semantics of JCR by only allowing date * queries between specified bounds. This class will need revisiting when we * work with a real JCR implementation. * <p> * TODO(ziff): extend the query semantics as needed */ public class MockJcrQuery implements Query { private final String statement; private final List<MockRepositoryDocument> internalQuery; /** * Creates a MockJcrQuery object from a date range. This is intended to be * used for query traversal. We may need to add another constructor, or * another type that implements this interface, for other SPI requirements * as we go along. * @param from Beginning point of range * @param to End point of range * @param store MockRepositoryDocumentStore from which documents are * returned */ public MockJcrQuery(MockRepositoryDateTime from, MockRepositoryDateTime to, MockRepositoryDocumentStore store) { this.statement = "Query for documents between " + from.toString() + " and " + to.toString(); this.internalQuery = store.dateRange(from, to); } /** * Creates a MockJcrQuery object from a single date. This is intended to be * used for query traversal. * @param from Beginning point of range * @param store MockRepositoryDocumentStore from which documents are * returned */ public MockJcrQuery(MockRepositoryDateTime from, MockRepositoryDocumentStore store) { this.statement = "Query for documents from " + from.toString(); this.internalQuery = store.dateRange(from); } /** * Returns the result list from executing the query. Clients may consume as * much or little of the result as they need. * @return MockJcrQueryResult */ public QueryResult execute() { return new MockJcrQueryResult(this.internalQuery); } /** * Returns the query statement. In this implementation, this is * just for debugging - it's not an actual query string in a query language. * @return the stored statement */ public String getStatement() { return statement; } /** * Returns the query language. TBD(ziff): consider whether this is really * needed. * @return null */ public String getLanguage() { return null; } //The following methods are JCR level 1 - but we do not anticipate using them /** * Throws UnsupportedOperationException * @return nothing */ public String getStoredQueryPath() { throw new UnsupportedOperationException(); } //The following methods are JCR level 2 - these would never be needed /** * Throws UnsupportedOperationException * @param arg0 * @return nothing */ public Node storeAsNode(String arg0) { throw new UnsupportedOperationException(); } }
3e0103c7c1f185a59710fe270c15a2394ec8a5ba
4,048
java
Java
src/main/java/com/phicomm/product/manger/service/BpmSaleStatisticService.java
renqiang2016/product.manger
98221534380ffe89849f8c0edc8884714accff74
[ "Apache-2.0" ]
null
null
null
src/main/java/com/phicomm/product/manger/service/BpmSaleStatisticService.java
renqiang2016/product.manger
98221534380ffe89849f8c0edc8884714accff74
[ "Apache-2.0" ]
null
null
null
src/main/java/com/phicomm/product/manger/service/BpmSaleStatisticService.java
renqiang2016/product.manger
98221534380ffe89849f8c0edc8884714accff74
[ "Apache-2.0" ]
4
2018-08-07T15:21:29.000Z
2021-07-06T07:35:52.000Z
31.874016
85
0.653903
421
package com.phicomm.product.manger.service; import com.phicomm.product.manger.dao.BpmSaleStatisticMapper; import com.phicomm.product.manger.model.bpm.BpmCountBean; import com.phicomm.product.manger.module.dds.CustomerContextHolder; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * 统计血压计的销量 * Created by yafei.hou on 2017/11/9. * * @author yafei.hou */ @Service public class BpmSaleStatisticService { private Logger logger = Logger.getLogger(BpmSaleStatisticService.class); private BpmSaleStatisticMapper bpmSaleStatisticMapper; @Autowired public BpmSaleStatisticService(BpmSaleStatisticMapper bpmSaleStatisticMapper) { this.bpmSaleStatisticMapper = bpmSaleStatisticMapper; Assert.notNull(this.bpmSaleStatisticMapper); } /** * 获取前N个月的血压计每个月的销量 * * @param months 月数 * @return Map\<String, Integer>月份和数量的关系表 */ public Map<String, Integer> obtainBPMSaleNumByMonth(int months) { DateTime dateTime = new DateTime(DateTime.now()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM"); List<BpmCountBean> countBeans; CustomerContextHolder.selectProdDataSource(); countBeans = bpmSaleStatisticMapper.obtainBpmSaleByMonth(months); CustomerContextHolder.clearDataSource(); if (countBeans.isEmpty()) { return new HashMap<>(0); } Map<String, Integer> resultMonth = new TreeMap<>(); for (BpmCountBean countBean : countBeans) { resultMonth.put(countBean.getBindPBMTime(), countBean.getBindPBMCount()); } int i = 0; while (i < months) { String bindPBMTime = dateFormat.format(dateTime.toDate()); if (!resultMonth.containsKey(bindPBMTime)) { resultMonth.put(bindPBMTime, 0); } dateTime = dateTime.minusMonths(1); i++; } return resultMonth; } /** * 获取前N天的血压计每天的销量 * * @param days 天数 * @return Map\<String, Integer>天数和数量的关系表 */ public Map<String, Integer> obtainBPMSaleNumByDay(int days) { DateTime dateTime = new DateTime(DateTime.now()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); List<BpmCountBean> countBeans; CustomerContextHolder.selectProdDataSource(); countBeans = bpmSaleStatisticMapper.obtainBpmSaleNumByDay(days); CustomerContextHolder.clearDataSource(); if (countBeans.isEmpty()) { return new HashMap<>(0); } Map<String, Integer> result = new TreeMap<>(); for (BpmCountBean countBean : countBeans) { result.put(countBean.getBindPBMTime(), countBean.getBindPBMCount()); } int i = 0; while (i < days) { String bindPBMTime = dateFormat.format(dateTime.toDate()); if (!result.containsKey(bindPBMTime)) { result.put(bindPBMTime, 0); } dateTime = dateTime.minusDays(1); i++; } logger.info("obtainBPMSaleNumByDay\n"+result); return result; } /** * 统计血压计总销量(包括今天) * * @return 总销量 */ public int obtainBPMSaleNumAll() { CustomerContextHolder.selectProdDataSource(); int result = bpmSaleStatisticMapper.obtainBpmSaleNumAll(); CustomerContextHolder.clearDataSource(); return result; } /** * 统计血压计 今天销量(包括今天) * * @return 总销量 */ public int obtainBPMSaleNumToday() { CustomerContextHolder.selectProdDataSource(); int result = bpmSaleStatisticMapper.obtainBpmSaleNumToday(); CustomerContextHolder.clearDataSource(); return result; } }
3e01042cad033a6714231a734c81b98f44bc6fb8
2,986
java
Java
extide/o.apache.tools.ant.module/test/unit/src/org/apache/tools/ant/module/wizards/shortcut/SelectFolderPanelTest.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,056
2019-04-25T20:00:35.000Z
2022-03-30T04:46:14.000Z
extide/o.apache.tools.ant.module/test/unit/src/org/apache/tools/ant/module/wizards/shortcut/SelectFolderPanelTest.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
1,846
2019-04-25T20:50:05.000Z
2022-03-31T23:40:41.000Z
extide/o.apache.tools.ant.module/test/unit/src/org/apache/tools/ant/module/wizards/shortcut/SelectFolderPanelTest.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
550
2019-04-25T20:04:33.000Z
2022-03-25T17:43:01.000Z
37.325
116
0.680844
422
/* * 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.tools.ant.module.wizards.shortcut; import java.util.Arrays; import javax.swing.ListModel; import org.openide.loaders.DataFolder; /** * Test functionality of SelectFolderPanel. * @author Jesse Glick */ public final class SelectFolderPanelTest extends ShortcutWizardTestBase { public SelectFolderPanelTest(String name) { super(name); } private SelectFolderPanel.SelectFolderWizardPanel menuPanel; private SelectFolderPanel.SelectFolderWizardPanel toolbarsPanel; private ListModel menuListModel; private ListModel toolbarsListModel; @Override protected void setUp() throws Exception { super.setUp(); iter.nextPanel(); wiz.putProperty(ShortcutWizard.PROP_SHOW_MENU, true); wiz.putProperty(ShortcutWizard.PROP_SHOW_TOOL, true); menuPanel = (SelectFolderPanel.SelectFolderWizardPanel)iter.current(); menuListModel = menuPanel.getPanel().getModel(); iter.nextPanel(); toolbarsPanel = (SelectFolderPanel.SelectFolderWizardPanel)iter.current(); toolbarsListModel = toolbarsPanel.getPanel().getModel(); } public void testFolderListDisplay() throws Exception { String[] names = new String[menuListModel.getSize()]; for (int i = 0; i < names.length; i++) { names[i] = menuPanel.getPanel().getNestedDisplayName((DataFolder)menuListModel.getElementAt(i)); } String[] expected = { "File", "Edit", "Build", "Build \u2192 Other", "Help", }; assertEquals("right names in list", Arrays.asList(expected), Arrays.asList(names)); names = new String[toolbarsListModel.getSize()]; for (int i = 0; i < names.length; i++) { names[i] = toolbarsPanel.getPanel().getNestedDisplayName((DataFolder)toolbarsListModel.getElementAt(i)); } expected = new String[] { "Build", "Help", }; assertEquals("right names in list", Arrays.asList(expected), Arrays.asList(names)); } // XXX test setting correct folder & display name in wizard data }
3e010485d6fe3ce37aa3da9ac4f6e37cc5b28b76
641
java
Java
src/main/java/frc/robot/commands/CannonFiringSolenoidSetState.java
WARPSPEED4239/ShowBotV3
19e7b33a761b5dc54c3f32244d6bb977b8067785
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/CannonFiringSolenoidSetState.java
WARPSPEED4239/ShowBotV3
19e7b33a761b5dc54c3f32244d6bb977b8067785
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/CannonFiringSolenoidSetState.java
WARPSPEED4239/ShowBotV3
19e7b33a761b5dc54c3f32244d6bb977b8067785
[ "BSD-3-Clause" ]
null
null
null
20.03125
68
0.734789
423
package frc.robot.commands; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Cannon; public class CannonFiringSolenoidSetState extends CommandBase { private final Cannon mCannon; private final boolean mOpen; public CannonFiringSolenoidSetState(Cannon cannon, boolean open) { mCannon = cannon; mOpen = open; addRequirements(mCannon); } @Override public void initialize() { mCannon.setFiringSolenoidState(mOpen); } @Override public void execute() {} @Override public void end(boolean interrupted) {} @Override public boolean isFinished() { return false; } }
3e0104ff75bf79558f17e6f879f5c27438b5806d
770
java
Java
spring-boot-mybatis-typehandler/src/main/java/com/constant/Sex.java
linqin07/SpringBoot-Study
e592e298193865a037badedb97b4dc8dffac2ebd
[ "Apache-2.0" ]
null
null
null
spring-boot-mybatis-typehandler/src/main/java/com/constant/Sex.java
linqin07/SpringBoot-Study
e592e298193865a037badedb97b4dc8dffac2ebd
[ "Apache-2.0" ]
null
null
null
spring-boot-mybatis-typehandler/src/main/java/com/constant/Sex.java
linqin07/SpringBoot-Study
e592e298193865a037badedb97b4dc8dffac2ebd
[ "Apache-2.0" ]
1
2022-01-14T00:28:09.000Z
2022-01-14T00:28:09.000Z
18.780488
52
0.557143
424
package com.constant; /** * @Description: * @author: LinQin * @date: 2019/05/22 */ //用于SexTypeHandler的性别转换器枚举 public enum Sex { //每一个类型都是一个枚举类(Sex)的实例 MALE(1, "男"), FMALE(0, "女"); //用于保存在数据库 private int SexCode; //用于UI展示 private String SexName; Sex(int sexCode, String sexName) { SexCode = sexCode; SexName = sexName; } public int getSexCode() { return SexCode; } public String getSexName() { return SexName; } //通过SexCode的值来获取Sex枚举类型,数据库只需保存code,通过代码解析成Sex类型 public static Sex getSexFromCode(int code) { for (Sex sex : Sex.values()) { if (sex.getSexCode() == code) { return sex; } } return null; } }
3e0105a087b6ed1f2f3571eee7e785e82459b433
1,975
java
Java
src/main/java/entities/GoldenApple.java
gbarte/Snake
8739b82446afd48a57d834ffa2dfeb3e7ba5497a
[ "MIT" ]
null
null
null
src/main/java/entities/GoldenApple.java
gbarte/Snake
8739b82446afd48a57d834ffa2dfeb3e7ba5497a
[ "MIT" ]
null
null
null
src/main/java/entities/GoldenApple.java
gbarte/Snake
8739b82446afd48a57d834ffa2dfeb3e7ba5497a
[ "MIT" ]
null
null
null
27.816901
78
0.652152
425
package entities; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import models.Coordinate; import utils.Sizes; import world.GameMap; /** * Interactive food object of Golden Apple. * Main difference from regular apple is that it gives more * score points and increases the snake twice. */ public class GoldenApple implements Food { public static int DEFAULT_SCORE = 25; public static double rarity = 0.2; private static final String texturePath = "assets/goldapple16px.png"; private Coordinate coordinate; private Texture texture; /** * Creates an apple with a predefined texture at Random coordinate in the * texture space (Coordinate is multiplied with cell size!). * @param coordinate of the GoldenApple to be placed. */ public GoldenApple(Coordinate coordinate) { this.coordinate = coordinate; } public GoldenApple() { } /** * Method used to render this apple one the screen with * an golden apple texture. * @param batch to draw on */ public void render(SpriteBatch batch) { this.texture = new Texture(texturePath); batch.draw(texture, coordinate.getCoordinateX() * Sizes.TILE_PIXELS, coordinate.getCoordinateY() * Sizes.TILE_PIXELS); } public Coordinate getCoordinate() { return coordinate; } public void setCoordinate(Coordinate coordinate) { this.coordinate = coordinate; } public void setTexture(Texture texture) { this.texture = texture; } public Texture getTexture() { return this.texture; } @Override public void action(GameMap map) { map.getScore().add(GoldenApple.DEFAULT_SCORE); map.getSnake().growSnake(2); } }
3e0105ccff45f82b1b16814d0b004cf6b6201b80
4,774
java
Java
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201708/ProductTemplateServiceInterface.java
mo4ss/googleads-java-lib
beee87c10744335b9e3e49770feeee897944b3ec
[ "Apache-2.0" ]
null
null
null
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201708/ProductTemplateServiceInterface.java
mo4ss/googleads-java-lib
beee87c10744335b9e3e49770feeee897944b3ec
[ "Apache-2.0" ]
null
null
null
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201708/ProductTemplateServiceInterface.java
mo4ss/googleads-java-lib
beee87c10744335b9e3e49770feeee897944b3ec
[ "Apache-2.0" ]
null
null
null
39.783333
300
0.593842
426
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * ProductTemplateServiceInterface.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201708; public interface ProductTemplateServiceInterface extends java.rmi.Remote { /** * Creates new {@link ProductTemplate} objects. * * * @param productTemplates the productTemplates to create * * @return the persisted product templates with their Ids filled in */ public com.google.api.ads.dfp.axis.v201708.ProductTemplate[] createProductTemplates(com.google.api.ads.dfp.axis.v201708.ProductTemplate[] productTemplates) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201708.ApiException; /** * Gets a {@link ProductTemplatePage} of {@link ProductTemplate} * objects * that satisfy the filtering criteria specified by given {@link * Statement#query}. * The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ProductTemplate#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link ProductTemplate#name}</td> * </tr> * <tr> * <td>{@code nameMacro}</td> * <td>{@link ProductTemplate#nameMacro}</td> * </tr> * <tr> * <td>{@code description}</td> * <td>{@link ProductTemplate#description}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link ProductTemplate#status}</td> * </tr> * <tr> * <td>{@code lastModifiedDateTime}</td> * <td>{@link ProductTemplate#lastModifiedDateTime}</td> * </tr> * <tr> * <td>{@code lineItemType}</td> * <td>{@link LineItemType}</td> * </tr> * <tr> * <td>{@code productType}</td> * <td>{@link ProductType}</td> * </tr> * <tr> * <td>{@code rateType}</td> * <td>{@link RateType}</td> * </tr> * </table> * * * @param statement a Publisher Query Language statement which specifies * the * filtering criteria over productTemplates * * @return the productTemplates that match the given statement */ public com.google.api.ads.dfp.axis.v201708.ProductTemplatePage getProductTemplatesByStatement(com.google.api.ads.dfp.axis.v201708.Statement statement) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201708.ApiException; /** * Performs action on {@link ProductTemplate} objects that satisfy * the given * {@link Statement#query}. * * * @param action the action to perform * * @param filterStatement a Publisher Query Language statement used to * filter * a set of product templates * * @return the result of the action performed */ public com.google.api.ads.dfp.axis.v201708.UpdateResult performProductTemplateAction(com.google.api.ads.dfp.axis.v201708.ProductTemplateAction action, com.google.api.ads.dfp.axis.v201708.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201708.ApiException; /** * Updates the specified {@link ProductTemplate} objects. * * * @param productTemplates the product templates to update * * @return the updated product templates */ public com.google.api.ads.dfp.axis.v201708.ProductTemplate[] updateProductTemplates(com.google.api.ads.dfp.axis.v201708.ProductTemplate[] productTemplates) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201708.ApiException; }
3e010625ebf06512e56ae0b165bacb54a1a3d52b
2,067
java
Java
game-net/src/main/java/com/wjybxx/fastjgame/misc/VoidRpcResponseChannel.java
taojhlwkl/fastjgame
281f8aa2ea53ea600614508ad6e45f47deab39da
[ "Apache-2.0" ]
1
2021-04-13T08:54:49.000Z
2021-04-13T08:54:49.000Z
game-net/src/main/java/com/wjybxx/fastjgame/misc/VoidRpcResponseChannel.java
taojhlwkl/fastjgame
281f8aa2ea53ea600614508ad6e45f47deab39da
[ "Apache-2.0" ]
null
null
null
game-net/src/main/java/com/wjybxx/fastjgame/misc/VoidRpcResponseChannel.java
taojhlwkl/fastjgame
281f8aa2ea53ea600614508ad6e45f47deab39da
[ "Apache-2.0" ]
null
null
null
29.956522
91
0.726173
427
/* * Copyright 2019 wjybxx * * 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.wjybxx.fastjgame.misc; import com.wjybxx.fastjgame.net.common.ProtocolDispatcher; import com.wjybxx.fastjgame.net.common.RpcErrorCode; import com.wjybxx.fastjgame.net.common.RpcResponse; import com.wjybxx.fastjgame.net.common.RpcResponseChannel; import com.wjybxx.fastjgame.net.session.Session; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** * 没有返回值的Channel,占位符,表示用户不关心返回值或方法本身无返回值 * 主要是{@link ProtocolDispatcher#postOneWayMessage(Session, Object)}用的, * 可以将{@code postOneWayMessage}伪装成 {@code postRpcRequest},这样应用层可以使用相同的接口对待需要结果和不需要结果的rpc请求。 * * @author wjybxx * @version 1.0 * date - 2019/8/21 * github - https://github.com/hl845740757 */ @ThreadSafe public class VoidRpcResponseChannel implements RpcResponseChannel<Object> { public static final RpcResponseChannel INSTANCE = new VoidRpcResponseChannel(); @Override public void writeSuccess(@Nullable Object body) { // do nothing } @Override public void writeFailure(@Nonnull RpcErrorCode errorCode, @Nonnull Throwable cause) { // do nothing } @Override public void writeFailure(@Nonnull RpcErrorCode errorCode, @Nonnull String message) { // do nothing } @Override public void write(@Nonnull RpcResponse rpcResponse) { // do nothing } @Override public boolean isVoid() { return true; } }
3e01066089245be0f746b8163b9b85d7206e5027
386
java
Java
api/src/main/java/com/jivesoftware/jivesdk/api/Credentials.java
guoyj21/jive-sdk-java
81473e27235fb4224654c2066ea2b0e6db85703c
[ "Apache-2.0" ]
null
null
null
api/src/main/java/com/jivesoftware/jivesdk/api/Credentials.java
guoyj21/jive-sdk-java
81473e27235fb4224654c2066ea2b0e6db85703c
[ "Apache-2.0" ]
null
null
null
api/src/main/java/com/jivesoftware/jivesdk/api/Credentials.java
guoyj21/jive-sdk-java
81473e27235fb4224654c2066ea2b0e6db85703c
[ "Apache-2.0" ]
null
null
null
17.545455
52
0.725389
428
package com.jivesoftware.jivesdk.api; import javax.annotation.Nonnull; /** * Interface representing oauth credentials. */ public interface Credentials { @Nonnull String getUrl(); void setAuthToken(@Nonnull String newAuthToken); @Nonnull String getAuthToken(); @Nonnull String getRefreshToken(); void setRefreshToken(@Nonnull String refreshToken); }
3e01076ef0d10b0d0a6ff4ef7d246c15c2d61cff
4,300
java
Java
bbb-voice/src/main/java/local/media/AudioOutputStream.java
thong-hoczita/bigbluebutton
612b294e89e708eddb150d4dc7b17349bce21ef5
[ "MIT" ]
null
null
null
bbb-voice/src/main/java/local/media/AudioOutputStream.java
thong-hoczita/bigbluebutton
612b294e89e708eddb150d4dc7b17349bce21ef5
[ "MIT" ]
null
null
null
bbb-voice/src/main/java/local/media/AudioOutputStream.java
thong-hoczita/bigbluebutton
612b294e89e708eddb150d4dc7b17349bce21ef5
[ "MIT" ]
null
null
null
33.1
102
0.686498
429
/* * Copyright (C) 2005 Luca Veltri - University of Parma - Italy * * This source code 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 source code 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 source code; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author(s): * Luca Veltri ([email protected]) */ package local.media; import javax.sound.sampled.*; import java.io.*; /** AudioOutputStream is equivalent to javax.sound.sampled.AudioInputStream * for audio playout. * <p/> * AudioOutputStream also provides audio codec conversion, as * javax.sound.sampled.AudioSystem does for the corresponding * javax.sound.sampled.AudioInputStream class. */ class AudioOutputStream extends OutputStream { static final int INTERNAL_BUFFER_SIZE=40960; /** The SourceDataLine */ protected SourceDataLine source_line; /** Converted InputStream. */ protected InputStream input_stream; /** Piped OutputStream. */ protected OutputStream output_stream; /** Internal buffer. */ private byte[] buff=new byte[INTERNAL_BUFFER_SIZE]; /** Creates a new AudioOutputStream from a SourceDataLine. */ public AudioOutputStream(SourceDataLine source_line) { this.source_line=source_line; input_stream=null; output_stream=null; } /** Creates a new AudioOutputStream from a SourceDataLine converting the audio format. */ public AudioOutputStream(SourceDataLine source_line, AudioFormat format) throws IOException { this.source_line=source_line; PipedInputStream piped_input_stream=new PipedInputStream(); output_stream=new PipedOutputStream(piped_input_stream); AudioInputStream audio_input_stream=new AudioInputStream(piped_input_stream,format,-1); if (audio_input_stream==null) { String err="Failed while creating a new AudioInputStream."; throw new IOException(err); } input_stream=AudioSystem.getAudioInputStream(source_line.getFormat(),audio_input_stream); if (input_stream==null) { String err="Failed while getting a transcoded AudioInputStream from AudioSystem."; err+="\n input codec: "+format.toString(); err+="\n output codec:"+source_line.getFormat().toString(); throw new IOException(err); } } /** Closes this output stream and releases any system resources associated with this stream. */ public void close() { //source_line.close(); } /** Flushes this output stream and forces any buffered output bytes to be written out. */ public void flush() { source_line.flush(); } /** Writes b.length bytes from the specified byte array to this output stream. */ public void write(byte[] b) throws IOException { if (output_stream!=null) { output_stream.write(b); int len=input_stream.read(buff,0,buff.length); source_line.write(buff,0,len); } else { source_line.write(b,0,b.length); } } /** Writes len bytes from the specified byte array starting at offset off to this output stream. */ public void write(byte[] b, int off, int len) throws IOException { if (output_stream!=null) { output_stream.write(b,off,len); len=input_stream.read(buff,0,buff.length); source_line.write(buff,0,len); } else { source_line.write(b,off,len); } } /** Writes the specified byte to this output stream. */ public void write(int b) throws IOException { if (output_stream!=null) { output_stream.write(b); int len=input_stream.read(buff,0,buff.length); source_line.write(buff,0,len); } else { buff[0]=(byte)b; source_line.write(buff,0,1); } } }
3e0109404a2fda5d79d2fd71524414cdc04215d6
1,326
java
Java
xcloud-component-integration/xcloud-component-integration-feign-core/src/main/java/com/wl4g/component/integration/feign/core/annotation/mvc/HttpEncoding.java
wl4g/dopaas-infra
9c7142324dc142c77474840abc5ab4ae03c1f14c
[ "Apache-2.0" ]
1
2021-09-30T02:12:32.000Z
2021-09-30T02:12:32.000Z
xcloud-component-integration/xcloud-component-integration-feign-core/src/main/java/com/wl4g/component/integration/feign/core/annotation/mvc/HttpEncoding.java
wl4g/dopaas-infra
9c7142324dc142c77474840abc5ab4ae03c1f14c
[ "Apache-2.0" ]
6
2021-03-01T09:18:15.000Z
2021-08-17T08:02:25.000Z
xcloud-component-integration/xcloud-component-integration-feign-core/src/main/java/com/wl4g/component/integration/feign/core/annotation/mvc/HttpEncoding.java
wl4g/dopaas-infra
9c7142324dc142c77474840abc5ab4ae03c1f14c
[ "Apache-2.0" ]
1
2021-12-23T06:30:50.000Z
2021-12-23T06:30:50.000Z
23.263158
75
0.705128
430
/* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wl4g.component.integration.feign.core.annotation.mvc; /** * Lists all constants used by Feign encoders. * * @author Jakub Narloch */ public interface HttpEncoding { /** * The HTTP Content-Length header. */ String CONTENT_LENGTH = "Content-Length"; /** * The HTTP Content-Type header. */ String CONTENT_TYPE = "Content-Type"; /** * The HTTP Accept-Encoding header. */ String ACCEPT_ENCODING_HEADER = "Accept-Encoding"; /** * The HTTP Content-Encoding header. */ String CONTENT_ENCODING_HEADER = "Content-Encoding"; /** * The GZIP encoding. */ String GZIP_ENCODING = "gzip"; /** * The Deflate encoding. */ String DEFLATE_ENCODING = "deflate"; }
3e010966f221586f816b70f7e9aec249d92c3947
1,822
java
Java
full/src/main/java/com/tqdev/crudapi/record/spatial/SpatialDSL.java
Adito5393/java-crud-api
076e1607a1823358848b749129196624d00f0f3b
[ "MIT" ]
39
2017-01-19T22:18:42.000Z
2022-01-11T14:52:22.000Z
full/src/main/java/com/tqdev/crudapi/record/spatial/SpatialDSL.java
Adito5393/java-crud-api
076e1607a1823358848b749129196624d00f0f3b
[ "MIT" ]
5
2017-11-29T17:43:19.000Z
2018-07-11T17:50:26.000Z
full/src/main/java/com/tqdev/crudapi/record/spatial/SpatialDSL.java
Adito5393/java-crud-api
076e1607a1823358848b749129196624d00f0f3b
[ "MIT" ]
23
2017-02-09T15:49:59.000Z
2022-01-10T08:10:37.000Z
24.293333
71
0.714599
431
package com.tqdev.crudapi.record.spatial; import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.SQLDialect; import org.jooq.impl.DefaultDataType; public class SpatialDSL { public static Field<?> asText(Field<?> field) { return new AsText(field); } public static Field<?> geomFromText(Field<?> field) { return new GeomFromText(field); } public static Condition contains(Field<?> field1, Field<?> field2) { return new Contains(field1, field2); } public static Condition crosses(Field<?> field1, Field<?> field2) { return new Crosses(field1, field2); } public static Condition disjoint(Field<?> field1, Field<?> field2) { return new Disjoint(field1, field2); } public static Condition equals(Field<?> field1, Field<?> field2) { return new Equals(field1, field2); } public static Condition intersects(Field<?> field1, Field<?> field2) { return new Intersects(field1, field2); } public static Condition overlaps(Field<?> field1, Field<?> field2) { return new Overlaps(field1, field2); } public static Condition touches(Field<?> field1, Field<?> field2) { return new Touches(field1, field2); } public static Condition within(Field<?> field1, Field<?> field2) { return new Within(field1, field2); } public static Condition isClosed(Field<?> field) { return new IsClosed(field); } public static Condition isSimple(Field<?> field) { return new IsSimple(field); } public static Condition isValid(Field<?> field) { return new IsValid(field); } public static void registerDataTypes(DSLContext dsl) { SQLDialect dialect = dsl.dialect(); switch (dialect.family().toString()) { case "MYSQL": case "POSTGRES": case "SQLSERVER": DefaultDataType.getDefaultDataType(SQLDialect.DEFAULT, "geometry"); break; } } }
3e010987ad8ad7bbd60d4dc986bd1e7cf3ba2437
3,664
java
Java
oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/ProfileTaskLogEsDAO.java
sunpwork/skywalking
b22d29afd9d76d825d19a6d5e7f0761b2436fa19
[ "Apache-2.0" ]
6
2020-10-28T09:13:39.000Z
2021-05-19T08:11:06.000Z
oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/ProfileTaskLogEsDAO.java
sunpwork/skywalking
b22d29afd9d76d825d19a6d5e7f0761b2436fa19
[ "Apache-2.0" ]
27
2020-12-19T21:59:58.000Z
2022-01-21T23:50:16.000Z
oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/ProfileTaskLogEsDAO.java
sunpwork/skywalking
b22d29afd9d76d825d19a6d5e7f0761b2436fa19
[ "Apache-2.0" ]
2
2020-08-21T05:02:27.000Z
2021-09-01T05:42:02.000Z
46.974359
119
0.72571
432
/* * 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.skywalking.oap.server.storage.plugin.elasticsearch.query; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.skywalking.oap.server.core.profile.ProfileTaskLogRecord; import org.apache.skywalking.oap.server.core.query.type.ProfileTaskLog; import org.apache.skywalking.oap.server.core.query.type.ProfileTaskLogOperationType; import org.apache.skywalking.oap.server.core.storage.profile.IProfileTaskLogQueryDAO; import org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient; import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.EsDAO; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; public class ProfileTaskLogEsDAO extends EsDAO implements IProfileTaskLogQueryDAO { private final int queryMaxSize; public ProfileTaskLogEsDAO(ElasticSearchClient client, int profileTaskQueryMaxSize) { super(client); // query log size use profile task query max size * per log count this.queryMaxSize = profileTaskQueryMaxSize * 50; } @Override public List<ProfileTaskLog> getTaskLogList() throws IOException { final SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource(); final BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); sourceBuilder.query(boolQueryBuilder); sourceBuilder.sort(ProfileTaskLogRecord.OPERATION_TIME, SortOrder.DESC); sourceBuilder.size(queryMaxSize); final SearchResponse response = getClient().search(ProfileTaskLogRecord.INDEX_NAME, sourceBuilder); final LinkedList<ProfileTaskLog> tasks = new LinkedList<>(); for (SearchHit searchHit : response.getHits().getHits()) { tasks.add(parseTaskLog(searchHit)); } return tasks; } private ProfileTaskLog parseTaskLog(SearchHit data) { return ProfileTaskLog.builder() .id(data.getId()) .taskId((String) data.getSourceAsMap().get(ProfileTaskLogRecord.TASK_ID)) .instanceId((String) data.getSourceAsMap().get(ProfileTaskLogRecord.INSTANCE_ID)) .operationType(ProfileTaskLogOperationType.parse( ((Number) data.getSourceAsMap().get(ProfileTaskLogRecord.OPERATION_TYPE)).intValue())) .operationTime( ((Number) data.getSourceAsMap().get(ProfileTaskLogRecord.OPERATION_TIME)).longValue()) .build(); } }
3e01098a65774531acf3dcc2623843c83c3b87c1
2,918
java
Java
jmt-core/src/test/java/info/naiv/lab/java/jmt/io/SystemTempDirectoryTest.java
enlo/jmt-projects
bb7eb6e93084f06cbbb2ba8a4330fc108ee4858e
[ "MIT" ]
null
null
null
jmt-core/src/test/java/info/naiv/lab/java/jmt/io/SystemTempDirectoryTest.java
enlo/jmt-projects
bb7eb6e93084f06cbbb2ba8a4330fc108ee4858e
[ "MIT" ]
null
null
null
jmt-core/src/test/java/info/naiv/lab/java/jmt/io/SystemTempDirectoryTest.java
enlo/jmt-projects
bb7eb6e93084f06cbbb2ba8a4330fc108ee4858e
[ "MIT" ]
null
null
null
30.715789
87
0.648732
433
/* * The MIT License * * Copyright 2016 enlo. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package info.naiv.lab.java.jmt.io; import java.io.IOException; import java.nio.file.Path; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import org.junit.Test; /** * * @author enlo */ public class SystemTempDirectoryTest extends TempDirectoryTest { /** * */ public SystemTempDirectoryTest() { } /** * * @throws IOException */ @Test() public void testCtor() throws IOException { try (TempDirectory temp1 = newConcrete(); TempDirectory temp2 = newConcrete(temp1.getPath(), ""); TempDirectory temp3 = newConcrete(temp1.getPath(), "")) { assertThat(temp2.getPath().getParent(), is(temp1.getPath())); assertThat(temp3.getPath().getParent(), is(temp1.getPath())); assertThat(temp3.getPath(), is(not(temp2.getPath()))); } } /** * * @return @throws IOException */ @Override protected TempDirectory newConcrete() throws IOException { TempDirectory td = new SystemTempDirectory(); return td; } /** * * @param prefix * @return * @throws IOException */ @Override protected TempDirectory newConcrete(String prefix) throws IOException { TempDirectory td = new SystemTempDirectory(prefix); return td; } /** * * @param root * @param prefix * @return * @throws IOException */ protected TempDirectory newConcrete(Path root, String prefix) throws IOException { TempDirectory td = new SystemTempDirectory(root, prefix); return td; } }
3e010ba23ddcfeac542061fc33a906a6e7f42125
116
java
Java
metrics-spring/src/test/java/com/yammer/metrics/spring/UselessInterface.java
blackbaud/metrics-jdk5
0c88d70db72443cb7d1078b3fdf1286eb5e34cf6
[ "Apache-2.0" ]
3
2016-10-18T20:44:32.000Z
2017-09-22T13:16:36.000Z
metrics-spring/src/test/java/com/yammer/metrics/spring/UselessInterface.java
blackbaud/metrics-jdk5
0c88d70db72443cb7d1078b3fdf1286eb5e34cf6
[ "Apache-2.0" ]
13
2016-10-03T13:57:02.000Z
2022-01-25T22:16:18.000Z
metrics-spring/src/test/java/com/yammer/metrics/spring/UselessInterface.java
blackbaud/metrics-jdk5
0c88d70db72443cb7d1078b3fdf1286eb5e34cf6
[ "Apache-2.0" ]
5
2016-04-20T05:05:07.000Z
2019-08-01T21:40:29.000Z
19.333333
36
0.75
434
package com.yammer.metrics.spring; /** * Empty interface to trick Spring. */ public interface UselessInterface {}
3e010d1b52b488bd6f632ebe64021c2b552f046a
706
java
Java
jumbo-converters-compchem/jumbo-converters-compchem-nwchem/src/main/java/org/xmlcml/cml/converters/compchem/nwchem/NWChemConverters.java
BlueObelisk/jumbo-converters
858ba47240f3109db7d0338e572736eb6f8e5b61
[ "Apache-2.0" ]
2
2021-12-10T15:17:28.000Z
2022-03-13T13:28:51.000Z
jumbo-converters-compchem/jumbo-converters-compchem-nwchem/src/main/java/org/xmlcml/cml/converters/compchem/nwchem/NWChemConverters.java
BlueObelisk/jumbo-converters
858ba47240f3109db7d0338e572736eb6f8e5b61
[ "Apache-2.0" ]
1
2020-01-05T00:02:39.000Z
2020-01-06T08:47:03.000Z
jumbo-converters-compchem/jumbo-converters-compchem-nwchem/src/main/java/org/xmlcml/cml/converters/compchem/nwchem/NWChemConverters.java
BlueObelisk/jumbo-converters
858ba47240f3109db7d0338e572736eb6f8e5b61
[ "Apache-2.0" ]
null
null
null
32.090909
82
0.764873
435
package org.xmlcml.cml.converters.compchem.nwchem; import java.util.Collections; import org.xmlcml.cml.converters.compchem.nwchem.log.NWChemLog2XMLConverter; import org.xmlcml.cml.converters.compchem.nwchem.log.NWChemLog2CompchemConverter; import org.xmlcml.cml.converters.registry.ConverterInfo; import org.xmlcml.cml.converters.registry.ConverterListImpl; /** * @author Sam Adams */ public class NWChemConverters extends ConverterListImpl { public NWChemConverters() { list.add(new ConverterInfo(NWChemLog2XMLConverter.class)); list.add(new ConverterInfo(NWChemLog2CompchemConverter.class)); this.list = Collections.unmodifiableList(list); } }
3e010e1164dc1da7e3c58135c170d4d988ddcdd1
5,970
java
Java
core/src/main/java/hoopoe/core/base/BaseController.java
imloama/hoopoe
3d0bb3156405117dec253c4ccc75280297e51c35
[ "Apache-2.0" ]
null
null
null
core/src/main/java/hoopoe/core/base/BaseController.java
imloama/hoopoe
3d0bb3156405117dec253c4ccc75280297e51c35
[ "Apache-2.0" ]
1
2021-09-01T03:49:45.000Z
2021-09-01T03:49:45.000Z
core/src/main/java/hoopoe/core/base/BaseController.java
imloama/hoopoe
3d0bb3156405117dec253c4ccc75280297e51c35
[ "Apache-2.0" ]
null
null
null
34.508671
110
0.664824
436
package hoopoe.core.base; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.github.imloama.mybatisplus.bootext.base.APIResult; import com.wuwenze.poi.ExcelKit; import hoopoe.core.zfarm.Farm; import hoopoe.core.zfarm.Field; import hoopoe.core.zfarm.ZFarmAnnotationHandler; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.stream.Collectors; @Slf4j @Data public abstract class BaseController<M extends BaseModel<M,Long>,S extends BaseService<M>> { @Autowired protected S service; @Autowired protected HttpServletRequest request; @Autowired protected HttpServletResponse response; @Autowired protected StringRedisTemplate redisTemplate; protected abstract Class<M> getModelClass(); @GetMapping("/zfarm") public APIResult zfarm()throws Exception{ String key = this.getModelClass().getName() + ":zfarm"; String val = this.redisTemplate.opsForValue().get(key); if(StringUtils.isNotBlank(val)){ return APIResult.ok("success", JSON.parseObject(val, Farm.class)); } Farm<M> farm = ZFarmAnnotationHandler.handler(this.getModelClass()); if(farm == null)return APIResult.fail("no farm"); val = JSON.toJSONString(farm); this.redisTemplate.opsForValue().set(key, val); return APIResult.ok("success", farm); } @GetMapping("/{id}") public APIResult getById(@PathVariable("id") Long id)throws Exception{ M model = this.service.getById(id); return APIResult.ok("success", model); } @PostMapping("/create") public APIResult create(@RequestBody M model)throws Exception{ this.service.create(model); return APIResult.ok("success", true); } @PostMapping("/update/{id}") public APIResult update(@PathVariable("id") Long id, @RequestBody M model)throws Exception{ if(id!=model.getPrimaryKey())return APIResult.fail("参数错误!"); this.service.update(model); return APIResult.ok("success", true); } @GetMapping("/del/{id}") public APIResult delete(@PathVariable("id") Long id)throws Exception{ this.service.delete(id); return APIResult.ok("success", true); } // 批量删除 @PostMapping("/delall") public APIResult deleteAll(@RequestBody JSONObject params)throws Exception{ JSONArray ids = params.getJSONArray("ids"); if(ids == null || ids.isEmpty())return APIResult.fail("参数不正确!"); List<Long> list = ids.stream().map(id -> Long.parseLong(id.toString())).collect(Collectors.toList()); this.service.deleteAll(list); return APIResult.ok("success", true); } /** * 分页查询 * @param pageRequest * @return * @throws Exception */ @PostMapping("/page") public APIResult page(@RequestBody PageRequest pageRequest)throws Exception{ Page<M> page = new Page<>(); page.setCurrent(pageRequest.getPageNum()); page.setSize(pageRequest.getPageSize()); if(pageRequest.isAsc()){ page.setAsc(pageRequest.getOrderby()); }else{ page.setDesc(pageRequest.getOrderby()); } QueryWrapper<M> queryWrapper = queryWrapperFromRequest(pageRequest); IPage<M> pageResult = this.service.page(page, queryWrapper); return APIResult.ok("success", pageResult); } private QueryWrapper<M> queryWrapperFromRequest(PageRequest pageRequest) throws Exception { QueryWrapper<M> queryWrapper = new QueryWrapper<>(); // 模糊查询条件 if(StringUtils.isNotBlank(pageRequest.getSearch())){ M m = this.getModelClass().newInstance(); List<String> cols = m.searchColumns(); if(cols!=null&&!cols.isEmpty()){ for(int i=0,n=cols.size();i<n;i++){ if(i>0){ queryWrapper.or(); } queryWrapper.like(cols.get(i), pageRequest.getSearch()); } } } //精确查询条件 List<Query> queries = pageRequest.getQuery(); if(queries!=null&&!queries.isEmpty()){ for(int i=0,n=queries.size();i<n;i++){ queryWrapper = queries.get(i).fill(queryWrapper); } } return queryWrapper; } /** * 下载excel * @param pageRequest * @throws Exception */ @PostMapping("/excel") public void toExcel(@RequestBody PageRequest pageRequest)throws Exception{ QueryWrapper<M> queryWrapper = queryWrapperFromRequest(pageRequest); List<M> list = this.service.list(queryWrapper); ExcelKit.$Export(this.getModelClass(), this.response).downXlsx(list, false); } @GetMapping("/action/{name}/{id}") public APIResult action(@PathVariable("name") String name, @PathVariable("id") Long id) throws Exception { this.service.doAction(name, id); return APIResult.ok("success", true); } @GetMapping("/all") public APIResult all()throws Exception{ return APIResult.ok("success", this.service.list()); } }
3e010e904c5ad747338dd6cd72aab5b5b5c84983
820
java
Java
src/main/java/org/omg/hw/HW_vpnManager/IPCrossConnectionList_THolder.java
dong706/CorbaDemo
bcf0826ae8934f91b5e68085605127c2a671ffe3
[ "Apache-2.0" ]
null
null
null
src/main/java/org/omg/hw/HW_vpnManager/IPCrossConnectionList_THolder.java
dong706/CorbaDemo
bcf0826ae8934f91b5e68085605127c2a671ffe3
[ "Apache-2.0" ]
null
null
null
src/main/java/org/omg/hw/HW_vpnManager/IPCrossConnectionList_THolder.java
dong706/CorbaDemo
bcf0826ae8934f91b5e68085605127c2a671ffe3
[ "Apache-2.0" ]
null
null
null
24.848485
100
0.773171
437
package org.omg.hw.HW_vpnManager; /** * Generated from IDL definition of alias "IPCrossConnectionList_T" * @author JacORB IDL compiler */ public final class IPCrossConnectionList_THolder implements org.omg.CORBA.portable.Streamable { public org.omg.hw.HW_vpnManager.IPCrossConnection_T[] value; public IPCrossConnectionList_THolder () { } public IPCrossConnectionList_THolder (final org.omg.hw.HW_vpnManager.IPCrossConnection_T[] initial) { value = initial; } public org.omg.CORBA.TypeCode _type () { return IPCrossConnectionList_THelper.type (); } public void _read (final org.omg.CORBA.portable.InputStream in) { value = IPCrossConnectionList_THelper.read (in); } public void _write (final org.omg.CORBA.portable.OutputStream out) { IPCrossConnectionList_THelper.write (out,value); } }
3e010eae51f0843ad3b34011bc34db1b588c0ce9
3,286
java
Java
game/src/main/java/me/ryleykimmel/brandywine/game/message/listener/LoginMessageListener.java
ryleykimmel/brandywine
92ed17c9786c24c8e453a388fc77560298f7db19
[ "0BSD" ]
8
2015-12-19T07:37:32.000Z
2019-03-23T20:30:02.000Z
game/src/main/java/me/ryleykimmel/brandywine/game/message/listener/LoginMessageListener.java
rmcmk/brandywine
92ed17c9786c24c8e453a388fc77560298f7db19
[ "0BSD" ]
10
2015-09-22T09:24:37.000Z
2016-08-25T05:16:54.000Z
game/src/main/java/me/ryleykimmel/brandywine/game/message/listener/LoginMessageListener.java
rmcmk/brandywine
92ed17c9786c24c8e453a388fc77560298f7db19
[ "0BSD" ]
2
2019-03-23T20:29:44.000Z
2019-07-23T01:06:39.000Z
32.215686
104
0.732806
438
package me.ryleykimmel.brandywine.game.message.listener; import io.netty.channel.ChannelFutureListener; import me.ryleykimmel.brandywine.game.auth.AuthenticationRequest; import me.ryleykimmel.brandywine.game.auth.AuthenticationService; import me.ryleykimmel.brandywine.game.message.LoginMessage; import me.ryleykimmel.brandywine.game.message.LoginResponseMessage; import me.ryleykimmel.brandywine.game.model.World; import me.ryleykimmel.brandywine.game.model.player.PlayerCredentials; import me.ryleykimmel.brandywine.network.ResponseCode; import me.ryleykimmel.brandywine.network.Session; import me.ryleykimmel.brandywine.network.message.MessageListener; /** * Listener for the {@link LoginMessage}. */ public final class LoginMessageListener implements MessageListener<LoginMessage> { /** * The expected client version received. */ private static final int CLIENT_VERSION = 317; /** * The expected value of a dummy byte sent at the start of the login protocol. */ private static final int EXPECTED_DUMMY = 255; /** * The expected opcode which indicates successful our secure RSA buffer is using the correct key pair. */ private static final int EXPECTED_BLOCK_OPCODE = 10; /** * The World for submitting authentication requests. */ private final World world; /** * Constructs a new {@link LoginMessageListener}. * * @param world The World for submitting authentication requests. */ public LoginMessageListener(World world) { this.world = world; } @Override public void handle(Session session, LoginMessage message) { if (message.getDummy() != EXPECTED_DUMMY) { closeWithResponse(session, ResponseCode.STATUS_LOGIN_SERVER_REJECTED_SESSION); return; } if (message.getClientVersion() != CLIENT_VERSION) { closeWithResponse(session, ResponseCode.STATUS_GAME_UPDATED); return; } if (message.getDetail() != 0 && message.getDetail() != 1) { closeWithResponse(session, ResponseCode.STATUS_LOGIN_SERVER_REJECTED_SESSION); return; } if (message.getBlockOperationCode() != EXPECTED_BLOCK_OPCODE) { closeWithResponse(session, ResponseCode.STATUS_LOGIN_SERVER_REJECTED_SESSION); return; } long serverSessionId = message.getServerSessionId(); long clientSessionId = message.getClientSessionId(); if (serverSessionId != session.getId()) { closeWithResponse(session, ResponseCode.STATUS_BAD_SESSION_ID); return; } int[] sessionIds = { (int) (clientSessionId >> 32), (int) clientSessionId, (int) (serverSessionId >> 32), (int) serverSessionId }; world.getService(AuthenticationService.class).submit(new AuthenticationRequest(session, new PlayerCredentials(message.getUserId(), message.getUsername(), message.getPassword(), sessionIds))); } /** * Closes the specified Session and notifies the client with the specified ResponseCode. * * @param session The Session to close. * @param response The ResponseCode sent to the client. */ private void closeWithResponse(Session session, ResponseCode response) { session.writeAndFlush(new LoginResponseMessage(response)) .addListener(ChannelFutureListener.CLOSE); } }
3e010f41331a3dc39fd50f99eb8e69dae9eab5a3
963
java
Java
sample/src/main/java/com/kevin/delegationadapter/sample/samedata/adapter/BillItemAdapterDelegate.java
EyckWu/DelegationAdapter
3317162869fcf042bece7eaf3e1ee10aec5078e5
[ "Apache-2.0" ]
420
2018-05-09T02:49:28.000Z
2022-03-25T07:39:11.000Z
sample/src/main/java/com/kevin/delegationadapter/sample/samedata/adapter/BillItemAdapterDelegate.java
EyckWu/DelegationAdapter
3317162869fcf042bece7eaf3e1ee10aec5078e5
[ "Apache-2.0" ]
16
2018-10-12T02:53:59.000Z
2021-02-23T00:44:16.000Z
sample/src/main/java/com/kevin/delegationadapter/sample/samedata/adapter/BillItemAdapterDelegate.java
xuehuayous/DelegationAdapter
feb290a6ca5d18510e452d55a5d7e679d50dfa03
[ "Apache-2.0" ]
73
2018-05-29T01:18:03.000Z
2021-12-17T10:15:03.000Z
29.242424
93
0.744041
439
package com.kevin.delegationadapter.sample.samedata.adapter; import androidx.annotation.NonNull; import androidx.databinding.ViewDataBinding; import androidx.databinding.library.baseAdapters.BR; import com.kevin.delegationadapter.extras.binding.BindingAdapterDelegate; import com.kevin.delegationadapter.sample.R; import com.kevin.delegationadapter.sample.samedata.bean.Bill; /** * BillItemAdapterDelegate * * @author [email protected], Created on 2018-04-28 17:23:00 * Major Function:<b></b> * <p/> * 注:如果您修改了本类请填写以下内容作为记录,如非本人操作劳烦通知,谢谢!!! * @author mender,Modified Date Modify Content: */ public class BillItemAdapterDelegate extends BindingAdapterDelegate<Bill.Item> { @Override public int getLayoutRes() { return R.layout.item_bill_item; } @Override public void setVariable(@NonNull ViewDataBinding binding, Bill.Item item, int position) { binding.setVariable(BR.model, item); } }
3e010f971d3ec572dfbd3455f01014f07bb2dd78
285
java
Java
bemyndigelsesservice/src/main/java/dk/bemyndigelsesregister/bemyndigelsesservice/server/NspManager.java
trifork/bemyndigelsesregister
8d2b6e1981245da04ab68ae4b294017d83c2f288
[ "MIT" ]
null
null
null
bemyndigelsesservice/src/main/java/dk/bemyndigelsesregister/bemyndigelsesservice/server/NspManager.java
trifork/bemyndigelsesregister
8d2b6e1981245da04ab68ae4b294017d83c2f288
[ "MIT" ]
null
null
null
bemyndigelsesservice/src/main/java/dk/bemyndigelsesregister/bemyndigelsesservice/server/NspManager.java
trifork/bemyndigelsesregister
8d2b6e1981245da04ab68ae4b294017d83c2f288
[ "MIT" ]
null
null
null
31.666667
84
0.842105
440
package dk.bemyndigelsesregister.bemyndigelsesservice.server; import dk.bemyndigelsesregister.bemyndigelsesservice.server.exportmodel.Delegations; import org.joda.time.DateTime; public interface NspManager { void send(Delegations delegations, DateTime startTime, int batchNo); }
3e01104a612a6e433c8c57b9bfe9a74c971cead4
100
java
Java
interpreter.common/src/main/java/gov/nist/drmf/interpreter/common/eval/EvaluatorType.java
ag-gipp/LaCASt
e24830e16cdc4ae34c193b0bac11fef7066b1f23
[ "MIT" ]
null
null
null
interpreter.common/src/main/java/gov/nist/drmf/interpreter/common/eval/EvaluatorType.java
ag-gipp/LaCASt
e24830e16cdc4ae34c193b0bac11fef7066b1f23
[ "MIT" ]
null
null
null
interpreter.common/src/main/java/gov/nist/drmf/interpreter/common/eval/EvaluatorType.java
ag-gipp/LaCASt
e24830e16cdc4ae34c193b0bac11fef7066b1f23
[ "MIT" ]
null
null
null
16.666667
46
0.77
441
package gov.nist.drmf.interpreter.common.eval; public enum EvaluatorType { SYMBOLIC, NUMERIC }
3e0110b529b07b3d8400ca6be0a3b306c194b028
2,638
java
Java
StartHere/src/main/java/com/lambdaschool/starthere/services/UserArticleServiceImpl.java
Pintereach-BuildWeek/Backend
f654b90c9e076bcb657d50a0f60c061497a3c962
[ "MIT" ]
null
null
null
StartHere/src/main/java/com/lambdaschool/starthere/services/UserArticleServiceImpl.java
Pintereach-BuildWeek/Backend
f654b90c9e076bcb657d50a0f60c061497a3c962
[ "MIT" ]
5
2019-09-24T20:01:28.000Z
2021-12-09T21:37:09.000Z
StartHere/src/main/java/com/lambdaschool/starthere/services/UserArticleServiceImpl.java
Pintereach-BuildWeek/Backend
f654b90c9e076bcb657d50a0f60c061497a3c962
[ "MIT" ]
null
null
null
31.404762
115
0.703563
442
package com.lambdaschool.starthere.services; import com.lambdaschool.starthere.exceptions.ResourceNotFoundException; import com.lambdaschool.starthere.models.UserArticles; import com.lambdaschool.starthere.repository.UserArticleRepository; import com.lambdaschool.starthere.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; @Service(value = "articleService") public class UserArticleServiceImpl implements UserArticleService { @Autowired UserArticleRepository userarticlerepos; @Autowired UserRepository userrepos; @Override public UserArticles update(UserArticles user, long id, boolean isAdmin) { return null; } @Override public List<UserArticles> findAll() { List<UserArticles> articles = new ArrayList<>(); userarticlerepos.findAll().iterator().forEachRemaining(articles::add); return articles; } @Override public UserArticles findArticleById(long id) { return userarticlerepos.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User Article id " + id + " not found!")); } @Transactional @Override public void delete(long id) { userarticlerepos.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User Article id " + id + " not found!")); userarticlerepos.deleteById(id); } @Override public UserArticles save(UserArticles userarticle) { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); if (userarticle.getUser() .getUsername() .equalsIgnoreCase(authentication.getName())) { return userarticlerepos.save(userarticle); } else { throw new ResourceNotFoundException((authentication.getName() + "not authorized to make change")); } } @Override public UserArticles findByName(String name) { return null; } @Override public List<UserArticles> findByUserName(String username) { return userarticlerepos.findAllByUser_Username(username); } @Override public List<UserArticles> findByCategoryName(String category) { return userarticlerepos.findAllByCategory(category); } }
3e011294b94017cfce5ee7693bdf076d5676ac7c
2,330
java
Java
subprojects/internal-testing/src/main/java/dev/nokee/internal/testing/TaskMatchers.java
nokeedev/gradle-native
19f63779b60529dee897e471e28c495fefae8534
[ "Apache-2.0" ]
40
2020-04-24T13:02:27.000Z
2022-01-28T02:45:49.000Z
subprojects/internal-testing/src/main/java/dev/nokee/internal/testing/TaskMatchers.java
nokeedev/gradle-native
19f63779b60529dee897e471e28c495fefae8534
[ "Apache-2.0" ]
315
2020-03-04T05:04:59.000Z
2022-03-30T00:32:46.000Z
subprojects/internal-testing/src/main/java/dev/nokee/internal/testing/TaskMatchers.java
nokeedev/gradle-native
19f63779b60529dee897e471e28c495fefae8534
[ "Apache-2.0" ]
6
2020-04-24T18:36:13.000Z
2021-11-16T00:05:47.000Z
31.917808
110
0.730901
443
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 dev.nokee.internal.testing; import dev.nokee.utils.DeferredUtils; import org.gradle.api.Task; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import static org.hamcrest.Matchers.equalTo; public final class TaskMatchers { /** * Matches a task group with the specified value. * * @param group a task group to match, must not be null * @return a task matcher, never null */ public static Matcher<Task> group(String group) { return group(equalTo(group)); } public static Matcher<Task> group(Matcher<String> matcher) { return new FeatureMatcher<Task, String>(matcher, "a task with group", "task group") { @Override protected String featureValueOf(Task actual) { return actual.getGroup(); } }; } public static Matcher<Task> description(String description) { return description(equalTo(description)); } /** * Matches a task description using the specified matcher. * * @param matcher a task description to matcher, must not be null * @return a task matcher, never null */ public static Matcher<Task> description(Matcher<? super String> matcher) { return new FeatureMatcher<Task, String>(matcher, "a task with description of", "task description") { @Override protected String featureValueOf(Task actual) { return actual.getDescription(); } }; } public static Matcher<Task> dependsOn(Matcher<? super Iterable<Object>> matcher) { return new FeatureMatcher<Task, Iterable<Object>>(matcher, "a task with dependency on", "task dependency") { @Override protected Iterable<Object> featureValueOf(Task actual) { return DeferredUtils.flatUnpackWhile(actual.getDependsOn(), DeferredUtils::isDeferred); } }; } }
3e011357809b1e1914c2da55ccc57fa7a6bf7724
233
java
Java
Forloop1.java
sheshanireddy/sheshani
509b1831005748e3600bc097c040132ae47a4621
[ "Apache-2.0" ]
null
null
null
Forloop1.java
sheshanireddy/sheshani
509b1831005748e3600bc097c040132ae47a4621
[ "Apache-2.0" ]
null
null
null
Forloop1.java
sheshanireddy/sheshani
509b1831005748e3600bc097c040132ae47a4621
[ "Apache-2.0" ]
null
null
null
16.642857
45
0.48927
444
//for-each loop package oops; public class Forloop1 { public static void main(String[] args) { int arr[]={12,23,44,56,78}; for(int i:arr){ System.out.println(i); } } }
3e011393be5c3b98f799e29f094f84e51a25500e
773
java
Java
fxgl-samples/src/main/java/basics/TextureSample.java
GeorgeJoLo/FXGL
8db76c5250fb844eb0c98a456aa0bb3becb08e85
[ "MIT" ]
2,859
2015-04-03T20:52:31.000Z
2022-03-31T08:30:01.000Z
fxgl-samples/src/main/java/basics/TextureSample.java
GeorgeJoLo/FXGL
8db76c5250fb844eb0c98a456aa0bb3becb08e85
[ "MIT" ]
1,015
2015-07-05T17:18:11.000Z
2022-03-26T18:58:50.000Z
fxgl-samples/src/main/java/basics/TextureSample.java
GeorgeJoLo/FXGL
8db76c5250fb844eb0c98a456aa0bb3becb08e85
[ "MIT" ]
461
2015-05-22T03:47:33.000Z
2022-03-29T04:55:51.000Z
22.794118
60
0.643871
445
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package basics; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.app.GameSettings; import com.almasb.fxgl.dsl.FXGL; /** * Shows how to use textures to draw entities. * * @author Almas Baimagambetov (AlmasB) ([email protected]) */ public class TextureSample extends GameApplication { @Override protected void initSettings(GameSettings settings) { } @Override protected void initGame() { FXGL.entityBuilder() .at(200, 200) .view("brick.png") .buildAndAttach(); } public static void main(String[] args) { launch(args); } }
3e0113e73f1d0d3e7cf1d3be256100a9f91683e0
15,984
java
Java
src/uk/ac/manchester/cs/jfact/kernel/ToDoList.java
edlectrico/android-jfact
30cb773cf15bea8af170399dd1ccf01cbfa8026d
[ "Apache-2.0" ]
2
2020-04-30T02:36:10.000Z
2021-03-02T22:17:33.000Z
src/uk/ac/manchester/cs/jfact/kernel/ToDoList.java
edlectrico/android-jfact
30cb773cf15bea8af170399dd1ccf01cbfa8026d
[ "Apache-2.0" ]
null
null
null
src/uk/ac/manchester/cs/jfact/kernel/ToDoList.java
edlectrico/android-jfact
30cb773cf15bea8af170399dd1ccf01cbfa8026d
[ "Apache-2.0" ]
1
2015-03-27T11:22:41.000Z
2015-03-27T11:22:41.000Z
33.864407
249
0.542605
446
package uk.ac.manchester.cs.jfact.kernel; /* This file is part of the JFact DL reasoner Copyright 2011 by Ignazio Palmisano, Dmitry Tsarkov, University of Manchester This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA*/ import static uk.ac.manchester.cs.jfact.kernel.ToDoPriorMatrix.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import uk.ac.manchester.cs.jfact.dep.DepSet; import uk.ac.manchester.cs.jfact.helpers.FastSetSimple; import uk.ac.manchester.cs.jfact.helpers.Helper; import uk.ac.manchester.cs.jfact.helpers.SaveStack; import conformance.Original; import conformance.PortedFrom; @PortedFrom(file = "ToDoList.h", name = "ToDoList") public class ToDoList { @Original static int limit = 500; @Original protected TODOListSaveState[] states = new TODOListSaveState[limit]; @Original protected int nextState = 0; @Original volatile boolean change = true; /** the entry of Todo table */ public static class ToDoEntry { /** node to include concept */ private DlCompletionTree node; private int concept; private FastSetSimple delegate; ToDoEntry(DlCompletionTree n, ConceptWDep off) { node = n; concept = off.getConcept(); delegate = off.getDep().getDelegate(); } protected DlCompletionTree getNode() { return node; } protected int getOffsetConcept() { return concept; } protected FastSetSimple getOffsetDepSet() { return delegate; } @Override public String toString() { return "Node(" + node.getId() + "), offset(" + new ConceptWDep(concept, DepSet.create(delegate)) + ")"; } } /** class to represent single queue */ static class ArrayQueue { /** waiting ops queue */ List<ToDoEntry> Wait = new ArrayList<ToDoEntry>(50); /** start pointer; points to the 1st element in the queue */ int sPointer = 0; /** add entry to a queue */ public void add(DlCompletionTree node, ConceptWDep offset) { Wait.add(new ToDoEntry(node, offset)); } /** clear queue */ @PortedFrom(file = "ToDoList.h", name = "clear") public void clear() { sPointer = 0; Wait.clear(); } /** check if queue empty */ @PortedFrom(file = "ToDoList.h", name = "empty") public boolean isEmpty() { return sPointer == Wait.size(); } /** get next entry from the queue; works for non-empty queues */ public ToDoEntry get() { return Wait.get(sPointer++); } /** save queue content to the given entry */ @PortedFrom(file = "ToDoList.h", name = "save") public void save(int[][] tss, int pos) { tss[pos][0] = sPointer; tss[pos][1] = Wait.size(); } /** restore queue content from the given entry */ @PortedFrom(file = "ToDoList.h", name = "restore") public void restore(int[][] tss, int pos) { sPointer = tss[pos][0]; Helper.resize(Wait, tss[pos][1]); } @PortedFrom(file = "ToDoList.h", name = "restore") public void restore(int sp, int ep) { sPointer = sp; Helper.resize(Wait, ep); } @Override public String toString() { StringBuilder l = new StringBuilder(); l.append("ArrayQueue{"); l.append(sPointer); l.append(","); for (ToDoEntry t : Wait) { l.append(t); l.append(" "); } l.append("}"); return l.toString(); } } /** class for saving/restoring priority queue Todo */ static class QueueQueueSaveState { /** save whole array */ protected List<ToDoEntry> waitingQueue; /** save start point of queue of entries */ protected int sp; /** save end point of queue of entries */ protected int ep; /** save flag of queue's consistency */ protected boolean queueBroken; } /** class to represent single priority queue */ static class QueueQueue { /** waiting ops queue */ private List<ToDoEntry> _Wait = new ArrayList<ToDoEntry>(); /** start pointer; points to the 1st element in the queue */ private int sPointer = 0; /** flag for checking whether queue was reordered */ private boolean queueBroken = false; int size = 0; /** add entry to a queue */ void add(DlCompletionTree Node, ConceptWDep offset) { ToDoEntry e = new ToDoEntry(Node, offset); // no problems with empty queue and if no priority // clashes if (isEmpty() || _Wait.get(size - 1).getNode().getNominalLevel() <= Node .getNominalLevel()) { _Wait.add(e); size++; return; } // here we need to put e on the proper place int n = size; while (n > sPointer && _Wait.get(n - 1).getNode().getNominalLevel() > Node .getNominalLevel()) { --n; } _Wait.add(n, e); queueBroken = true; size++; } /** clear queue */ @PortedFrom(file = "ToDoList.h", name = "clear") void clear() { sPointer = 0; queueBroken = false; _Wait.clear(); size = 0; } /** check if queue empty */ boolean isEmpty() { return sPointer == size; } /** get next entry from the queue; works for non-empty queues */ ToDoEntry get() { return _Wait.get(sPointer++); } /** save queue content to the given entry */ @PortedFrom(file = "ToDoList.h", name = "save") void save(QueueQueueSaveState tss) { tss.queueBroken = queueBroken; tss.sp = sPointer; if (queueBroken) { tss.waitingQueue = new ArrayList<ToDoEntry>(_Wait); } else { // save just end pointer tss.ep = size; } // clear flag for the next session queueBroken = false; } /** restore queue content from the given entry */ @PortedFrom(file = "ToDoList.h", name = "restore") void restore(QueueQueueSaveState tss) { queueBroken = tss.queueBroken; sPointer = tss.sp; if (queueBroken) { // the tss variable is discarded at the end of the restore, so // no need to copy _Wait = tss.waitingQueue; size = _Wait.size(); } else { // save just end pointer Helper.resize(_Wait, tss.ep); size = tss.ep; } } @Override public String toString() { return "{" + (!isEmpty() ? _Wait.get(sPointer) : "empty") + " sPointer: " + sPointer + " size: " + size + " Wait: " + _Wait + "}"; } } /** class for saving/restoring array Todo table */ static class TODOListSaveState { protected int backupID_sp; protected int backupID_ep; /** save state for queueNN */ protected QueueQueueSaveState backupNN = new QueueQueueSaveState(); /** save state of all regular queues */ protected int[][] backup = new int[nRegularOptions][2]; /** save number-of-entries to do */ @PortedFrom(file = "ToDoList.h", name = "noe") protected int noe; TODOListSaveState() {} @Override public String toString() { return "" + noe + " " + backupID_sp + "," + backupID_ep + " " + backupNN + " " + Arrays.toString(backup); } } @Original public TODOListSaveState getInstance() { return new TODOListSaveState(); } // @Original // public TODOListSaveState getInstance() { // // return new TODOListSaveState(); // if (nextState == limit) { // nextState = 0; // } // TODOListSaveState toReturn = states[nextState]; // if (toReturn != null) { // states[nextState++] = null; // change = true; // return toReturn; // } else { // // if (!isSaveStateGenerationStarted()) { // startSaveStateGeneration(); // } // return new TODOListSaveState(); // } // } @Original protected boolean saveStateGenerationStarted = false; @Original public boolean isSaveStateGenerationStarted() { return saveStateGenerationStarted; } @Original public void startSaveStateGeneration() { saveStateGenerationStarted = true; Thread stateFiller = new Thread() { @Override public void run() { long last = System.currentTimeMillis(); // timeout at one minute from last operation while (System.currentTimeMillis() - last < 60000) { for (int wait = 0; wait < 10000; wait++) { if (change) { for (int i = 0; i < limit; i++) { if (states[i] == null) { states[i] = new TODOListSaveState(); } } change = false; last = System.currentTimeMillis(); } try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } } // after timeout elapses, reset the flag - new requests will // reactivate the thread saveStateGenerationStarted = false; } }; stateFiller.setPriority(Thread.MIN_PRIORITY); stateFiller.setDaemon(true); stateFiller.start(); } /** waiting ops queue for IDs */ @PortedFrom(file = "ToDoList.h", name = "queueID") private ArrayQueue queueID = new ArrayQueue(); /** waiting ops queue for <= ops in nominal nodes */ @PortedFrom(file = "ToDoList.h", name = "queueNN") private QueueQueue queueNN = new QueueQueue(); /** waiting ops queues */ @PortedFrom(file = "ToDoList.h", name = "Wait") private List<ArrayQueue> waitQueue = new ArrayList<ArrayQueue>(nRegularOptions); /** stack of saved states */ @PortedFrom(file = "ToDoList.h", name = "SaveStack") private SaveStack<TODOListSaveState> saveStack = new SaveStack<TODOListSaveState>(); /** priority matrix */ @PortedFrom(file = "ToDoList.h", name = "Matrix") private ToDoPriorMatrix matrix = new ToDoPriorMatrix(); /** number of un-processed entries */ @PortedFrom(file = "ToDoList.h", name = "noe") private int noe; /** save current Todo table content to given saveState entry */ @PortedFrom(file = "ToDoList.h", name = "saveState") public void saveState(TODOListSaveState tss) { tss.backupID_sp = queueID.sPointer; tss.backupID_ep = queueID.Wait.size(); queueNN.save(tss.backupNN); for (int i = nRegularOptions - 1; i >= 0; --i) { waitQueue.get(i).save(tss.backup, i); } tss.noe = noe; } /** restore Todo table content from given saveState entry */ @PortedFrom(file = "ToDoList.h", name = "restoreState") public void restoreState(TODOListSaveState tss) { queueID.restore(tss.backupID_sp, tss.backupID_ep); queueNN.restore(tss.backupNN); for (int i = nRegularOptions - 1; i >= 0; --i) { waitQueue.get(i).restore(tss.backup[i][0], tss.backup[i][1]); } noe = tss.noe; } public ToDoList() { noe = 0; // Helper.resize(Wait, nRegularOps); for (int i = 0; i < nRegularOptions; i++) { waitQueue.add(new ArrayQueue()); } } /** init priorities via Options */ @Original public void initPriorities(String Options) { matrix.initPriorities(Options, "IAOEFLG"); } /** clear Todo table */ @PortedFrom(file = "ToDoList.h", name = "clear") public void clear() { queueID.clear(); queueNN.clear(); for (int i = nRegularOptions - 1; i >= 0; --i) { waitQueue.get(i).clear(); } saveStack.clear(); noe = 0; } /** check if Todo table is empty */ public boolean isEmpty() { return noe == 0; } // work with entries /** add entry with given NODE and CONCEPT with given OFFSET to the Todo table */ @PortedFrom(file = "ToDoList.h", name = "addEntry") public void addEntry(DlCompletionTree node, DagTag type, ConceptWDep C) { int index = matrix.getIndex(type, C.getConcept() > 0, node.isNominalNode()); switch (index) { case nRegularOptions: // unused entry return; case priorityIndexID: // ID queueID.add(node, C); break; case priorityIndexNominalNode: // NN queueNN.add(node, C); break; default: // regular queue waitQueue.get(index).add(node, C); break; } ++noe; } /** save current state using internal stack */ @PortedFrom(file = "ToDoList.h", name = "save") public void save() { TODOListSaveState state = getInstance(); saveState(state); saveStack.push(state); } /** restore state to the given level using internal stack */ @PortedFrom(file = "ToDoList.h", name = "restore") public void restore(int level) { restoreState(saveStack.pop(level)); } @PortedFrom(file = "ToDoList.h", name = "getNextEntry") public ToDoEntry getNextEntry() { assert !isEmpty(); // decrease amount of elements-to-process --noe; // check ID queue if (!queueID.isEmpty()) { return queueID.get(); } // check NN queue if (!queueNN.isEmpty()) { return queueNN.get(); } // check regular queues for (int i = 0; i < nRegularOptions; ++i) { ArrayQueue arrayQueue = waitQueue.get(i); if (!arrayQueue.isEmpty()) { return arrayQueue.get(); } } // that's impossible, but still... return null; } @Override public String toString() { StringBuilder l = new StringBuilder("Todolist{"); l.append("\n"); l.append(queueID); l.append("\n"); for (int i = 0; i < nRegularOptions; ++i) { l.append(waitQueue.get(i)); l.append("\n"); } l.append("\n"); l.append("}"); return l.toString(); } }
3e0113fa2cce19a7038ae373cbe9f87eaedc6603
14,259
java
Java
app/src/main/java/io/lbry/browser/utils/LbryUri.java
nhnifong/lbry-android
1e3a74cae1451ba8a26fbf95477865058e0109db
[ "MIT" ]
4,289
2017-08-13T05:57:57.000Z
2022-03-29T01:13:44.000Z
app/src/main/java/io/lbry/browser/utils/LbryUri.java
nhnifong/lbry-android
1e3a74cae1451ba8a26fbf95477865058e0109db
[ "MIT" ]
899
2017-08-17T07:00:05.000Z
2022-03-06T11:30:41.000Z
app/src/main/java/io/lbry/browser/utils/LbryUri.java
nhnifong/lbry-android
1e3a74cae1451ba8a26fbf95477865058e0109db
[ "MIT" ]
137
2017-08-13T07:03:41.000Z
2022-03-21T20:35:29.000Z
41.815249
157
0.624728
447
package io.lbry.browser.utils; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.lbry.browser.exceptions.LbryUriException; import lombok.Data; import static org.apache.commons.codec.CharEncoding.UTF_8; @Data public class LbryUri { public static final String LBRY_TV_BASE_URL = "https://lbry.tv/"; public static final String ODYSEE_COM_BASE_URL = "https://odysee.com/"; public static final String PROTO_DEFAULT = "lbry://"; public static final String REGEX_INVALID_URI = "[ =&#:$@%?;/\\\\\"<>%\\{\\}|^~\\[\\]`\u0000-\u0008\u000b-\u000c\u000e-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]"; public static final String REGEX_ADDRESS = "^(b)(?=[^0OIl]{32,33})[0-9A-Za-z]{32,33}$"; public static final int CHANNEL_NAME_MIN_LENGTH = 1; public static final int CLAIM_ID_MAX_LENGTH = 40; private static final String REGEX_PART_PROTOCOL = "^((?:lbry://|https://)?)"; private static final String REGEX_PART_HOST = "((?:open.lbry.com/|lbry.tv/|lbry.lat/|lbry.fr/|lbry.in/)?)"; private static final String REGEX_PART_STREAM_OR_CHANNEL_NAME = "([^:$#/]*)"; private static final String REGEX_PART_MODIFIER_SEPARATOR = "([:$#]?)([^/]*)"; private static final String QUERY_STRING_BREAKER = "^([\\S]+)([?][\\S]*)"; private static final Pattern PATTERN_SEPARATE_QUERY_STRING = Pattern.compile(QUERY_STRING_BREAKER); private String path; private boolean isChannel; private String streamName; private String streamClaimId; private String channelName; private String channelClaimId; private int primaryClaimSequence; private int secondaryClaimSequence; private int primaryBidPosition; private int secondaryBidPosition; private String claimName; private String claimId; private String contentName; private String queryString; private boolean isChannelUrl() { return (!Helper.isNullOrEmpty(channelName) && Helper.isNullOrEmpty(streamName)) || (!Helper.isNullOrEmpty(claimName) && claimName.startsWith("@")); } public static boolean isNameValid(String name) { return !Pattern.compile(REGEX_INVALID_URI).matcher(name).find(); } public static LbryUri tryParse(String url) { try { return parse(url, false); } catch (LbryUriException ex) { return null; } } public static LbryUri parse(String url) throws LbryUriException { return parse(url, false); } public static LbryUri parse(String url, boolean requireProto) throws LbryUriException { Pattern componentsPattern = Pattern.compile(String.format("%s%s%s%s(/?)%s%s", REGEX_PART_PROTOCOL, REGEX_PART_HOST, REGEX_PART_STREAM_OR_CHANNEL_NAME, REGEX_PART_MODIFIER_SEPARATOR, REGEX_PART_STREAM_OR_CHANNEL_NAME, REGEX_PART_MODIFIER_SEPARATOR)); String cleanUrl = url, queryString = null; if (Helper.isNullOrEmpty(url)) { throw new LbryUriException("Invalid url parameter."); } Matcher qsMatcher = PATTERN_SEPARATE_QUERY_STRING.matcher(url); if (qsMatcher.matches()) { queryString = qsMatcher.group(2); cleanUrl = !Helper.isNullOrEmpty(queryString) ? url.substring(0, url.indexOf(queryString)) : url; if (queryString != null && queryString.length() > 0) { queryString = queryString.substring(1); } } List<String> components = new ArrayList<>(); Matcher matcher = componentsPattern.matcher(cleanUrl); if (matcher.matches()) { // Note: For Java regex, group index 0 is always the full match for (int i = 1; i <= matcher.groupCount(); i++) { components.add(matcher.group(i)); } } if (components.size() == 0) { throw new LbryUriException("Regular expression error occurred while trying to parse the value"); } // components[0] = proto // components[1] = host // components[2] = streamNameOrChannelName // components[3] = primaryModSeparator // components[4] = primaryModValue // components[5] = pathSep // components[6] = possibleStreamName // components[7] = secondaryModSeparator // components[8] = secondaryModValue if (requireProto && Helper.isNullOrEmpty(components.get(0))) { throw new LbryUriException("LBRY URLs must include a protocol prefix (lbry://)."); } if (Helper.isNullOrEmpty(components.get(2))) { throw new LbryUriException("URL does not include name."); } for (String component : components.subList(2, components.size())) { if (component.indexOf(' ') > -1) { throw new LbryUriException("URL cannot include a space."); } } String streamOrChannelName = null; String possibleStreamName = null; try { // Using java.net.URLDecoder to be able to quickly unit test streamOrChannelName = URLDecoder.decode(components.get(2), UTF_8); possibleStreamName = URLDecoder.decode(components.get(6), UTF_8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String primaryModSeparator = components.get(3); String primaryModValue = components.get(4); String secondaryModSeparator = components.get(7); String secondaryModValue = components.get(8); boolean includesChannel = streamOrChannelName.startsWith("@"); boolean isChannel = includesChannel && Helper.isNullOrEmpty(possibleStreamName); String channelName = includesChannel && streamOrChannelName.length() > 1 ? streamOrChannelName.substring(1) : null; if (includesChannel) { if (Helper.isNullOrEmpty(channelName)) { throw new LbryUriException("No channel name after @."); } if (channelName.length() < CHANNEL_NAME_MIN_LENGTH) { throw new LbryUriException(String.format("Channel names must be at least %d character long.", CHANNEL_NAME_MIN_LENGTH)); } } UriModifier primaryMod = null, secondaryMod = null; if (!Helper.isNullOrEmpty(primaryModSeparator) && !Helper.isNullOrEmpty(primaryModValue)) { primaryMod = UriModifier.parse(primaryModSeparator, primaryModValue); } if (!Helper.isNullOrEmpty(secondaryModSeparator) && !Helper.isNullOrEmpty(secondaryModValue)) { secondaryMod = UriModifier.parse(secondaryModSeparator, secondaryModValue); } String streamName = includesChannel ? possibleStreamName : streamOrChannelName; String streamClaimId = (includesChannel && secondaryMod != null) ? secondaryMod.getClaimId() : primaryMod != null ? primaryMod.getClaimId() : null; String channelClaimId = (includesChannel && primaryMod != null) ? primaryMod.getClaimId() : null; LbryUri uri = new LbryUri(); uri.setChannel(isChannel); uri.setPath(Helper.join(components.subList(2, components.size()), "")); uri.setStreamName(streamName); uri.setStreamClaimId(streamClaimId); uri.setChannelName(channelName); uri.setChannelClaimId(channelClaimId); uri.setPrimaryClaimSequence(primaryMod != null ? primaryMod.getClaimSequence() : -1); uri.setSecondaryClaimSequence(secondaryMod != null ? secondaryMod.getClaimSequence() : -1); uri.setPrimaryBidPosition(primaryMod != null ? primaryMod.getBidPosition() : -1); uri.setSecondaryBidPosition(secondaryMod != null ? secondaryMod.getBidPosition() : -1); // Values that will not work properly with canonical urls uri.setClaimName(streamOrChannelName); uri.setClaimId(primaryMod != null ? primaryMod.getClaimId() : null); uri.setContentName(streamName); uri.setQueryString(queryString); return uri; } public String build(boolean includeProto, String protocol, boolean vanity) { String formattedChannelName = null; if (channelName != null) { formattedChannelName = channelName.startsWith("@") ? channelName : String.format("@%s", channelName); } String primaryClaimName = null; if ((protocol.equals(LBRY_TV_BASE_URL) || protocol.equals(ODYSEE_COM_BASE_URL)) && Helper.isNullOrEmpty(formattedChannelName)) { try { primaryClaimName = URLEncoder.encode(claimName, UTF_8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { primaryClaimName = claimName; } if (Helper.isNullOrEmpty(primaryClaimName)) { primaryClaimName = contentName; } if (Helper.isNullOrEmpty(primaryClaimName)) { primaryClaimName = formattedChannelName; } if (Helper.isNullOrEmpty(primaryClaimName)) { primaryClaimName = streamName; } String primaryClaimId = claimId; if (Helper.isNullOrEmpty(primaryClaimId)) { primaryClaimId = !Helper.isNullOrEmpty(formattedChannelName) ? channelClaimId : streamClaimId; } StringBuilder sb = new StringBuilder(); if (includeProto) { sb.append(protocol); } sb.append(primaryClaimName); if (vanity) { return sb.toString(); } String secondaryClaimName = null; if (Helper.isNullOrEmpty(claimName) && !Helper.isNullOrEmpty(contentName)) { secondaryClaimName = contentName; } if (Helper.isNullOrEmpty(secondaryClaimName)) { if (protocol.equals(LBRY_TV_BASE_URL) || protocol.equals(ODYSEE_COM_BASE_URL)) { try { secondaryClaimName = !Helper.isNullOrEmpty(formattedChannelName) ? URLEncoder.encode(streamName, UTF_8) : null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { secondaryClaimName = !Helper.isNullOrEmpty(formattedChannelName) ? streamName : null; } } String secondaryClaimId = !Helper.isNullOrEmpty(secondaryClaimName) ? streamClaimId : null; if (!Helper.isNullOrEmpty(primaryClaimId)) { if (protocol.equals(LBRY_TV_BASE_URL) || protocol.equals(ODYSEE_COM_BASE_URL)) sb.append(':').append(primaryClaimId); else sb.append('#').append(primaryClaimId); } else if (primaryClaimSequence > 0) { sb.append(':').append(primaryClaimSequence); } else if (primaryBidPosition > 0) { sb.append('$').append(primaryBidPosition); } if (!Helper.isNullOrEmpty(secondaryClaimName)) { sb.append('/').append(secondaryClaimName); } if (!Helper.isNullOrEmpty(secondaryClaimId)) { if (protocol.equals(LBRY_TV_BASE_URL) || protocol.equals(ODYSEE_COM_BASE_URL)) sb.append(':').append(secondaryClaimId); else sb.append('#').append(secondaryClaimId); } else if (secondaryClaimSequence > 0) { sb.append(':').append(secondaryClaimSequence); } else if (secondaryBidPosition > 0) { sb.append('$').append(secondaryBidPosition); } return sb.toString(); } public static String normalize(String url) throws LbryUriException { return parse(url).toString(); } public String toTvString() { return build(true, LBRY_TV_BASE_URL, false); } public String toOdyseeString() { return build(true, ODYSEE_COM_BASE_URL, false); } public String toVanityString() { return build(true, PROTO_DEFAULT, true); } public String toString() { return build(true, PROTO_DEFAULT, false); } public int hashCode() { return toString().hashCode(); } public boolean equals(Object o) { if (!(o instanceof LbryUri)) { return false; } return toString().equalsIgnoreCase(o.toString()); } @Data public static class UriModifier { private final String claimId; private final int claimSequence; private final int bidPosition; public UriModifier(String claimId, int claimSequence, int bidPosition) { this.claimId = claimId; this.claimSequence = claimSequence; this.bidPosition = bidPosition; } public static UriModifier parse(String modSeparator, String modValue) throws LbryUriException { String claimId = null; int claimSequence = 0, bidPosition = 0; if (!Helper.isNullOrEmpty(modSeparator)) { if (Helper.isNullOrEmpty(modValue)) { throw new LbryUriException(String.format("No modifier provided after separator %s", modSeparator)); } if ("#".equals(modSeparator) || ":".equals(modSeparator)) { claimId = modValue; } else if ("*".equals(modSeparator)) { claimSequence = Helper.parseInt(modValue, -1); } else if ("$".equals(modSeparator)) { bidPosition = Helper.parseInt(modValue, -1); } } if (!Helper.isNullOrEmpty(claimId) && (claimId.length() > CLAIM_ID_MAX_LENGTH || !claimId.matches("^[0-9a-f]+$"))) { throw new LbryUriException(String.format("Invalid claim ID %s", claimId)); } if (claimSequence == -1) { throw new LbryUriException("Claim sequence must be a number"); } if (bidPosition == -1) { throw new LbryUriException("Bid position must be a number"); } return new UriModifier(claimId, claimSequence, bidPosition); } } }
3e011449539e97aaeb6e1662be6d2aedab38e3bd
134
java
Java
src/zajecia11bootcamp/Hat.java
Konrad-code/NaukaCD
1f08750d65767bdb1a39f6369b1809a7159abfa9
[ "Unlicense" ]
null
null
null
src/zajecia11bootcamp/Hat.java
Konrad-code/NaukaCD
1f08750d65767bdb1a39f6369b1809a7159abfa9
[ "Unlicense" ]
null
null
null
src/zajecia11bootcamp/Hat.java
Konrad-code/NaukaCD
1f08750d65767bdb1a39f6369b1809a7159abfa9
[ "Unlicense" ]
null
null
null
12.181818
33
0.708955
448
package zajecia11bootcamp; public class Hat implements Wear{ @Override public void put() { System.out.println("on head"); } }
3e0114f994eeedddfee580ece7ae1061b6a979ed
2,787
java
Java
engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLTupleResultSet.java
guilhermejccavalcanti/ontop
3819f47622cfa0423c930d3671c7cb033af613b0
[ "Apache-2.0" ]
null
null
null
engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLTupleResultSet.java
guilhermejccavalcanti/ontop
3819f47622cfa0423c930d3671c7cb033af613b0
[ "Apache-2.0" ]
null
null
null
engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLTupleResultSet.java
guilhermejccavalcanti/ontop
3819f47622cfa0423c930d3671c7cb033af613b0
[ "Apache-2.0" ]
null
null
null
38.178082
151
0.729458
449
package it.unibz.inf.ontop.answering.resultset.impl; /* * #%L * ontop-reformulation-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * 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. * #L% */ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import it.unibz.inf.ontop.answering.reformulation.IRIDictionary; import it.unibz.inf.ontop.answering.resultset.TupleResultSet; import it.unibz.inf.ontop.dbschema.DBMetadata; import it.unibz.inf.ontop.exception.OntopConnectionException; import it.unibz.inf.ontop.utils.ImmutableCollectors; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; /** * Implementation of TupleResultSet for SQL queries, in the case where the IRI construction is delegated to the source * engine rather than post-processed. */ public class DelegatedIriSQLTupleResultSet extends AbstractSQLTupleResultSet implements TupleResultSet { private final ImmutableMap<String, Integer> columnMap; protected final JDBC2ConstantConverter ontopConstantRetriever; public DelegatedIriSQLTupleResultSet(ResultSet rs, ImmutableList<String> signature, DBMetadata dbMetadata, Optional<IRIDictionary> iriDictionary) { super(rs, signature); this.columnMap = buildColumnMap(); this.ontopConstantRetriever = new JDBC2ConstantConverter(dbMetadata, iriDictionary); } @Override protected DelegatedIriSQLBindingSet readCurrentRow() throws OntopConnectionException { SQLRowReader rowReader = new SQLRowReader(); try { final List<MainTypeLangValues> cells = rowReader.read(rs, getColumnCount()); return new DelegatedIriSQLBindingSet(cells, signature, columnMap, ontopConstantRetriever); } catch (SQLException e) { throw new OntopConnectionException(e); } } private ImmutableMap<String, Integer> buildColumnMap() { AtomicInteger i = new AtomicInteger(0); return signature.stream().sequential() .collect(ImmutableCollectors.toMap( v -> v, v -> i.incrementAndGet() )); } }
3e0116733b5c9834a87effbe3aae088c456e7ec9
8,017
java
Java
cyclops-futurestream/src/test/java/cyclops/futurestream/react/lazy/LazySeqAgronaTest.java
andyglick/cyclops-react
dc26bdad0f2b8a5aa87de4aa946ed52a0dbf00de
[ "ECL-2.0", "Apache-2.0" ]
937
2015-06-02T10:36:23.000Z
2022-03-28T11:16:22.000Z
cyclops-futurestream/src/test/java/cyclops/futurestream/react/lazy/LazySeqAgronaTest.java
preuss/cyclops
0be977662db87d2aaeac391a458ab3de0fe70d9b
[ "Apache-2.0" ]
631
2016-02-23T14:55:57.000Z
2018-09-27T16:57:13.000Z
cyclops-futurestream/src/test/java/cyclops/futurestream/react/lazy/LazySeqAgronaTest.java
preuss/cyclops
0be977662db87d2aaeac391a458ab3de0fe70d9b
[ "Apache-2.0" ]
118
2015-06-08T14:14:52.000Z
2022-03-18T18:43:32.000Z
34.556034
198
0.700511
450
package cyclops.futurestream.react.lazy; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.not; import static cyclops.data.tuple.Tuple.tuple; import static org.junit.Assert.assertThat; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import cyclops.futurestream.FutureStream; import cyclops.reactive.ReactiveSeq; import cyclops.data.tuple.Tuple2; import org.junit.Ignore; import org.junit.Test; import cyclops.futurestream.LazyReact; import com.oath.cyclops.async.adapters.Queue; import com.oath.cyclops.async.QueueFactories; import com.oath.cyclops.async.adapters.Signal; import com.oath.cyclops.react.ThreadPools; import cyclops.futurestream.react.base.BaseSeqTest; public class LazySeqAgronaTest extends BaseSeqTest { @Test public void testZipWithFutures(){ FutureStream stream = of("a","b"); FutureStream<Tuple2<Integer,String>> seq = of(1,2).actOnFutures().zip(stream); List<Tuple2<Integer,String>> result = seq.block();//.map(tuple -> Tuple.tuple(tuple.v1.join(),tuple.v2)).collect(CyclopsCollectors.toList()); assertThat(result.size(),is(asList(tuple(1,"a"),tuple(2,"b")).size())); } @Test public void testZipWithFuturesStream(){ Stream stream = of("a","b"); FutureStream<Tuple2<Integer,String>> seq = of(1,2).actOnFutures().zip(stream); List<Tuple2<Integer,String>> result = seq.block();//.map(tuple -> Tuple.tuple(tuple.v1.join(),tuple.v2)).collect(CyclopsCollectors.toList()); assertThat(result.size(),is(asList(tuple(1,"a"),tuple(2,"b")).size())); } @Test public void testZipWithFuturesCoreStream(){ Stream stream = Stream.of("a","b"); FutureStream<Tuple2<Integer,String>> seq = of(1,2).actOnFutures().zip(stream); List<Tuple2<Integer,String>> result = seq.block();//.map(tuple -> Tuple.tuple(tuple.v1.join(),tuple.v2)).collect(CyclopsCollectors.toList()); assertThat(result.size(),is(asList(tuple(1,"a"),tuple(2,"b")).size())); } @Test public void testZipFuturesWithIndex(){ FutureStream<Tuple2<String,Long>> seq = of("a","b").actOnFutures().zipWithIndex(); List<Tuple2<String,Long>> result = seq.block();//.map(tuple -> Tuple.tuple(tuple.v1.join(),tuple.v2)).collect(CyclopsCollectors.toList()); assertThat(result.size(),is(asList(tuple("a",0l),tuple("b",1l)).size())); } @Test public void duplicateFutures(){ List<String> list = of("a","b").actOnFutures().duplicate()._1().block(); System.out.println(list); assertThat(sortedList(list),is(asList("a","b"))); } private <T> List<T> sortedList(List<T> list) { return list.stream().sorted().collect(Collectors.toList()); } @Test public void duplicateFutures2(){ List<String> list = of("a","b").actOnFutures().duplicate()._2().block(); assertThat(sortedList(list),is(asList("a","b"))); } @Test public void batchSinceLastReadIterator() throws InterruptedException{ Iterator<Collection<Integer>> it = of(1,2,3,4,5,6).chunkLastReadIterator(); Thread.sleep(10); Collection one = it.next(); Collection two = it.next(); assertThat(one.size(),greaterThan(0)); assertThat(two.size(),greaterThan(0)); } @Test public void batchSinceLastRead() throws InterruptedException{ List<Collection> cols = of(1,2,3,4,5,6).chunkSinceLastRead() .peek(System.out::println) .peek(it->{sleep(50);}) .collect(Collectors.toList()); System.out.println(cols); System.out.println(cols.get(0)); assertThat(cols.get(0).size(),is(1)); assertThat(cols.size(),greaterThan(0)); } @Test public void zipFastSlow() { FutureStream<Integer> s; Queue q = new Queue(); LazyReact.parallelBuilder().generate(() -> sleep(100)) .then(it -> q.add("100")).runThread(new Thread()); new LazyReact().of(1, 2, 3, 4, 5, 6).zip(q.stream()) .peek(it -> System.out.println(it)) .collect(Collectors.toList()); } @Test public void testBackPressureWhenZippingUnevenStreams2() { Queue fast = LazyReact.parallelBuilder().withExecutor(new ForkJoinPool(2)).generateAsync(() -> "100") .withQueueFactory(QueueFactories.boundedQueue(10)).toQueue(); new Thread(() -> { LazyReact.parallelBuilder().withExecutor(new ForkJoinPool(2)).range(0,1000).peek(c -> sleep(10)) .zip(fast.stream()).forEach(it -> { }); }).start(); ; fast.setSizeSignal(Signal.queueBackedSignal()); int max = fast.getSizeSignal().getContinuous().stream() .mapToInt(it -> (int) it).limit(50).max().getAsInt(); assertThat(max, lessThan(11)); } @Test public void testOfType() { System.out.println("list: "+of(1, 2, 3,null).ofType(Integer.class).toList()); assertThat(of(1, "a", 2, "b", 3, null).ofType(Integer.class).toList(),containsInAnyOrder(1, 2, 3)); assertThat(of(1, "a", 2, "b", 3, null).ofType(Integer.class).toList(),not(containsInAnyOrder("a", "b",null))); assertThat(of(1, "a", 2, "b", 3, null) .ofType(Serializable.class).toList(),containsInAnyOrder(1, "a", 2, "b", 3)); } @Test @Ignore public void shouldZipTwoInfiniteSequences() throws Exception { final FutureStream<Integer> units = new LazyReact(ThreadPools.getCommonFreeThread()).iterate(1, n -> n+1); final FutureStream<Integer> hundreds = new LazyReact(ThreadPools.getCommonFreeThread()).iterate(100, n-> n+100); final ReactiveSeq<String> zipped = units.zip(hundreds, (n, p) -> n + ": " + p); assertThat(zipped.limit(5).join(),equalTo(of("1: 100", "2: 200", "3: 300", "4: 400", "5: 500").join())); } @Test public void shouldZipFiniteWithInfiniteSeq() throws Exception { ThreadPools.setUseCommon(false); final ReactiveSeq<Integer> units = new LazyReact(ThreadPools.getCommonFreeThread()).iterate(1, n -> n+1).limit(5); final FutureStream<Integer> hundreds = new LazyReact(ThreadPools.getCommonFreeThread()).iterate(100, n-> n+100); // <-- MEMORY LEAK! - no auto-closing yet, so writes infinetely to it's async queue final ReactiveSeq<String> zipped = units.zip(hundreds, (n, p) -> n + ": " + p); assertThat(zipped.limit(5).join(),equalTo(of("1: 100", "2: 200", "3: 300", "4: 400", "5: 500").join())); ThreadPools.setUseCommon(true); } @Test public void shouldZipInfiniteWithFiniteSeq() throws Exception { ThreadPools.setUseCommon(false); final FutureStream<Integer> units = new LazyReact(ThreadPools.getCommonFreeThread()).iterate(1, n -> n+1); // <-- MEMORY LEAK!- no auto-closing yet, so writes infinetely to it's async queue final ReactiveSeq<Integer> hundreds = new LazyReact(ThreadPools.getCommonFreeThread()).iterate(100, n-> n+100).limit(5); final ReactiveSeq<String> zipped = units.zip(hundreds, (n, p) -> n + ": " + p); assertThat(zipped.limit(5).join(),equalTo(of("1: 100", "2: 200", "3: 300", "4: 400", "5: 500").join())); ThreadPools.setUseCommon(true); } @Test public void testCastPast() { assertThat( of(1, "a", 2, "b", 3, null).capture(e -> e.printStackTrace()) .cast(Serializable.class).toList(),containsInAnyOrder(1, "a", 2, "b", 3, null)); } @Override protected <U> FutureStream<U> of(U... array) { return LazyReact.sequentialBuilder().of(array).boundedWaitFree(1000); } @Override protected <U> FutureStream<U> ofThread(U... array) { return LazyReact.sequentialCommonBuilder().of(array).boundedWaitFree(1000); } @Override protected <U> FutureStream<U> react(Supplier<U>... array) { return LazyReact.sequentialBuilder().ofAsync(array); } protected Object sleep(int i) { try { Thread.currentThread().sleep(i); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return i; } }
3e0116f26d416024423988ab7c641373db227945
4,675
java
Java
data/infinispan/src/main/java/org/teiid/spring/data/infinispan/InfinispanConfiguration.java
ciphereck/teiid-spring-boot
253f38b2709bda98c889ee931204bca60f26420d
[ "Apache-2.0" ]
37
2017-09-19T13:19:33.000Z
2021-10-15T08:51:04.000Z
data/infinispan/src/main/java/org/teiid/spring/data/infinispan/InfinispanConfiguration.java
ciphereck/teiid-spring-boot
253f38b2709bda98c889ee931204bca60f26420d
[ "Apache-2.0" ]
89
2017-05-22T09:32:52.000Z
2022-02-16T01:13:53.000Z
data/infinispan/src/main/java/org/teiid/spring/data/infinispan/InfinispanConfiguration.java
ciphereck/teiid-spring-boot
253f38b2709bda98c889ee931204bca60f26420d
[ "Apache-2.0" ]
56
2017-05-12T08:07:46.000Z
2021-12-28T14:35:38.000Z
27.023121
98
0.697968
451
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.spring.data.infinispan; import org.infinispan.client.hotrod.configuration.TransactionMode; import org.springframework.beans.factory.annotation.Value; public class InfinispanConfiguration implements org.teiid.infinispan.api.InfinispanConfiguration { private String url; private String cacheName; // security private String saslMechanism; private String username; private String password; private String authenticationRealm = "default"; private String authenticationServerName = "infinispan"; private String cacheTemplate; @Value("${teiid.ssl.trustStoreFileName:/etc/tls/private/truststore.pkcs12}") private String trustStoreFileName; @Value("${teiid.ssl.trustStorePassword:changeit}") private String trustStorePassword; @Value("${teiid.ssl.keyStoreFileName:/etc/tls/private/keystore.pkcs12}") private String keyStoreFileName; @Value("${teiid.ssl.keyStorePassword:changeit}") private String keyStorePassword; private TransactionMode transactionMode; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String getCacheName() { return cacheName; } public void setCacheName(String cacheName) { this.cacheName = cacheName; } @Override public String getSaslMechanism() { return saslMechanism; } public void setSaslMechanism(String saslMechanism) { this.saslMechanism = saslMechanism; } @Override public String getUsername() { return username; } public void setUsername(String userName) { this.username = userName; } @Override public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String getAuthenticationRealm() { return authenticationRealm; } public void setAuthenticationRealm(String authenticationRealm) { this.authenticationRealm = authenticationRealm; } @Override public String getAuthenticationServerName() { return authenticationServerName; } public void setAuthenticationServerName(String authenticationServerName) { this.authenticationServerName = authenticationServerName; } @Override public String getTrustStoreFileName() { return trustStoreFileName; } public void setTrustStoreFileName(String trustStoreFileName) { this.trustStoreFileName = trustStoreFileName; } @Override public String getTrustStorePassword() { return trustStorePassword; } public void setTrustStorePassword(String trustStorePassword) { this.trustStorePassword = trustStorePassword; } @Override public String getKeyStoreFileName() { return keyStoreFileName; } public void setKeyStoreFileName(String keyStoreFileName) { this.keyStoreFileName = keyStoreFileName; } @Override public String getKeyStorePassword() { return keyStorePassword; } public void setKeyStorePassword(String keyStorePassword) { this.keyStorePassword = keyStorePassword; } @Override public String getCacheTemplate() { return cacheTemplate; } public void setCacheTemplate(String cacheTemplate) { this.cacheTemplate = cacheTemplate; } public void setTransactionMode(TransactionMode transactionMode) { this.transactionMode = transactionMode; } @Override public String getTransactionMode() { if (transactionMode == null) { return null; } return transactionMode.name(); } @Override public String getRemoteServerList() { return url; } public void setRemoteServerList(String remoteSeverList) { this.url = remoteSeverList; } }
3e011719a9a4c287c98e7262bffd1fcd44de14f7
1,982
java
Java
toolkit-basic/src/main/java/pxf/toolkit/basic/lang/collection/GroupStatisticalMap.java
potatoxf/Toolkit
3b92c6a01ce49996907d291e7607e600eb04d934
[ "Apache-2.0" ]
null
null
null
toolkit-basic/src/main/java/pxf/toolkit/basic/lang/collection/GroupStatisticalMap.java
potatoxf/Toolkit
3b92c6a01ce49996907d291e7607e600eb04d934
[ "Apache-2.0" ]
null
null
null
toolkit-basic/src/main/java/pxf/toolkit/basic/lang/collection/GroupStatisticalMap.java
potatoxf/Toolkit
3b92c6a01ce49996907d291e7607e600eb04d934
[ "Apache-2.0" ]
null
null
null
19.431373
84
0.617558
452
package pxf.toolkit.basic.lang.collection; import java.util.HashMap; import java.util.Map; /** * 分组统计计算 * * @author potatoxf * @date 2021/5/15 */ public class GroupStatisticalMap<K> extends HashMap<K, Integer> { public static final int DEFAULT_INIT_VALUE = 0; private final int defaultInitValue; public GroupStatisticalMap() { this(DEFAULT_INIT_VALUE); } public GroupStatisticalMap(int defaultInitValue) { this.defaultInitValue = defaultInitValue; } /** * 在原来基础上加值,如果没有则创建值再加值 * * @param key 键 * @param value 值 * @return 返回新值 */ public int add(K key, int value) { Integer oldValue = get(key); int newValue; if (oldValue == null) { newValue = defaultInitValue + value; } else { newValue = oldValue + value; } put(key, newValue); return newValue; } /** * 在原来基础上自加值,如果没有则创建值自加值 * * @param key 键 * @return 返回新值 */ public int increase(K key) { return add(key, 1); } /** * 在原来基础上减值,如果没有则创建值再减值 * * @param key 键 * @param value 值 * @return 返回新值 */ public int sub(K key, int value) { Integer oldValue = get(key); int newValue; if (oldValue == null) { newValue = defaultInitValue - value; } else { newValue = oldValue - value; } put(key, newValue); return newValue; } /** * 在原来基础上自减值,如果没有则创建值自减值 * * @param key 键 * @return 返回新值 */ public int decrease(K key) { return sub(key, 1); } @Override public Integer put(K key, Integer value) { if (value == null) { value = defaultInitValue; } return super.put(key, value); } @Override public void putAll(Map<? extends K, ? extends Integer> m) { throw new UnsupportedOperationException("Does not support 'putAll' operations"); } @Override public Integer putIfAbsent(K key, Integer value) { if (value == null) { value = defaultInitValue; } return super.putIfAbsent(key, value); } }
3e0117c58613c59d026299d0d547b90e3c298f37
321
java
Java
src/traffic_web/src/main/java/traffic_web/tools/MessageSourceProvider.java
jwaliszko/msc-thesis
5ead9c3b4cf232a07c2c6df218d60eddd0a666ca
[ "MIT" ]
1
2015-11-10T10:35:55.000Z
2015-11-10T10:35:55.000Z
src/traffic_web/src/main/java/traffic_web/tools/MessageSourceProvider.java
JaroslawWaliszko/msc-thesis
5ead9c3b4cf232a07c2c6df218d60eddd0a666ca
[ "MIT" ]
null
null
null
src/traffic_web/src/main/java/traffic_web/tools/MessageSourceProvider.java
JaroslawWaliszko/msc-thesis
5ead9c3b4cf232a07c2c6df218d60eddd0a666ca
[ "MIT" ]
null
null
null
24.692308
67
0.806854
453
package traffic_web.tools; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; public class MessageSourceProvider implements MessageSourceAware { @Override public void setMessageSource(MessageSource arg0) { MessageAgent.setMessageSource(arg0); } }
3e0118a468ea9a0caad26b6b07cd2a4708d02d32
1,655
java
Java
src/slogo/model/ASTNodes/ASTAsk.java
tjysdsg/cs308-slogo
b2acbd0fbb78e6da8eb417281da7cc5717065cc8
[ "MIT" ]
null
null
null
src/slogo/model/ASTNodes/ASTAsk.java
tjysdsg/cs308-slogo
b2acbd0fbb78e6da8eb417281da7cc5717065cc8
[ "MIT" ]
null
null
null
src/slogo/model/ASTNodes/ASTAsk.java
tjysdsg/cs308-slogo
b2acbd0fbb78e6da8eb417281da7cc5717065cc8
[ "MIT" ]
null
null
null
27.131148
74
0.689426
454
package slogo.model.ASTNodes; import java.util.ArrayList; import java.util.List; import slogo.model.InfoBundle; import slogo.model.Turtle; /** * Children: * <ol> * <li>Compound statement containing indices of turtles</li> * <li>Compound statement containing commands to execute</li> * </ol> * * @author Jiyang Tang */ public class ASTAsk extends ASTCommand { private static final int NUM_PARAMS = 2; private static final String NAME = "Ask"; public ASTAsk() { super(NAME, NUM_PARAMS); } @Override protected double doEvaluate(InfoBundle info, List<ASTNode> params) { double ret = 0; // get previous active turtles so that we can restore them later List<Turtle> prevTurtles = info.getActiveTurtles(); ArrayList<Integer> prevTurtleIdx = new ArrayList<>(); for (Turtle t : prevTurtles) { prevTurtleIdx.add(t.getId()); } // get previous main turtle int prevMainTurtle = info.getMainTurtle().getId(); ASTCompoundStatement comp = (ASTCompoundStatement) params.get(0); ASTCompoundStatement commands = (ASTCompoundStatement) params.get(1); // run all commands for each turtle index for (ASTNode child : comp.getChildren()) { int idx = (int) child.evaluate(info); // only contains 1 index, so that ASTTurtleCommand works as intended ArrayList<Integer> indices = new ArrayList<>(); indices.add(idx); info.setCurrTurtle(indices); // run commands ret = commands.evaluate(info); } // restore previous active and main turtles info.setCurrTurtle(prevTurtleIdx); info.setMainTurtle(prevMainTurtle); return ret; } }
3e0118b54c2223501ac73e661b9ec4da1d2885f6
1,132
java
Java
divide2-core/src/main/java/com/divide2/basis/service/impl/CommentServiceImpl.java
bvvy/mj-demo
84be751380004b4915050562f2595287ac37f1b1
[ "MIT" ]
2
2019-06-10T04:10:34.000Z
2020-03-11T01:57:46.000Z
divide2-core/src/main/java/com/divide2/basis/service/impl/CommentServiceImpl.java
divide2/ying
84be751380004b4915050562f2595287ac37f1b1
[ "MIT" ]
null
null
null
divide2-core/src/main/java/com/divide2/basis/service/impl/CommentServiceImpl.java
divide2/ying
84be751380004b4915050562f2595287ac37f1b1
[ "MIT" ]
null
null
null
30.594595
127
0.780035
455
package com.divide2.basis.service.impl; import com.divide2.basis.model.Comment; import com.divide2.basis.repo.CommentRepository; import com.divide2.basis.service.CommentService; import com.divide2.core.basic.service.impl.SimpleBasicServiceImpl; import com.divide2.core.er.Loginer; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; /** * @author bvvy * @date 2018/7/19 */ @Service public class CommentServiceImpl extends SimpleBasicServiceImpl<Comment, Integer, CommentRepository> implements CommentService { private final CommentRepository commentRepository; public CommentServiceImpl(CommentRepository commentRepository) { this.commentRepository = commentRepository; } @Override public Page<Comment> findByToIdAndType(Integer toId, String type, Pageable pageable) { return commentRepository.findByToIdAndType(toId, type, pageable); } @Override public Page<Comment> findByUser(Pageable pageable) { return commentRepository.findByFromId(Loginer.userId(), pageable); } }
3e011918096f0485aa64698fbc377bbee4b35a41
2,018
java
Java
plugins/com.robotoworks.mechanoid.db.ui/src/com/robotoworks/mechanoid/db/ui/outline/SqliteModelOutlineTreeProvider.java
fluxtah/mechanoid
1c35bab2a7d524aa4108b5b66fa0bd65368ff774
[ "Apache-2.0" ]
null
null
null
plugins/com.robotoworks.mechanoid.db.ui/src/com/robotoworks/mechanoid/db/ui/outline/SqliteModelOutlineTreeProvider.java
fluxtah/mechanoid
1c35bab2a7d524aa4108b5b66fa0bd65368ff774
[ "Apache-2.0" ]
null
null
null
plugins/com.robotoworks.mechanoid.db.ui/src/com/robotoworks/mechanoid/db/ui/outline/SqliteModelOutlineTreeProvider.java
fluxtah/mechanoid
1c35bab2a7d524aa4108b5b66fa0bd65368ff774
[ "Apache-2.0" ]
null
null
null
28.828571
93
0.740337
456
/* * generated by Xtext */ package com.robotoworks.mechanoid.db.ui.outline; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.ui.editor.outline.IOutlineNode; import org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider; import org.eclipse.xtext.ui.editor.outline.impl.DocumentRootNode; import com.robotoworks.mechanoid.db.sqliteModel.ColumnDef; import com.robotoworks.mechanoid.db.sqliteModel.CreateIndexStatement; import com.robotoworks.mechanoid.db.sqliteModel.CreateTriggerStatement; import com.robotoworks.mechanoid.db.sqliteModel.CreateViewStatement; import com.robotoworks.mechanoid.db.sqliteModel.DropViewStatement; /** * customization of the default outline structure * */ public class SqliteModelOutlineTreeProvider extends DefaultOutlineTreeProvider { // @Inject // private StylerFactory stylerFactory; // // @Override // protected void createNode(IOutlineNode parent, EObject modelElement) { // super.createNode(parent, modelElement); // } // // @Override // protected Object _text(Object modelElement) { // if(modelElement instanceof MigrationBlock) { // return new StyledString("Migration"); // } else { // return super._text(modelElement); // } // } protected boolean _isLeaf(ColumnDef modelElement) { return true; } protected boolean _isLeaf(CreateViewStatement modelElement) { return true; } protected boolean _isLeaf(CreateTriggerStatement modelElement) { return true; } protected boolean _isLeaf(CreateIndexStatement modelElement) { return true; } protected boolean _isLeaf(DropViewStatement modelElement) { return true; } // @Override // protected void _createNode(DocumentRootNode parentNode, EObject modelElement) { // // if(modelElement instanceof CreateViewStatement) { // createEObjectNode(parentNode, modelElement, _image(modelElement), "qux", true); // } else { // super._createNode(parentNode, modelElement); // } // } }
3e0119574788de4d54ab9f45deceb7afacea6660
1,168
java
Java
src/main/java/cn/com/codingce/pojo/Invite.java
xzMhehe/bbs_codingce
6d99aef35bec4fc30859a9bc2761c1c54587c3e7
[ "MIT" ]
null
null
null
src/main/java/cn/com/codingce/pojo/Invite.java
xzMhehe/bbs_codingce
6d99aef35bec4fc30859a9bc2761c1c54587c3e7
[ "MIT" ]
null
null
null
src/main/java/cn/com/codingce/pojo/Invite.java
xzMhehe/bbs_codingce
6d99aef35bec4fc30859a9bc2761c1c54587c3e7
[ "MIT" ]
null
null
null
22.461538
53
0.729452
457
package cn.com.codingce.pojo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Date; /** * <p> * 实体类 * </p> * * @since 2021-01-01 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("ze_invite") @ApiModel(value="Invite邀请码", description="邀请码") public class Invite implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "自增id") @TableId(value = "id", type = IdType.AUTO) private Integer id; @ApiModelProperty(value = "邀请码") private String code; @ApiModelProperty(value = "用户id") private String uid; @ApiModelProperty(value = "状态 0 未使用 1 使用") private Integer status; @ApiModelProperty(value = "激活时间") private Date activeTime; @ApiModelProperty(value = "创建时间") private Date gmtCreate; }
3e011a1d682c2fca22dc7ad97d767004a5e2adbf
3,090
java
Java
installer/core/src/main/java/org/apache/sling/installer/core/impl/tasks/BundleRemoveTask.java
tteofili/sling
97be5ec4711d064dfb762e347fd9a92bf471ba29
[ "Apache-2.0" ]
5
2018-02-27T07:19:48.000Z
2021-11-08T14:21:32.000Z
installer/core/src/main/java/org/apache/sling/installer/core/impl/tasks/BundleRemoveTask.java
tteofili/sling
97be5ec4711d064dfb762e347fd9a92bf471ba29
[ "Apache-2.0" ]
6
2018-02-02T13:07:56.000Z
2022-03-12T14:40:50.000Z
installer/core/src/main/java/org/apache/sling/installer/core/impl/tasks/BundleRemoveTask.java
tteofili/sling
97be5ec4711d064dfb762e347fd9a92bf471ba29
[ "Apache-2.0" ]
6
2018-02-02T11:23:58.000Z
2022-03-12T14:35:11.000Z
40.657895
146
0.684142
458
/* * 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.sling.installer.core.impl.tasks; import org.apache.sling.installer.api.tasks.InstallationContext; import org.apache.sling.installer.api.tasks.ResourceState; import org.apache.sling.installer.api.tasks.TaskResourceGroup; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; /** Remove a bundle from a RegisteredResource. * Creates a SynchronousRefreshPackagesTask when * executed. */ public class BundleRemoveTask extends AbstractBundleTask { private static final String BUNDLE_REMOVE_ORDER = "30-"; public BundleRemoveTask(final TaskResourceGroup r, final TaskSupport creator) { super(r, creator); } /** * @see org.apache.sling.installer.api.tasks.InstallTask#execute(org.apache.sling.installer.api.tasks.InstallationContext) */ public void execute(InstallationContext ctx) { final String symbolicName = (String)getResource().getAttribute(Constants.BUNDLE_SYMBOLICNAME); final String version = (String)getResource().getAttribute(Constants.BUNDLE_VERSION); final Bundle b = BundleInfo.getMatchingBundle(this.getBundleContext(), symbolicName, version); if (b == null) { // nothing to do, so just stop this.setFinishedState(ResourceState.UNINSTALLED); return; } final int state = b.getState(); try { if (state == Bundle.ACTIVE || state == Bundle.STARTING) { b.stop(); } b.uninstall(); ctx.log("Uninstalled bundle {} from resource {}", b, getResource()); // if the bundle exported packages, we need to refresh if ( BundleUtil.getFragmentHostHeader(b) == null ) { RefreshBundlesTask.markBundleForRefresh(ctx, this.getTaskSupport(), b); } this.setFinishedState(ResourceState.UNINSTALLED); } catch (final BundleException be) { this.getLogger().info("Exception during removal of bundle " + this.getResource() + " : " + be.getMessage() + ". Retrying later.", be); } } @Override public String getSortKey() { return BUNDLE_REMOVE_ORDER + getResource().getURL(); } }
3e011ba411088cfdd336163a9b1a6d99af7370ef
637
java
Java
shop-manager/src/main/java/com/choco/manager/service/CookieService.java
finecola/shop-demo
d46e39b163a77ad6d8c1ce7ee6725d6c970c425a
[ "Apache-2.0" ]
null
null
null
shop-manager/src/main/java/com/choco/manager/service/CookieService.java
finecola/shop-demo
d46e39b163a77ad6d8c1ce7ee6725d6c970c425a
[ "Apache-2.0" ]
null
null
null
shop-manager/src/main/java/com/choco/manager/service/CookieService.java
finecola/shop-demo
d46e39b163a77ad6d8c1ce7ee6725d6c970c425a
[ "Apache-2.0" ]
null
null
null
21.233333
94
0.675039
459
package com.choco.manager.service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by choco on 2021/1/6 11:15 */ public interface CookieService { /** * 设置用户cookie * @param request * @param response * @param ticket * @return */ boolean setCookie(HttpServletRequest request, HttpServletResponse response,String ticket); /** * 获取cookie * @ request */ String getCookie(HttpServletRequest request); /** * 删除cookie */ boolean deleteCookie(HttpServletRequest request,HttpServletResponse response); }
3e011ba4625aa5bff7e7370040854d151d009ae2
1,436
java
Java
robolectric/src/test/java/org/robolectric/shadows/ShadowCookieSyncManagerTest.java
kriegfrj/robolectric
5cdc793166d8dfd8460330d4431237ed92cbe8d9
[ "MIT" ]
null
null
null
robolectric/src/test/java/org/robolectric/shadows/ShadowCookieSyncManagerTest.java
kriegfrj/robolectric
5cdc793166d8dfd8460330d4431237ed92cbe8d9
[ "MIT" ]
3
2021-02-03T19:37:53.000Z
2021-06-04T03:04:08.000Z
robolectric/src/test/java/org/robolectric/shadows/ShadowCookieSyncManagerTest.java
kriegfrj/robolectric
5cdc793166d8dfd8460330d4431237ed92cbe8d9
[ "MIT" ]
null
null
null
30.553191
84
0.770891
460
package org.robolectric.shadows; import android.app.Activity; import android.os.Build; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.TestRunners; import org.robolectric.annotation.Config; import static org.assertj.core.api.Assertions.assertThat; import static org.robolectric.Shadows.shadowOf; @RunWith(TestRunners.MultiApiWithDefaults.class) public class ShadowCookieSyncManagerTest { @Test public void testCreateInstance() { assertThat(CookieSyncManager.createInstance(new Activity())).isNotNull(); } @Test public void testGetInstance() { CookieSyncManager.createInstance(new Activity()); assertThat(CookieSyncManager.getInstance()).isNotNull(); } @Test @Config(sdk = { Build.VERSION_CODES.LOLLIPOP }) public void testSyncAndReset() { CookieSyncManager.createInstance(new Activity()); CookieSyncManager mgr = CookieSyncManager.getInstance(); ShadowCookieSyncManager shadowCookieSyncManager = shadowOf(mgr); ShadowCookieManager shadowCookieManager = shadowOf(CookieManager.getInstance()); assertThat(shadowCookieSyncManager.synced()).isFalse(); // TODO: API 21 -> sync moved to flush mgr.sync(); assertThat(shadowCookieManager.isFlushed()).isTrue(); shadowCookieManager.reset(); assertThat(shadowCookieManager.isFlushed()).isFalse(); } }
3e011c342d4f91b9a38cb29d383d78d943a4f9ab
3,455
java
Java
src/main/java/jenkins/plugins/itemstorage/s3/Downloads.java
daniel-beck-bot/jobcacher-plugin
6080e75fab6ec17f04f6261ebee7301e9581bc6a
[ "MIT" ]
11
2017-03-24T06:42:45.000Z
2020-06-23T09:39:33.000Z
src/main/java/jenkins/plugins/itemstorage/s3/Downloads.java
daniel-beck-bot/jobcacher-plugin
6080e75fab6ec17f04f6261ebee7301e9581bc6a
[ "MIT" ]
3
2020-02-28T15:52:45.000Z
2021-01-21T14:52:20.000Z
src/main/java/jenkins/plugins/itemstorage/s3/Downloads.java
daniel-beck-bot/jobcacher-plugin
6080e75fab6ec17f04f6261ebee7301e9581bc6a
[ "MIT" ]
19
2017-06-20T12:58:48.000Z
2022-03-01T09:26:39.000Z
36.755319
154
0.70246
461
/* * The MIT License * * Copyright 2016 Peter Hayes. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jenkins.plugins.itemstorage.s3; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.transfer.Download; import com.amazonaws.services.s3.transfer.TransferManager; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; /** * From the S3 Jenkins plugin modified a bit to meet this use case */ public final class Downloads { private static final Logger LOGGER = Logger.getLogger(Downloads.class.getName()); private final List<Memo> startedDownloads = new LinkedList<>(); public Downloads() {} public void startDownload(TransferManager manager, File base, String pathPrefix, S3ObjectSummary summary) throws AmazonServiceException, IOException { // calculate target file name File targetFile = FileUtils.getFile(base, summary.getKey().substring(pathPrefix.length() + 1)); // if target file exists, only download it if newer if (targetFile.lastModified() < summary.getLastModified().getTime()) { // ensure directory above file exists FileUtils.forceMkdir(targetFile.getParentFile()); // Start the download Download download = manager.download(summary.getBucketName(), summary.getKey(), targetFile); // Keep for later startedDownloads.add(new Memo(download, targetFile, summary.getLastModified().getTime())); } } public void finishDownloading() throws InterruptedException { for (Memo memo : startedDownloads) { memo.download.waitForCompletion(); if (!memo.file.setLastModified(memo.timestamp)) { LOGGER.warning("Could not set last modified time on " + memo.file); } } startedDownloads.clear(); } public int count() { return startedDownloads.size(); } private static class Memo { public Download download; public File file; public long timestamp; public Memo(Download download, File file, long timestamp) { this.download = download; this.file = file; this.timestamp = timestamp; } } }
3e011c89a63a876955ce865392d9ef248b15932c
32,591
java
Java
solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
anistor/lucene-solr
1bf718948696e69053bd5b7177b9ed32b5f57015
[ "Apache-2.0" ]
1
2019-04-29T09:07:03.000Z
2019-04-29T09:07:03.000Z
solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
anistor/lucene-solr
1bf718948696e69053bd5b7177b9ed32b5f57015
[ "Apache-2.0" ]
null
null
null
solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
anistor/lucene-solr
1bf718948696e69053bd5b7177b9ed32b5f57015
[ "Apache-2.0" ]
null
null
null
48.57079
186
0.725016
462
/* * 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.solr.cloud; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.UnaryOperator; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.apache.lucene.util.IOUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.CloudSolrClient; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.request.V2Request; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.RequestStatusState; import org.apache.solr.common.SolrException; import org.apache.solr.common.cloud.Aliases; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.Utils; import org.apache.zookeeper.KeeperException; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.apache.solr.common.cloud.ZkStateReader.ALIASES; public class AliasIntegrationTest extends SolrCloudTestCase { private CloseableHttpClient httpClient; private CloudSolrClient solrClient; @BeforeClass public static void setupCluster() throws Exception { configureCluster(2) .addConfig("conf", configset("cloud-minimal")) .configure(); } @Before @Override public void setUp() throws Exception { super.setUp(); solrClient = getCloudSolrClient(cluster); httpClient = (CloseableHttpClient) solrClient.getHttpClient(); } @After @Override public void tearDown() throws Exception { super.tearDown(); IOUtils.close(solrClient, httpClient); // make sure all aliases created are removed for the next test method Map<String, String> aliases = new CollectionAdminRequest.ListAliases().process(cluster.getSolrClient()).getAliases(); for (String alias : aliases.keySet()) { CollectionAdminRequest.deleteAlias(alias).process(cluster.getSolrClient()); } cluster.deleteAllCollections(); } @Test public void testMetadata() throws Exception { CollectionAdminRequest.createCollection("collection1meta", "conf", 2, 1).process(cluster.getSolrClient()); CollectionAdminRequest.createCollection("collection2meta", "conf", 1, 1).process(cluster.getSolrClient()); waitForState("Expected collection1 to be created with 2 shards and 1 replica", "collection1meta", clusterShape(2, 1)); waitForState("Expected collection2 to be created with 1 shard and 1 replica", "collection2meta", clusterShape(1, 1)); ZkStateReader zkStateReader = cluster.getSolrClient().getZkStateReader(); zkStateReader.createClusterStateWatchersAndUpdate(); List<String> aliases = zkStateReader.getAliases().resolveAliases("meta1"); assertEquals(1, aliases.size()); assertEquals("meta1", aliases.get(0)); UnaryOperator<Aliases> op6 = a -> a.cloneWithCollectionAlias("meta1", "collection1meta,collection2meta"); final ZkStateReader.AliasesManager aliasesManager = zkStateReader.aliasesManager; aliasesManager.applyModificationAndExportToZk(op6); aliases = zkStateReader.getAliases().resolveAliases("meta1"); assertEquals(2, aliases.size()); assertEquals("collection1meta", aliases.get(0)); assertEquals("collection2meta", aliases.get(1)); //ensure we have the back-compat format in ZK: final byte[] rawBytes = zkStateReader.getZkClient().getData(ALIASES, null, null, true); //noinspection unchecked assertTrue(((Map<String,Map<String,?>>)Utils.fromJSON(rawBytes)).get("collection").get("meta1") instanceof String); // set metadata UnaryOperator<Aliases> op5 = a -> a.cloneWithCollectionAliasMetadata("meta1", "foo", "bar"); aliasesManager.applyModificationAndExportToZk(op5); Map<String, String> meta = zkStateReader.getAliases().getCollectionAliasMetadata("meta1"); assertNotNull(meta); assertTrue(meta.containsKey("foo")); assertEquals("bar", meta.get("foo")); // set more metadata UnaryOperator<Aliases> op4 = a -> a.cloneWithCollectionAliasMetadata("meta1", "foobar", "bazbam"); aliasesManager.applyModificationAndExportToZk(op4); meta = zkStateReader.getAliases().getCollectionAliasMetadata("meta1"); assertNotNull(meta); // old metadata still there assertTrue(meta.containsKey("foo")); assertEquals("bar", meta.get("foo")); // new metadata added assertTrue(meta.containsKey("foobar")); assertEquals("bazbam", meta.get("foobar")); // remove metadata UnaryOperator<Aliases> op3 = a -> a.cloneWithCollectionAliasMetadata("meta1", "foo", null); aliasesManager.applyModificationAndExportToZk(op3); meta = zkStateReader.getAliases().getCollectionAliasMetadata("meta1"); assertNotNull(meta); // verify key was removed assertFalse(meta.containsKey("foo")); // but only the specified key was removed assertTrue(meta.containsKey("foobar")); assertEquals("bazbam", meta.get("foobar")); // removal of non existent key should succeed. UnaryOperator<Aliases> op2 = a -> a.cloneWithCollectionAliasMetadata("meta1", "foo", null); aliasesManager.applyModificationAndExportToZk(op2); // chained invocations UnaryOperator<Aliases> op1 = a -> a.cloneWithCollectionAliasMetadata("meta1", "foo2", "bazbam") .cloneWithCollectionAliasMetadata("meta1", "foo3", "bazbam2"); aliasesManager.applyModificationAndExportToZk(op1); // some other independent update (not overwritten) UnaryOperator<Aliases> op = a -> a.cloneWithCollectionAlias("meta3", "collection1meta,collection2meta"); aliasesManager.applyModificationAndExportToZk(op); // competing went through assertEquals("collection1meta,collection2meta", zkStateReader.getAliases().getCollectionAliasMap().get("meta3")); meta = zkStateReader.getAliases().getCollectionAliasMetadata("meta1"); assertNotNull(meta); // old metadata still there assertTrue(meta.containsKey("foobar")); assertEquals("bazbam", meta.get("foobar")); // competing update not overwritten assertEquals("collection1meta,collection2meta", zkStateReader.getAliases().getCollectionAliasMap().get("meta3")); // new metadata added assertTrue(meta.containsKey("foo2")); assertEquals("bazbam", meta.get("foo2")); assertTrue(meta.containsKey("foo3")); assertEquals("bazbam2", meta.get("foo3")); // now check that an independently constructed ZkStateReader can see what we've done. // i.e. the data is really in zookeeper String zkAddress = cluster.getZkServer().getZkAddress(); boolean createdZKSR = false; try(SolrZkClient zkClient = new SolrZkClient(zkAddress, 30000)) { ZkController.createClusterZkNodes(zkClient); zkStateReader = new ZkStateReader(zkClient); createdZKSR = true; zkStateReader.createClusterStateWatchersAndUpdate(); meta = zkStateReader.getAliases().getCollectionAliasMetadata("meta1"); assertNotNull(meta); // verify key was removed in independent view assertFalse(meta.containsKey("foo")); // but only the specified key was removed assertTrue(meta.containsKey("foobar")); assertEquals("bazbam", meta.get("foobar")); Aliases a = zkStateReader.getAliases(); Aliases clone = a.cloneWithCollectionAlias("meta1", null); meta = clone.getCollectionAliasMetadata("meta1"); assertEquals(0,meta.size()); } finally { if (createdZKSR) { zkStateReader.close(); } } } public void testModifyMetadataV2() throws Exception { final String aliasName = getTestName(); ZkStateReader zkStateReader = createColectionsAndAlias(aliasName); final String baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString(); //TODO fix Solr test infra so that this /____v2/ becomes /api/ HttpPost post = new HttpPost(baseUrl + "/____v2/c"); post.setEntity(new StringEntity("{\n" + "\"modify-alias\" : {\n" + " \"name\": \"" + aliasName + "\",\n" + " \"metadata\" : {\n" + " \"foo\": \"baz\",\n" + " \"bar\": \"bam\"\n" + " }\n" + //TODO should we use "NOW=" param? Won't work with v2 and is kinda a hack any way since intended for distrib " }\n" + "}", ContentType.APPLICATION_JSON)); assertSuccess(post); checkFooAndBarMeta(aliasName, zkStateReader); } public void testModifyMetadataV1() throws Exception { // note we don't use TZ in this test, thus it's UTC final String aliasName = getTestName(); ZkStateReader zkStateReader = createColectionsAndAlias(aliasName); final String baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString(); HttpGet get = new HttpGet(baseUrl + "/admin/collections?action=MODIFYALIAS" + "&wt=xml" + "&name=" + aliasName + "&metadata.foo=baz" + "&metadata.bar=bam"); assertSuccess(get); checkFooAndBarMeta(aliasName, zkStateReader); } public void testModifyMetadataCAR() throws Exception { // note we don't use TZ in this test, thus it's UTC final String aliasName = getTestName(); ZkStateReader zkStateReader = createColectionsAndAlias(aliasName); CollectionAdminRequest.ModifyAlias modifyAlias = CollectionAdminRequest.modifyAlias(aliasName); modifyAlias.addMetadata("foo","baz"); modifyAlias.addMetadata("bar","bam"); modifyAlias.process(cluster.getSolrClient()); checkFooAndBarMeta(aliasName, zkStateReader); // now verify we can delete modifyAlias = CollectionAdminRequest.modifyAlias(aliasName); modifyAlias.addMetadata("foo",""); modifyAlias.process(cluster.getSolrClient()); modifyAlias = CollectionAdminRequest.modifyAlias(aliasName); modifyAlias.addMetadata("bar",null); modifyAlias.process(cluster.getSolrClient()); modifyAlias = CollectionAdminRequest.modifyAlias(aliasName); // whitespace value modifyAlias.addMetadata("foo"," "); modifyAlias.process(cluster.getSolrClient()); } private void checkFooAndBarMeta(String aliasName, ZkStateReader zkStateReader) throws Exception { zkStateReader.aliasesManager.update(); // ensure our view is up to date Map<String, String> meta = zkStateReader.getAliases().getCollectionAliasMetadata(aliasName); assertNotNull(meta); assertTrue(meta.containsKey("foo")); assertEquals("baz", meta.get("foo")); assertTrue(meta.containsKey("bar")); assertEquals("bam", meta.get("bar")); } private ZkStateReader createColectionsAndAlias(String aliasName) throws SolrServerException, IOException, KeeperException, InterruptedException { CollectionAdminRequest.createCollection("collection1meta", "conf", 2, 1).process(cluster.getSolrClient()); CollectionAdminRequest.createCollection("collection2meta", "conf", 1, 1).process(cluster.getSolrClient()); waitForState("Expected collection1 to be created with 2 shards and 1 replica", "collection1meta", clusterShape(2, 1)); waitForState("Expected collection2 to be created with 1 shard and 1 replica", "collection2meta", clusterShape(1, 1)); ZkStateReader zkStateReader = cluster.getSolrClient().getZkStateReader(); zkStateReader.createClusterStateWatchersAndUpdate(); List<String> aliases = zkStateReader.getAliases().resolveAliases(aliasName); assertEquals(1, aliases.size()); assertEquals(aliasName, aliases.get(0)); UnaryOperator<Aliases> op6 = a -> a.cloneWithCollectionAlias(aliasName, "collection1meta,collection2meta"); final ZkStateReader.AliasesManager aliasesManager = zkStateReader.aliasesManager; aliasesManager.applyModificationAndExportToZk(op6); aliases = zkStateReader.getAliases().resolveAliases(aliasName); assertEquals(2, aliases.size()); assertEquals("collection1meta", aliases.get(0)); assertEquals("collection2meta", aliases.get(1)); return zkStateReader; } private void assertSuccess(HttpUriRequest msg) throws IOException { try (CloseableHttpResponse response = httpClient.execute(msg)) { if (200 != response.getStatusLine().getStatusCode()) { System.err.println(EntityUtils.toString(response.getEntity())); fail("Unexpected status: " + response.getStatusLine()); } } } // Rather a long title, but it's common to recommend when people need to re-index for any reason that they: // 1> create a new collection // 2> index the corpus to the new collection and verify it // 3> create an alias pointing to the new collection WITH THE SAME NAME as their original collection // 4> delete the old collection. // // They may or may not have an alias already pointing to the old collection that's being replaced. // If they don't already have an alias, this leaves them with: // // > a collection named old_collection // > a collection named new_collection // > an alias old_collection->new_collection // // What happens when they delete old_collection now? // // Current behavior is that delete "does the right thing" and deletes old_collection rather than new_collection, // but if this behavior changes it could be disastrous for users so this test insures that this behavior. // @Test public void testDeleteAliasWithExistingCollectionName() throws Exception { CollectionAdminRequest.createCollection("collection_old", "conf", 2, 1).process(cluster.getSolrClient()); CollectionAdminRequest.createCollection("collection_new", "conf", 1, 1).process(cluster.getSolrClient()); waitForState("Expected collection_old to be created with 2 shards and 1 replica", "collection_old", clusterShape(2, 1)); waitForState("Expected collection_new to be created with 1 shard and 1 replica", "collection_new", clusterShape(1, 1)); new UpdateRequest() .add("id", "6", "a_t", "humpty dumpy sat on a wall") .add("id", "7", "a_t", "humpty dumpy3 sat on a walls") .add("id", "8", "a_t", "humpty dumpy2 sat on a walled") .commit(cluster.getSolrClient(), "collection_old"); new UpdateRequest() .add("id", "1", "a_t", "humpty dumpy sat on an unfortunate wall") .commit(cluster.getSolrClient(), "collection_new"); QueryResponse res = cluster.getSolrClient().query("collection_old", new SolrQuery("*:*")); assertEquals(3, res.getResults().getNumFound()); // Let's insure we have a "handle" to the old collection CollectionAdminRequest.createAlias("collection_old_reserve", "collection_old").process(cluster.getSolrClient()); // This is the critical bit. The alias uses the _old collection name. CollectionAdminRequest.createAlias("collection_old", "collection_new").process(cluster.getSolrClient()); // aliases: collection_old->collection_new, collection_old_reserve -> collection_old -> collection_new // collections: collection_new and collection_old // Now we should only see the doc in collection_new through the collection_old alias res = cluster.getSolrClient().query("collection_old", new SolrQuery("*:*")); assertEquals(1, res.getResults().getNumFound()); // Now we should still transitively see collection_new res = cluster.getSolrClient().query("collection_old_reserve", new SolrQuery("*:*")); assertEquals(1, res.getResults().getNumFound()); // Now delete the old collection. This should fail since the collection_old_reserve points to collection_old RequestStatusState delResp = CollectionAdminRequest.deleteCollection("collection_old").processAndWait(cluster.getSolrClient(), 60); assertEquals("Should have failed to delete collection: ", delResp, RequestStatusState.FAILED); // assure ourselves that the old colletion is, indeed, still there. assertNotNull("collection_old should exist!", cluster.getSolrClient().getZkStateReader().getClusterState().getCollectionOrNull("collection_old")); // Now we should still succeed using the alias collection_old which points to collection_new // aliase: collection_old -> collection_new, collection_old_reserve -> collection_old -> collection_new // collections: collection_old, collection_new res = cluster.getSolrClient().query("collection_old", new SolrQuery("*:*")); assertEquals(1, res.getResults().getNumFound()); Aliases aliases = cluster.getSolrClient().getZkStateReader().getAliases(); assertTrue("collection_old should point to collection_new", aliases.resolveAliases("collection_old").contains("collection_new")); assertTrue("collection_old_reserve should point to collection_new", aliases.resolveAliases("collection_old_reserve").contains("collection_new")); // Clean up CollectionAdminRequest.deleteAlias("collection_old_reserve").processAndWait(cluster.getSolrClient(), 60); CollectionAdminRequest.deleteAlias("collection_old").processAndWait(cluster.getSolrClient(), 60); CollectionAdminRequest.deleteCollection("collection_new").processAndWait(cluster.getSolrClient(), 60); CollectionAdminRequest.deleteCollection("collection_old").processAndWait(cluster.getSolrClient(), 60); // collection_old already deleted as well as collection_old_reserve assertNull("collection_old_reserve should be gone", cluster.getSolrClient().getZkStateReader().getAliases().getCollectionAliasMap().get("collection_old_reserve")); assertNull("collection_old should be gone", cluster.getSolrClient().getZkStateReader().getAliases().getCollectionAliasMap().get("collection_old")); assertFalse("collection_new should be gone", cluster.getSolrClient().getZkStateReader().getClusterState().hasCollection("collection_new")); assertFalse("collection_old should be gone", cluster.getSolrClient().getZkStateReader().getClusterState().hasCollection("collection_old")); } // While writing the above test I wondered what happens when an alias points to two collections and one of them // is deleted. @Test public void testDeleteOneOfTwoCollectionsAliased() throws Exception { CollectionAdminRequest.createCollection("collection_one", "conf", 2, 1).process(cluster.getSolrClient()); CollectionAdminRequest.createCollection("collection_two", "conf", 1, 1).process(cluster.getSolrClient()); waitForState("Expected collection_one to be created with 2 shards and 1 replica", "collection_one", clusterShape(2, 1)); waitForState("Expected collection_two to be created with 1 shard and 1 replica", "collection_two", clusterShape(1, 1)); new UpdateRequest() .add("id", "1", "a_t", "humpty dumpy sat on a wall") .commit(cluster.getSolrClient(), "collection_one"); new UpdateRequest() .add("id", "10", "a_t", "humpty dumpy sat on a high wall") .add("id", "11", "a_t", "humpty dumpy sat on a low wall") .commit(cluster.getSolrClient(), "collection_two"); // Create an alias pointing to both CollectionAdminRequest.createAlias("collection_alias_pair", "collection_one,collection_two").process(cluster.getSolrClient()); QueryResponse res = cluster.getSolrClient().query("collection_alias_pair", new SolrQuery("*:*")); assertEquals(3, res.getResults().getNumFound()); // Now delete one of the collections, should fail since an alias points to it. RequestStatusState delResp = CollectionAdminRequest.deleteCollection("collection_one").processAndWait(cluster.getSolrClient(), 60); assertEquals("Should have failed to delete collection: ", delResp, RequestStatusState.FAILED); // Now redefine the alias to only point to colletion two CollectionAdminRequest.createAlias("collection_alias_pair", "collection_two").process(cluster.getSolrClient()); //Delete collection_one. delResp = CollectionAdminRequest.deleteCollection("collection_one").processAndWait(cluster.getSolrClient(), 60); assertEquals("Should not have failed to delete collection, it was removed from the alias: ", delResp, RequestStatusState.COMPLETED); // Should only see two docs now in second collection res = cluster.getSolrClient().query("collection_alias_pair", new SolrQuery("*:*")); assertEquals(2, res.getResults().getNumFound()); // We shouldn't be able to ping the deleted collection directly as // was deleted (and, assuming that it only points to collection_old). try { cluster.getSolrClient().query("collection_one", new SolrQuery("*:*")); } catch (SolrServerException se) { assertTrue(se.getMessage().contains("No live SolrServers")); } // Clean up CollectionAdminRequest.deleteAlias("collection_alias_pair").processAndWait(cluster.getSolrClient(), 60); CollectionAdminRequest.deleteCollection("collection_two").processAndWait(cluster.getSolrClient(), 60); // collection_one already deleted assertNull("collection_alias_pair should be gone", cluster.getSolrClient().getZkStateReader().getAliases().getCollectionAliasMap().get("collection_alias_pair")); assertFalse("collection_one should be gone", cluster.getSolrClient().getZkStateReader().getClusterState().hasCollection("collection_one")); assertFalse("collection_two should be gone", cluster.getSolrClient().getZkStateReader().getClusterState().hasCollection("collection_two")); } @Test public void test() throws Exception { CollectionAdminRequest.createCollection("collection1", "conf", 2, 1).process(cluster.getSolrClient()); CollectionAdminRequest.createCollection("collection2", "conf", 1, 1).process(cluster.getSolrClient()); waitForState("Expected collection1 to be created with 2 shards and 1 replica", "collection1", clusterShape(2, 1)); waitForState("Expected collection2 to be created with 1 shard and 1 replica", "collection2", clusterShape(1, 1)); new UpdateRequest() .add("id", "6", "a_t", "humpty dumpy sat on a wall") .add("id", "7", "a_t", "humpty dumpy3 sat on a walls") .add("id", "8", "a_t", "humpty dumpy2 sat on a walled") .commit(cluster.getSolrClient(), "collection1"); new UpdateRequest() .add("id", "9", "a_t", "humpty dumpy sat on a wall") .add("id", "10", "a_t", "humpty dumpy3 sat on a walls") .commit(cluster.getSolrClient(), "collection2"); /////////////// CollectionAdminRequest.createAlias("testalias1", "collection1").process(cluster.getSolrClient()); sleepToAllowZkPropagation(); // ensure that the alias has been registered assertEquals("collection1", new CollectionAdminRequest.ListAliases().process(cluster.getSolrClient()).getAliases().get("testalias1")); // search for alias searchSeveralWays("testalias1", new SolrQuery("*:*"), 3); // Use a comma delimited list, one of which is an alias searchSeveralWays("testalias1,collection2", new SolrQuery("*:*"), 5); /////////////// // test alias pointing to two collections. collection2 first because it's not on every node CollectionAdminRequest.createAlias("testalias2", "collection2,collection1").process(cluster.getSolrClient()); searchSeveralWays("testalias2", new SolrQuery("*:*"), 5); /////////////// // update alias CollectionAdminRequest.createAlias("testalias2", "collection2").process(cluster.getSolrClient()); sleepToAllowZkPropagation(); searchSeveralWays("testalias2", new SolrQuery("*:*"), 2); /////////////// // alias pointing to alias. One level of indirection is supported; more than that is not (may or may not work) // TODO dubious; remove? CollectionAdminRequest.createAlias("testalias3", "testalias2").process(cluster.getSolrClient()); searchSeveralWays("testalias3", new SolrQuery("*:*"), 2); /////////////// // Test 2 aliases pointing to the same collection CollectionAdminRequest.createAlias("testalias4", "collection2").process(cluster.getSolrClient()); CollectionAdminRequest.createAlias("testalias5", "collection2").process(cluster.getSolrClient()); // add one document to testalias4, thus to collection2 new UpdateRequest() .add("id", "11", "a_t", "humpty dumpy4 sat on a walls") .commit(cluster.getSolrClient(), "testalias4"); // thus gets added to collection2 searchSeveralWays("testalias4", new SolrQuery("*:*"), 3); //searchSeveralWays("testalias4,testalias5", new SolrQuery("*:*"), 3); /////////////// // use v2 API new V2Request.Builder("/collections") .withMethod(SolrRequest.METHOD.POST) .withPayload("{\"create-alias\": {\"name\": \"testalias6\", collections:[\"collection2\",\"collection1\"]}}") .build().process(cluster.getSolrClient()); searchSeveralWays("testalias6", new SolrQuery("*:*"), 6); // add one document to testalias6, which will route to collection2 because it's the first new UpdateRequest() .add("id", "12", "a_t", "humpty dumpy5 sat on a walls") .commit(cluster.getSolrClient(), "testalias6"); // thus gets added to collection2 searchSeveralWays("collection2", new SolrQuery("*:*"), 4); /////////////// for (int i = 1; i <= 6 ; i++) { CollectionAdminRequest.deleteAlias("testalias" + i).process(cluster.getSolrClient()); } sleepToAllowZkPropagation(); SolrException e = expectThrows(SolrException.class, () -> { SolrQuery q = new SolrQuery("*:*"); q.set("collection", "testalias1"); cluster.getSolrClient().query(q); }); assertTrue("Unexpected exception message: " + e.getMessage(), e.getMessage().contains("Collection not found: testalias1")); } /** * Sleep a bit to allow Zookeeper state propagation. * * Solr's view of the cluster is eventually consistent. *Eventually* all nodes and CloudSolrClients will be aware of * alias changes, but not immediately. If a newly created alias is queried, things should work right away since Solr * will attempt to see if it needs to get the latest aliases when it can't otherwise resolve the name. However * modifications to an alias will take some time. */ private void sleepToAllowZkPropagation() { try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } private void searchSeveralWays(String collectionList, SolrParams solrQuery, int expectedNumFound) throws IOException, SolrServerException { searchSeveralWays(collectionList, solrQuery, res -> assertEquals(expectedNumFound, res.getResults().getNumFound())); } private void searchSeveralWays(String collectionList, SolrParams solrQuery, Consumer<QueryResponse> responseConsumer) throws IOException, SolrServerException { if (random().nextBoolean()) { // cluster's CloudSolrClient responseConsumer.accept(cluster.getSolrClient().query(collectionList, solrQuery)); } else { // new CloudSolrClient (random shardLeadersOnly) try (CloudSolrClient solrClient = getCloudSolrClient(cluster)) { if (random().nextBoolean()) { solrClient.setDefaultCollection(collectionList); responseConsumer.accept(solrClient.query(null, solrQuery)); } else { responseConsumer.accept(solrClient.query(collectionList, solrQuery)); } } } // note: collectionList could be null when we randomly recurse and put the actual collection list into the // "collection" param and some bugs value into collectionList (including null). Only CloudSolrClient supports null. if (collectionList != null) { // HttpSolrClient JettySolrRunner jetty = cluster.getRandomJetty(random()); if (random().nextBoolean()) { try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString() + "/" + collectionList)) { responseConsumer.accept(client.query(null, solrQuery)); } } else { try (HttpSolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString())) { responseConsumer.accept(client.query(collectionList, solrQuery)); } } // Recursively do again; this time with the &collection= param if (solrQuery.get("collection") == null) { // put in "collection" param ModifiableSolrParams newParams = new ModifiableSolrParams(solrQuery); newParams.set("collection", collectionList); String maskedColl = new String[]{null, "bogus", "collection2", "collection1"}[random().nextInt(4)]; searchSeveralWays(maskedColl, newParams, responseConsumer); } } } @Test public void testErrorChecks() throws Exception { CollectionAdminRequest.createCollection("testErrorChecks-collection", "conf", 2, 1).process(cluster.getSolrClient()); waitForState("Expected testErrorChecks-collection to be created with 2 shards and 1 replica", "testErrorChecks-collection", clusterShape(2, 1)); ignoreException("."); // Invalid Alias name SolrException e = expectThrows(SolrException.class, () -> CollectionAdminRequest.createAlias("test:alias", "testErrorChecks-collection").process(cluster.getSolrClient())); assertEquals(SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code())); // Target collection doesn't exists e = expectThrows(SolrException.class, () -> CollectionAdminRequest.createAlias("testalias", "doesnotexist").process(cluster.getSolrClient())); assertEquals(SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code())); assertTrue(e.getMessage().contains("Can't create collection alias for collections='doesnotexist', 'doesnotexist' is not an existing collection or alias")); // One of the target collections doesn't exist e = expectThrows(SolrException.class, () -> CollectionAdminRequest.createAlias("testalias", "testErrorChecks-collection,doesnotexist").process(cluster.getSolrClient())); assertEquals(SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code())); assertTrue(e.getMessage().contains("Can't create collection alias for collections='testErrorChecks-collection,doesnotexist', 'doesnotexist' is not an existing collection or alias")); // Valid CollectionAdminRequest.createAlias("testalias", "testErrorChecks-collection").process(cluster.getSolrClient()); // TODO dubious; remove? CollectionAdminRequest.createAlias("testalias2", "testalias").process(cluster.getSolrClient()); // Alias + invalid e = expectThrows(SolrException.class, () -> CollectionAdminRequest.createAlias("testalias3", "testalias2,doesnotexist").process(cluster.getSolrClient())); assertEquals(SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code())); unIgnoreException("."); CollectionAdminRequest.deleteAlias("testalias").process(cluster.getSolrClient()); CollectionAdminRequest.deleteAlias("testalias2").process(cluster.getSolrClient()); CollectionAdminRequest.deleteCollection("testErrorChecks-collection"); } }
3e011db00c72b2d0ba48b0665edbbfe024752722
1,947
java
Java
parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java
akhishukla23/my-parfait
50d4cdf5a855483cf4bfd01a3a587a7a5fb805d5
[ "BSD-3-Clause" ]
null
null
null
parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java
akhishukla23/my-parfait
50d4cdf5a855483cf4bfd01a3a587a7a5fb805d5
[ "BSD-3-Clause" ]
null
null
null
parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java
akhishukla23/my-parfait
50d4cdf5a855483cf4bfd01a3a587a7a5fb805d5
[ "BSD-3-Clause" ]
null
null
null
39.734694
98
0.671289
463
package io.pcp.parfait; import io.pcp.parfait.DynamicMonitoringView; import java.lang.instrument.Instrumentation; import java.lang.management.ManagementFactory; import org.apache.log4j.Logger; import org.springframework.beans.BeansException; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ParfaitAgent { private static final Logger logger = Logger.getLogger(ParfaitAgent.class); public static void setupArguments(String arguments) { for (String propertyAndValue: arguments.split(",")) { String[] tokens = propertyAndValue.split(":", 2); if (tokens.length == 2) { String name = MonitoringViewProperties.PARFAIT + "." + tokens[0]; String value = tokens[1]; System.setProperty(name, value); } } } public static void premain(String arguments, Instrumentation instrumentation) { String runtimeName = ManagementFactory.getRuntimeMXBean().getName(); logger.debug(String.format("Agent runtime: %s [%s]", runtimeName, arguments)); // extract properties from arguments, properties files, or intuition MonitoringViewProperties.setupProperties(); if (arguments != null) { setupArguments(arguments); } String name = System.getProperty(MonitoringViewProperties.PARFAIT_NAME); logger.debug(String.format("Starting Parfait agent %s", name)); // inject all metrics via parfait-spring and parfait-jmx ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("agent.xml"); try { DynamicMonitoringView view = (DynamicMonitoringView)context.getBean("monitoringView"); view.start(); } catch (BeansException e) { logger.error("Stopping Parfait agent, cannot setup beans", e); } finally { context.close(); } } }
3e011dfa2fea7f586932be35bbd6a06100aa9fcd
11,437
java
Java
app/src/main/java/Utils/webservices/RequestExecutor.java
TecXra/GetFoneApp
a2b75de433f198123d67c273bb80152979fb9738
[ "Apache-2.0" ]
null
null
null
app/src/main/java/Utils/webservices/RequestExecutor.java
TecXra/GetFoneApp
a2b75de433f198123d67c273bb80152979fb9738
[ "Apache-2.0" ]
null
null
null
app/src/main/java/Utils/webservices/RequestExecutor.java
TecXra/GetFoneApp
a2b75de433f198123d67c273bb80152979fb9738
[ "Apache-2.0" ]
null
null
null
29.861619
139
0.677713
464
package Utils.webservices; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import gcm.play.android.samples.com.gcmquickstart.ContactsData; import gcm.play.android.samples.com.gcmquickstart.QuickstartPreferences; public class RequestExecutor extends AsyncTask<Object, Object, Object> { public AsyncResponse delegate = null; public Context con; public RequestExecutor(Context con) { super(); this.con = con; } @Override protected void onPostExecute(Object result) { delegate.onProcessCompelete( result); }; @Override protected String doInBackground(Object... params) { if (Utils.isNetworkAvailable(con)) { if ( params[0].equals("1")) return postContacts((ArrayList<ContactsData>)params[1]); else if ( params[0].equals("2")) return postReceivedSms((String)params[1],(String)params[2],(String)params[3]); // return postData(params); } else { return "Network error"; } return "Nothing"; } public String postReceivedSms(String Id,String number,String message) {// throws IOException try { HttpClient httpclient = Utils.getClient(); HttpPost httppost = new HttpPost(QuickstartPreferences.SERVER_HOST+ QuickstartPreferences.URL_Send_Receivevd_SMS); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("message", message)); formparams.add(new BasicNameValuePair("phone_number", number)); httppost.setEntity(new UrlEncodedFormEntity(formparams)); Log.i("SmsReceiver", "senderNum" + number+ " message: " + message); httpclient.execute(httppost); } catch (ClientProtocolException e) { // writing exception to log e.printStackTrace(); } catch (IOException e) { // writing exception to log e.printStackTrace(); } return "200"; /* HttpClient httpclient = Utils.getClient(); // Web URL HttpPost httpPost = new HttpPost("http://192.168.1.103/storerecieveconversation"); // httpclient.setRedirectHandler(new CustomRedirectHandler()); String returnData = "nothing.."; String _token = "heavy token"; try { // Data to send List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("message", message)); formparams.add(new BasicNameValuePair("phone_number", phoneNumber)); //Content Type UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); entity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(entity); // entity.setChunked(true); // HttpPost httpPost = new HttpPost(QuickstartPreferences.SERVER_HOST + QuickstartPreferences.URL_PATH); // httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setEntity(entity); LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy(); CloseableHttpClient httpclient1 = HttpClients.custom() .setRedirectStrategy(redirectStrategy) .build(); HttpClientContext context = HttpClientContext.create(); httpclient.execute(httpPost,context); //HttpContext httpContext = new BasicHttpContext(); //httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore()); // HttpResponse response = httpclient.execute(httpPost); //httpclient.execute(httpPost); //Log.d("resone","response is :"+response.toString()+"data is:"+response.getStatusLine()); // returnData = EntityUtils.toString(response.getEntity()); /* System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); System.out.println("Response Enity : \n" + response.getEntity()); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String inputLine; StringBuffer responseBuffer = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { responseBuffer.append(inputLine+"\n"); } reader.close(); // print result System.out.println(responseBuffer.toString()); } catch (ClientProtocolException e) { Log.d("Async Request", "Failed by client protocol"); } catch (IOException e) { Log.d("Async Request", "Failed by IO"); } */ } public String postContacts(ArrayList<ContactsData> contactsList) { HttpClient httpclient = Utils.getClient(); HttpPost httpPost = new HttpPost(QuickstartPreferences.SERVER_HOST+QuickstartPreferences.URL_Send_Contacts); // httpclient.setRedirectHandler(new CustomRedirectHandler()); String returnData = "200"; String _token = "heavy token"; try { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); // formparams.add(new BasicNameValuePair("id", "1")); for(int i = 0; i<contactsList.size();i++) { formparams.add(new BasicNameValuePair("name[]", contactsList.get(i).getName())); formparams.add(new BasicNameValuePair("number[]", contactsList.get(i).getNumber())); } httpPost.setEntity(new UrlEncodedFormEntity(formparams)); Log.i("ContactList", "name" + contactsList.get(0).getName()); httpclient.execute(httpPost); /* UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); httpPost.setEntity(entity); LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy(); CloseableHttpClient httpclient1 = HttpClients.custom() .setRedirectStrategy(redirectStrategy) .build(); HttpClientContext context = HttpClientContext.create(); //HttpContext httpContext = new BasicHttpContext(); //httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore()); httpclient1.execute(httpPost,context); */ /* System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); System.out.println("Response Enity : \n" + response.getEntity()); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String inputLine; StringBuffer responseBuffer = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { responseBuffer.append(inputLine+"\n"); } reader.close(); // print result System.out.println(responseBuffer.toString()); */ } catch (ClientProtocolException e) { Log.d("Async Request", "Failed by client protocol"); } catch (IOException e) { Log.d("Async Request", "Failed by IO"); } return returnData; } /* public String postContacts(ArrayList<ContactsData> contactsList) { HttpClient httpclient = Utils.getClient(); HttpPost httpPost = new HttpPost(QuickstartPreferences.SERVER_HOST+QuickstartPreferences.URL_Send_Contacts); // httpclient.setRedirectHandler(new CustomRedirectHandler()); String returnData = "200"; String _token = "heavy token"; try { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); // formparams.add(new BasicNameValuePair("id", "1")); for(int i = 0; i<contactsList.size();i++) { formparams.add(new BasicNameValuePair("name[]", contactsList.get(i).getName())); formparams.add(new BasicNameValuePair("number[]", contactsList.get(i).getNumber())); } httpPost.setEntity(new UrlEncodedFormEntity(formparams)); Log.i("ContactList", "name" + contactsList.get(0).getName()); httpclient.execute(httpPost); /* UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); httpPost.setEntity(entity); LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy(); CloseableHttpClient httpclient1 = HttpClients.custom() .setRedirectStrategy(redirectStrategy) .build(); HttpClientContext context = HttpClientContext.create(); //HttpContext httpContext = new BasicHttpContext(); //httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore()); httpclient1.execute(httpPost,context); */ /* System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); System.out.println("Response Enity : \n" + response.getEntity()); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String inputLine; StringBuffer responseBuffer = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { responseBuffer.append(inputLine+"\n"); } reader.close(); // print result System.out.println(responseBuffer.toString()); } catch (ClientProtocolException e) { Log.d("Async Request", "Failed by client protocol"); } catch (IOException e) { Log.d("Async Request", "Failed by IO"); } return returnData; } */ public String postData(Object... params) { String returnData = "contacts uploaded"; HttpClient httpClient = Utils.getClient(); HttpPost httpPost = new HttpPost(QuickstartPreferences.SERVER_HOST+QuickstartPreferences.URL_PATH); //"http://192.168.10.134/sendmessage" // Request parameters and other properties. List<NameValuePair> nVparams = new ArrayList<NameValuePair>(); nVparams.add(new BasicNameValuePair("sender", "09887")); nVparams.add(new BasicNameValuePair("message", "jjku")); try { httpPost.setEntity(new UrlEncodedFormEntity(nVparams, "UTF-8")); } catch (UnsupportedEncodingException e) { // writing error to Log e.printStackTrace(); } /* * Execute the HTTP Request */ try { HttpResponse response = httpClient.execute(httpPost); HttpEntity respEntity = response.getEntity(); if (respEntity != null) { // EntityUtils to get the response content returnData = EntityUtils.toString(respEntity); Log.i("TAG", "returnData: " + returnData); Log.d("returnData",returnData); } } catch (ClientProtocolException e) { // writing exception to log e.printStackTrace(); } catch (IOException e) { // writing exception to log e.printStackTrace(); } return returnData; } }
3e011e6f1584308bca26b3350ef834ea8fc06bd2
132
java
Java
Managers/APIKey.java
Shogatsu/Drake
46852e8272367ea3ad4737598964c34897198877
[ "Apache-2.0" ]
null
null
null
Managers/APIKey.java
Shogatsu/Drake
46852e8272367ea3ad4737598964c34897198877
[ "Apache-2.0" ]
1
2019-11-01T17:29:29.000Z
2019-11-01T17:29:29.000Z
Managers/APIKey.java
Shogatsu/Drake
46852e8272367ea3ad4737598964c34897198877
[ "Apache-2.0" ]
1
2019-11-01T17:26:59.000Z
2019-11-01T17:26:59.000Z
16.5
46
0.613636
465
package me.Shogatsu.TheDrakeProject.Managers; public class APIKey { public String getKey() { return ""; } }
3e011ef0429e590efd50acaa5c283df34c18d8ac
3,091
java
Java
src/main/java/fr/unix_experience/owncloud_sms/authenticators/OwnCloudAuthenticator.java
nerzhul/ncsms-android
599fe535159ea689f8b81be499891ac7cdf3cff7
[ "BSD-2-Clause" ]
28
2019-02-26T07:04:06.000Z
2021-11-07T20:17:41.000Z
src/main/java/fr/unix_experience/owncloud_sms/authenticators/OwnCloudAuthenticator.java
nerzhul/ncsms-android
599fe535159ea689f8b81be499891ac7cdf3cff7
[ "BSD-2-Clause" ]
42
2019-01-24T10:30:50.000Z
2022-02-25T09:47:52.000Z
src/main/java/fr/unix_experience/owncloud_sms/authenticators/OwnCloudAuthenticator.java
nerzhul/ncsms-android
599fe535159ea689f8b81be499891ac7cdf3cff7
[ "BSD-2-Clause" ]
21
2019-01-24T08:53:25.000Z
2022-03-17T22:08:10.000Z
31.333333
79
0.770793
466
package fr.unix_experience.owncloud_sms.authenticators; /* * Copyright (c) 2014-2015, Loic Blot <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.accounts.NetworkErrorException; import android.content.Context; import android.content.Intent; import android.os.Bundle; import fr.unix_experience.owncloud_sms.activities.LoginActivity; public class OwnCloudAuthenticator extends AbstractAccountAuthenticator { // Simple constructor public OwnCloudAuthenticator(Context context) { super(context); _context = context; } @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { // TODO Auto-generated method stub return null; } @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { Bundle result; Intent intent; intent = new Intent(_context, LoginActivity.class); result = new Bundle(); result.putParcelable(AccountManager.KEY_INTENT, intent); return result; } @Override public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { // TODO Auto-generated method stub return null; } @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { // TODO Auto-generated method stub return null; } @Override public String getAuthTokenLabel(String authTokenType) { // TODO Auto-generated method stub return null; } @Override public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { // TODO Auto-generated method stub return null; } @Override public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException { // TODO Auto-generated method stub return null; } private final Context _context; private static final String TAG = OwnCloudAuthenticator.class.getSimpleName(); }
3e011f071087fc9471c036d29ba27ff2310e8173
1,674
java
Java
client/src/test/java/client/KafkaReciverTest.java
s6056826/netty-pubsub
ef18f171216308173149a7036399153a8a023e98
[ "MIT" ]
69
2019-01-14T00:47:44.000Z
2022-03-13T16:47:47.000Z
client/src/test/java/client/KafkaReciverTest.java
jieyuanfei/netty-pubsub
ef18f171216308173149a7036399153a8a023e98
[ "MIT" ]
3
2019-01-24T03:16:10.000Z
2020-03-16T09:18:59.000Z
client/src/test/java/client/KafkaReciverTest.java
jieyuanfei/netty-pubsub
ef18f171216308173149a7036399153a8a023e98
[ "MIT" ]
27
2019-01-14T03:02:43.000Z
2022-03-07T06:10:02.000Z
42.923077
106
0.679211
467
package client; import java.util.Arrays; import java.util.Collection; import java.util.Properties; import org.apache.kafka.clients.consumer.ConsumerRebalanceListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.TopicPartition; public class KafkaReciverTest { public static void main(String[] args) { Properties properties = new Properties(); properties.put("bootstrap.servers", "127.0.0.1:9092"); properties.put("group.id", "group-3"); properties.put("enable.auto.commit", "true"); properties.put("auto.commit.interval.ms", "1000"); properties.put("auto.offset.reset", "earliest"); properties.put("session.timeout.ms", "30000"); properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); //properties.put("value.deserializer", "client.KafkaDeSerialization"); KafkaConsumer<String, TestMsg> kafkaConsumer = new KafkaConsumer<>(properties); kafkaConsumer.subscribe(Arrays.asList("HelloWorld")); while (true) { ConsumerRecords<String, TestMsg> records = kafkaConsumer.poll(100); if(records.count()>0) for (ConsumerRecord<String, TestMsg> record : records) { System.out.printf("offset = %d, value = %s", record.offset(), record.value()); System.out.println(); } } } }
3e011f793db73e08e0c2e3c6cfda52418d8d3e82
2,878
java
Java
app/src/main/java/com/yibh/mytest/utils/BitmapUtil.java
yihaha/YTest
608f6bdcaf67ad11e280ca149cfb0d640338fa34
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yibh/mytest/utils/BitmapUtil.java
yihaha/YTest
608f6bdcaf67ad11e280ca149cfb0d640338fa34
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yibh/mytest/utils/BitmapUtil.java
yihaha/YTest
608f6bdcaf67ad11e280ca149cfb0d640338fa34
[ "Apache-2.0" ]
null
null
null
33.858824
101
0.626129
468
package com.yibh.mytest.utils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * Created by y on 2016/5/26. */ public class BitmapUtil { /** * 上传服务器时把图片调用下面方法压缩后 保存到临时文件夹 图片压缩后小于200KB,失真度不明显 * * @param path * @return * @throws IOException */ public static Bitmap revitionImageSize(String path) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream( new File(path))); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(in, null, options); in.close(); int i = 0; Bitmap bitmap = null; // options.inJustDecodeBounds=true那么将不返回实际的bitmap对象,不给其分配内存空间但是可以得到一些解码边界信息即图片大小等信息 // outHeight(图片原始高度)和 outWidth(图片的原始宽度) // inSampleSize表示缩略图大小为原始图片大小的几分之一 // options.outWidth >> i(右移运算符)表示:outWidth/(2^i) while (true) { if ((options.outWidth >> i <= 2000) && (options.outHeight >> i <= 2000)) { in = new BufferedInputStream( new FileInputStream(new File(path))); options.inSampleSize = (int) Math.pow(2.0D, i); // 幂运算 i为几次方 options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeStream(in, null, options); break; } i += 1; } return bitmap; } /** * 将图片放大或缩小到指定尺寸 */ public static Bitmap resizeImage(Bitmap source, int w, int h) { int width = source.getWidth(); int height = source.getHeight(); float scaleWidth = ((float) w) / width; float scaleHeight = ((float) h) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(source, 0, 0, width, height, matrix, true); } /** * 将图片剪裁为圆形 */ public static Bitmap createCircleImage(Bitmap source) { int length = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight(); Paint paint = new Paint(); paint.setAntiAlias(true); Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(target); canvas.drawCircle(length / 2, length / 2, length / 2, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(source, 0, 0, paint); return target; } }
3e01205c638801b47a3fd81669de949db45414e3
2,506
java
Java
core/src/main/java/io/dekorate/kubernetes/decorator/ApplyImageDecorator.java
ap4k/ap4k
56d082696b26c1e22a06dc0fcd65e670b8caa531
[ "Apache-2.0" ]
62
2018-11-24T14:50:29.000Z
2019-07-04T11:10:29.000Z
core/src/main/java/io/dekorate/kubernetes/decorator/ApplyImageDecorator.java
ap4k/ap4k
56d082696b26c1e22a06dc0fcd65e670b8caa531
[ "Apache-2.0" ]
138
2018-11-21T16:31:20.000Z
2019-07-03T19:32:31.000Z
core/src/main/java/io/dekorate/kubernetes/decorator/ApplyImageDecorator.java
ap4k/ap4k
56d082696b26c1e22a06dc0fcd65e670b8caa531
[ "Apache-2.0" ]
14
2018-11-15T21:11:50.000Z
2019-06-25T15:05:29.000Z
35.295775
121
0.727055
469
/** * Copyright 2018 The original authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dekorate.kubernetes.decorator; import java.util.Arrays; import java.util.List; import io.dekorate.ConfigReference; import io.dekorate.WithConfigReferences; import io.dekorate.utils.Strings; import io.fabric8.kubernetes.api.model.ContainerFluent; public class ApplyImageDecorator extends ApplicationContainerDecorator<ContainerFluent> implements WithConfigReferences { private final String image; public ApplyImageDecorator(String containerName, String image) { super(ANY, containerName); this.image = image; } public ApplyImageDecorator(String deploymentName, String containerName, String image) { super(deploymentName, containerName); this.image = image; } @Override public void andThenVisit(ContainerFluent container) { container.withImage(image); } public Class<? extends Decorator>[] after() { return new Class[] { ResourceProvidingDecorator.class, ApplyApplicationContainerDecorator.class, AddSidecarDecorator.class }; } @Override public List<ConfigReference> getConfigReferences() { return Arrays.asList(buildConfigReferenceForImage()); } private ConfigReference buildConfigReferenceForImage() { String property = "image"; String path = "spec.template.spec.containers.image"; if (!Strings.equals(getDeploymentName(), ANY) && !Strings.equals(getContainerName(), ANY)) { path = "(metadata.name == " + getDeploymentName() + ")].spec.template.spec.containers" + ".(name == " + getContainerName() + ").image"; } else if (!Strings.equals(getDeploymentName(), ANY)) { path = "(metadata.name == " + getDeploymentName() + ").spec.template.spec.containers.image"; } else if (!Strings.equals(getContainerName(), ANY)) { path = "spec.template.spec.containers.(name == " + getContainerName() + ").image"; } return new ConfigReference(property, path, image); } }
3e01206fb83c8b0ea214cbd7b35e29db456d8ea7
9,821
java
Java
juice-commons/src/main/java/juice/util/DecimalUtils.java
TFdream/juice
e0d8ad6a8d901a8cd7a1d16eb67c9928735965fb
[ "Apache-2.0" ]
37
2018-04-26T03:48:06.000Z
2022-03-16T03:31:17.000Z
juice-commons/src/main/java/juice/util/DecimalUtils.java
TFdream/juice
e0d8ad6a8d901a8cd7a1d16eb67c9928735965fb
[ "Apache-2.0" ]
1
2021-03-16T05:39:43.000Z
2021-03-16T05:39:43.000Z
juice-commons/src/main/java/juice/util/DecimalUtils.java
TFdream/juice
e0d8ad6a8d901a8cd7a1d16eb67c9928735965fb
[ "Apache-2.0" ]
22
2018-08-13T01:14:07.000Z
2022-03-16T03:34:19.000Z
34.339161
93
0.647897
470
package juice.util; import java.math.BigDecimal; /** * @author Ricky Fung */ public final class DecimalUtils { private DecimalUtils() {} private static final int DEFAULT_SCALE = 2; private static final int INT_ZERO = 0; //========== public static final BigDecimal MINUS_ONE = new BigDecimal("-1"); public static final BigDecimal ZERO = BigDecimal.ZERO; public static final BigDecimal ONE = BigDecimal.ONE; public static final BigDecimal TEN = BigDecimal.TEN; public static final BigDecimal TWENTY = new BigDecimal("20.00"); public static final BigDecimal FIFTY = new BigDecimal("50.00"); public static final BigDecimal ONE_HUNDRED = new BigDecimal("100.00"); public static final BigDecimal TWO_HUNDRED = new BigDecimal("200.00"); public static final BigDecimal FIVE_HUNDRED = new BigDecimal("500.00"); public static final BigDecimal ONE_THOUSAND = new BigDecimal("1000.00"); public static final BigDecimal TWO_THOUSAND = new BigDecimal("2000.00"); public static final BigDecimal FIVE_THOUSAND = new BigDecimal("5000.00"); public static final BigDecimal TEN_THOUSAND = new BigDecimal("10000.00"); //=======基本类型 public static BigDecimal valueOf(double num) { return new BigDecimal(Double.toString(num)); } public static BigDecimal valueOf(float num) { return new BigDecimal(Float.toString(num)); } public static BigDecimal valueOf(int num) { return new BigDecimal(Integer.toString(num)); } public static BigDecimal valueOf(long num) { return new BigDecimal(Long.toString(num)); } //=======包装类型 public static BigDecimal valueOf(Double num) { return new BigDecimal(num.toString()); } public static BigDecimal valueOf(Float num) { return new BigDecimal(num.toString()); } public static BigDecimal valueOf(Integer num) { return new BigDecimal(num.toString()); } public static BigDecimal valueOf(Long num) { return new BigDecimal(num.toString()); } public static BigDecimal valueOf(String val) { return new BigDecimal(val); } //=======格式化为字符串 public static String format(BigDecimal bd) { return bd.setScale(DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP).toString(); } public static String format(BigDecimal bd, int scale) { return bd.setScale(scale, BigDecimal.ROUND_HALF_UP).toString(); } public static String format(BigDecimal bd, int scale, int roundingMode) { return bd.setScale(scale, roundingMode).toString(); } //=======设置精度 public static BigDecimal setScale(BigDecimal bd, int scale) { return bd.setScale(scale, BigDecimal.ROUND_HALF_UP); } /** * * @param bd * @param scale * @param roundingMode 取值参考 BigDecimal.ROUND_HALF_UP 等 * @return */ public static BigDecimal setScale(BigDecimal bd, int scale, int roundingMode) { return bd.setScale(scale, roundingMode); } //=======求最小值 public static int min(int num1, int num2) { return num1 < num2 ? num1 : num2; } public static int min(int num1, int num2, int num3) { int min = num1 < num2 ? num1 : num2; return min < num3 ? min : num3; } public static long min(long num1, long num2) { return num1 < num2 ? num1 : num2; } public static long min(long num1, long num2, long num3) { long min = num1 < num2 ? num1 : num2; return min < num3 ? min : num3; } public static BigDecimal min(BigDecimal num1, BigDecimal num2) { return num1.compareTo(num2) < INT_ZERO ? num1 : num2; } public static BigDecimal min(BigDecimal num1, BigDecimal num2, BigDecimal num3) { BigDecimal min = num1.compareTo(num2) < INT_ZERO ? num1 : num2; return min.compareTo(num3) < INT_ZERO ? min : num3; } //=======求最大值 public static int max(int num1, int num2) { return num1 > num2 ? num1 : num2; } public static int max(int num1, int num2, int num3) { int max = num1 > num2 ? num1 : num2; return max > num3 ? max : num3; } public static long max(long num1, long num2) { return num1 > num2 ? num1 : num2; } public static long max(long num1, long num2, long num3) { long max = num1 > num2 ? num1 : num2; return max > num3 ? max : num3; } public static BigDecimal max(BigDecimal num1, BigDecimal num2) { return num1.compareTo(num2) > INT_ZERO ? num1 : num2; } public static BigDecimal max(BigDecimal num1, BigDecimal num2, BigDecimal num3) { BigDecimal max = num1.compareTo(num2) > INT_ZERO ? num1 : num2; return max.compareTo(num3) > INT_ZERO ? max : num3; } //=======加法 public static BigDecimal add(int v1, int v2) { BigDecimal b1 = new BigDecimal(Integer.toString(v1)); BigDecimal b2 = new BigDecimal(Integer.toString(v2)); return b1.add(b2); } public static BigDecimal add(long v1, long v2) { BigDecimal b1 = new BigDecimal(Long.toString(v1)); BigDecimal b2 = new BigDecimal(Long.toString(v2)); return b1.add(b2); } public static BigDecimal add(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2); } public static BigDecimal add(BigDecimal b1, BigDecimal b2) { return b1.add(b2); } public static BigDecimal add(BigDecimal b1, BigDecimal b2, int scale) { return b1.add(b2).setScale(scale, BigDecimal.ROUND_HALF_UP); } public static BigDecimal add(BigDecimal b1, BigDecimal b2, int scale, int roundingMode) { return b1.add(b2).setScale(scale, roundingMode); } //=======减法 public static BigDecimal sub(int v1, int v2) { BigDecimal b1 = new BigDecimal(Integer.toString(v1)); BigDecimal b2 = new BigDecimal(Integer.toString(v2)); return b1.subtract(b2); } public static BigDecimal sub(long v1, long v2) { BigDecimal b1 = new BigDecimal(Long.toString(v1)); BigDecimal b2 = new BigDecimal(Long.toString(v2)); return b1.subtract(b2); } public static BigDecimal sub(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2); } public static BigDecimal sub(BigDecimal b1, BigDecimal b2) { return b1.subtract(b2); } public static BigDecimal sub(BigDecimal b1, BigDecimal b2, int scale) { return b1.subtract(b2).setScale(scale, BigDecimal.ROUND_HALF_UP); } public static BigDecimal sub(BigDecimal b1, BigDecimal b2, int scale, int roundingMode) { return b1.subtract(b2).setScale(scale, roundingMode); } //=======乘法 public static BigDecimal mul(int v1, int v2) { BigDecimal b1 = new BigDecimal(Integer.toString(v1)); BigDecimal b2 = new BigDecimal(Integer.toString(v2)); return b1.multiply(b2); } public static BigDecimal mul(long v1, long v2) { BigDecimal b1 = new BigDecimal(Long.toString(v1)); BigDecimal b2 = new BigDecimal(Long.toString(v2)); return b1.multiply(b2); } public static BigDecimal mul(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2); } public static BigDecimal mul(BigDecimal b1, BigDecimal b2) { return b1.multiply(b2); } public static BigDecimal mul(BigDecimal b1, BigDecimal b2, int scale) { return b1.multiply(b2).setScale(scale, BigDecimal.ROUND_HALF_UP); } public static BigDecimal mul(BigDecimal b1, BigDecimal b2, int scale, int roundingMode) { return b1.multiply(b2).setScale(scale, roundingMode); } //=======除法 public static BigDecimal div(int v1, int v2) { return div(v1, v2, DEFAULT_SCALE); } public static BigDecimal div(int v1, int v2, int scale) { BigDecimal b1 = new BigDecimal(Integer.toString(v1)); BigDecimal b2 = new BigDecimal(Integer.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP);//四舍五入 } public static BigDecimal div(long v1, long v2) { return div(v1, v2, DEFAULT_SCALE); } public static BigDecimal div(long v1, long v2, int scale) { BigDecimal b1 = new BigDecimal(Long.toString(v1)); BigDecimal b2 = new BigDecimal(Long.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP);//四舍五入,保留两位小数 } public static BigDecimal div(double v1, double v2) { return div(v1, v2, DEFAULT_SCALE); } public static BigDecimal div(double v1, double v2, int scale) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP);//四舍五入 } public static BigDecimal div(double v1, double v2, int scale, int roundingMode) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.divide(b2, scale, roundingMode); } //============= public static BigDecimal div(BigDecimal v1, BigDecimal v2) { return div(v1, v2, DEFAULT_SCALE); } public static BigDecimal div(BigDecimal b1, BigDecimal b2, int scale) { return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP);//四舍五入 } public static BigDecimal div(BigDecimal b1, BigDecimal b2, int scale, int roundingMode) { return b1.divide(b2, scale, roundingMode); } }
3e01209f64df2ec51e3b61b3fbda3f31b6148164
591
java
Java
app/src/main/java/com/example/android/openweather/data/model/Coord.java
sumitsh55/test
f1dfe4c2498e29eec15556922c3df0dd1619bbac
[ "MIT" ]
null
null
null
app/src/main/java/com/example/android/openweather/data/model/Coord.java
sumitsh55/test
f1dfe4c2498e29eec15556922c3df0dd1619bbac
[ "MIT" ]
null
null
null
app/src/main/java/com/example/android/openweather/data/model/Coord.java
sumitsh55/test
f1dfe4c2498e29eec15556922c3df0dd1619bbac
[ "MIT" ]
null
null
null
16.416667
51
0.619289
471
package com.example.android.openweather.data.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by David on 07/02/2017. */ public class Coord { @SerializedName("lon") @Expose private Double lon; @SerializedName("lat") @Expose private Double lat; public Double getLon() { return lon; } public void setLon(Double lon) { this.lon = lon; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } }
3e0123a66b0cb230781ac9592a20144ed2920e73
3,441
java
Java
openjdk11/test/hotspot/jtreg/compiler/graalunit/com.oracle.mxtool.junit/com/oracle/mxtool/junit/TimingDecorator.java
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
null
null
null
openjdk11/test/hotspot/jtreg/compiler/graalunit/com.oracle.mxtool.junit/com/oracle/mxtool/junit/TimingDecorator.java
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
null
null
null
openjdk11/test/hotspot/jtreg/compiler/graalunit/com.oracle.mxtool.junit/com/oracle/mxtool/junit/TimingDecorator.java
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
null
null
null
33.735294
99
0.671898
472
/* * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.mxtool.junit; import java.util.HashMap; import java.util.Map; import org.junit.runner.Description; /** * Timing support for JUnit test runs. */ class TimingDecorator extends MxRunListenerDecorator { private long startTime; private long classStartTime; private Description currentTest; final Map<Class<?>, Long> classTimes; final Map<Description, Long> testTimes; TimingDecorator(MxRunListener l) { super(l); this.classTimes = new HashMap<>(); this.testTimes = new HashMap<>(); } @Override public void testClassStarted(Class<?> clazz) { classStartTime = System.nanoTime(); super.testClassStarted(clazz); } @Override public void testClassFinished(Class<?> clazz, int numPassed, int numFailed) { long totalTime = System.nanoTime() - classStartTime; super.testClassFinished(clazz, numPassed, numFailed); if (beVerbose()) { getWriter().print(' ' + valueToString(totalTime)); } classTimes.put(clazz, totalTime / 1_000_000); } @Override public void testStarted(Description description) { currentTest = description; startTime = System.nanoTime(); super.testStarted(description); } @Override public void testFinished(Description description) { long totalTime = System.nanoTime() - startTime; super.testFinished(description); if (beVerbose()) { getWriter().print(" " + valueToString(totalTime)); } currentTest = null; testTimes.put(description, totalTime / 1_000_000); } private static String valueToString(long valueNS) { long timeWholeMS = valueNS / 1_000_000; long timeFractionMS = (valueNS / 100_000) % 10; return String.format("%d.%d ms", timeWholeMS, timeFractionMS); } /** * Gets the test currently starting but not yet completed along with the number of milliseconds * it has been executing. * * @return {@code null} if there is no test currently executing */ public Object[] getCurrentTestDuration() { Description current = currentTest; if (current != null) { long timeMS = (System.nanoTime() - startTime) / 1_000_000; return new Object[]{current, timeMS}; } return null; } }
3e0123e3e237f6ff84e9a10db6df6ee5af10b37c
2,793
java
Java
src/main/java/org/logicng/formulas/CFalse.java
tnstrssnr/LogicNG
994294fbb283b7b96230da3937369bf8fc062b5f
[ "Apache-2.0" ]
92
2016-01-22T08:46:39.000Z
2022-03-15T20:18:54.000Z
src/main/java/org/logicng/formulas/CFalse.java
tnstrssnr/LogicNG
994294fbb283b7b96230da3937369bf8fc062b5f
[ "Apache-2.0" ]
29
2016-05-14T09:07:42.000Z
2022-02-22T07:40:23.000Z
src/main/java/org/logicng/formulas/CFalse.java
tnstrssnr/LogicNG
994294fbb283b7b96230da3937369bf8fc062b5f
[ "Apache-2.0" ]
18
2016-01-13T20:50:40.000Z
2022-01-26T18:04:44.000Z
41.073529
75
0.361976
473
/////////////////////////////////////////////////////////////////////////// // __ _ _ ________ // // / / ____ ____ _(_)____/ | / / ____/ // // / / / __ \/ __ `/ / ___/ |/ / / __ // // / /___/ /_/ / /_/ / / /__/ /| / /_/ / // // /_____/\____/\__, /_/\___/_/ |_/\____/ // // /____/ // // // // The Next Generation Logic Library // // // /////////////////////////////////////////////////////////////////////////// // // // Copyright 2015-20xx Christoph Zengler // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // // implied. See the License for the specific language governing // // permissions and limitations under the License. // // // /////////////////////////////////////////////////////////////////////////// package org.logicng.formulas; import org.logicng.datastructures.Assignment; /** * Boolean constant "False". * @version 1.0 * @since 1.0 */ public final class CFalse extends Constant { /** * Constructor. * @param factory the factory which created this instance */ CFalse(final FormulaFactory factory) { super(FType.FALSE, factory); } @Override public boolean evaluate(final Assignment assignment) { return false; } @Override public Constant negate() { return this.f.verum(); } @Override public int hashCode() { return -42; } @Override public boolean equals(final Object other) { return other instanceof CFalse; } }
3e0125417777cb905faf3262abbb626e8af06a36
12,369
java
Java
foundation/eclipselink.extension.oracle.nosql.test/src/org/eclipse/persistence/testing/tests/nosql/NoSQLProperties.java
marschall/eclipselink.runtime
3d59eaa9e420902d5347b9fb60fbe6c92310894b
[ "BSD-3-Clause" ]
null
null
null
foundation/eclipselink.extension.oracle.nosql.test/src/org/eclipse/persistence/testing/tests/nosql/NoSQLProperties.java
marschall/eclipselink.runtime
3d59eaa9e420902d5347b9fb60fbe6c92310894b
[ "BSD-3-Clause" ]
2
2021-03-24T17:58:46.000Z
2021-12-14T20:59:52.000Z
foundation/eclipselink.extension.oracle.nosql.test/src/org/eclipse/persistence/testing/tests/nosql/NoSQLProperties.java
marschall/eclipselink.runtime
3d59eaa9e420902d5347b9fb60fbe6c92310894b
[ "BSD-3-Clause" ]
null
null
null
42.071429
117
0.649931
474
/******************************************************************************* * Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * 03/30/2016-2.7 Tomas Kraus * - 490677: Initial API and implementation. ******************************************************************************/ package org.eclipse.persistence.testing.tests.nosql; import java.util.HashMap; import java.util.Map; import org.eclipse.persistence.config.PersistenceUnitProperties; import org.eclipse.persistence.eis.EISLogin; import org.eclipse.persistence.logging.AbstractSessionLog; import org.eclipse.persistence.logging.SessionLog; import org.eclipse.persistence.nosql.adapters.nosql.OracleNoSQLConnectionSpec; import org.eclipse.persistence.testing.framework.junit.JUnitTestCaseHelper; /** * NoSQL test suite properties. */ public class NoSQLProperties { /** Logger. */ private static final SessionLog LOG = AbstractSessionLog.getLog(); /** NoSQL database URL property prefix. */ private static final String NOSQL_URL_KEY_PREFIX = "nosql.url"; /** NoSQL database URL build property name. */ public static final String NOSQL_URL_KEY = JUnitTestCaseHelper.insertIndex(NOSQL_URL_KEY_PREFIX, null); /** Relational database URL build property name. */ private static final String DB_URL_KEY = JUnitTestCaseHelper.insertIndex(JUnitTestCaseHelper.DB_URL_KEY, null); /** Relational database user name build property name. */ private static final String DB_USER_KEY = JUnitTestCaseHelper.insertIndex(JUnitTestCaseHelper.DB_USER_KEY, null); /** Relational database user password build property name. */ private static final String DB_PWD_KEY = JUnitTestCaseHelper.insertIndex(JUnitTestCaseHelper.DB_PWD_KEY, null); /** Relational database driver class build property name. */ private static final String DB_DRIVER_KEY = JUnitTestCaseHelper.insertIndex(JUnitTestCaseHelper.DB_DRIVER_KEY, null); /** Relational database platform class build property name. */ private static final String DB_PLATFORM_KEY = JUnitTestCaseHelper.insertIndex(JUnitTestCaseHelper.DB_PLATFORM_KEY, null); // NoSQL related persistence unit property names. /** The persistence unit property key for the MongoDB connection host name or IP. */ public static final String PROPERTY_NOSQL_HOST_KEY = PersistenceUnitProperties.NOSQL_PROPERTY + "nosql.host"; /** The persistence unit property key for the MongoDB connection port. */ public static final String PROPERTY_NOSQL_PORT_KEY = PersistenceUnitProperties.NOSQL_PROPERTY + "nosql.port"; /** The persistence unit property key for the MongoDB database name. */ public static final String PROPERTY_NOSQL_STORE_KEY = PersistenceUnitProperties.NOSQL_PROPERTY + "nosql.store"; // Default properties values if not set. /** Default NoSQL database host. */ private static final String DEFAULT_HOST = "localhost"; /** Default NoSQL database store. */ private static final String DEFAULT_STORE = "kvstore"; /** Database PU properties {@link Map} from the build properties. Shared for whole test suite. */ public static final Map<String, String> properties = buildProperties(); /** * Get database URL from configuration properties. * @return Database URL. */ public static String getDBURL() { return properties.get(PersistenceUnitProperties.JDBC_URL); } /** * Get database user name from configuration properties. * @return Database user name. */ public static String getDBUserName() { return properties.get(PersistenceUnitProperties.JDBC_USER); } /** * Get database user password from configuration properties. * @return Database user password. */ public static String getDBPassword() { return properties.get(PersistenceUnitProperties.JDBC_PASSWORD); } /** * Get database JDBC driver from configuration properties. * @return Database JDBC driver. */ public static String getDBDriver() { return properties.get(PersistenceUnitProperties.JDBC_DRIVER); } /** * Get database platform class name from configuration properties. * @return Database platform class name. */ public static String getDBPlatform() { return properties.get(PersistenceUnitProperties.TARGET_DATABASE); } /** * Get NoSQL database URL from configuration properties. * @return NoSQL database URL. */ public static String getNoSQLURL() { final String host = properties.get(PROPERTY_NOSQL_HOST_KEY); final String port = properties.get(PROPERTY_NOSQL_PORT_KEY); final String store = properties.get(PROPERTY_NOSQL_STORE_KEY); final StringBuilder sb = new StringBuilder((host != null ? host.length() : 0) + (port != null ? port.length() + 1 : 0) + (store != null ? store.length() : 0) + NoSQLURI.KEYWORD.length() + 1); sb.append(NoSQLURI.KEYWORD); if (host != null) { sb.append(host); } if (port != null) { sb.append(':'); sb.append(port); } sb.append('/'); if (store != null) { sb.append(store); } return sb.toString(); } /** * Process and add {@code nosql.url} property. * @param properties Test properties {@link Map} being built. */ private static void processNoSqlUrl(final Map<String, String> properties) { final String noSqlUrl = JUnitTestCaseHelper.getProperty(NOSQL_URL_KEY); if (noSqlUrl != null && NoSQLURI.startsUri(noSqlUrl)) { final NoSQLURI uri = new NoSQLURI(noSqlUrl); final String host = uri.getHost(); final int port = uri.getPort(); final String store = uri.getStore(); if (host != null) { properties.put(PROPERTY_NOSQL_HOST_KEY, host); } else { properties.put(PROPERTY_NOSQL_HOST_KEY, DEFAULT_HOST); } if (port >= 0) { properties.put(PROPERTY_NOSQL_PORT_KEY, Integer.toString(port)); } if (store != null) { properties.put(PROPERTY_NOSQL_STORE_KEY, store); } else { properties.put(PROPERTY_NOSQL_STORE_KEY, DEFAULT_STORE); } } } /** * Process and add simple build property. * @param properties Test properties {@link Map} being built. * @param buildKey Property key in build properties. * @param puKey Property key in jUnit test. */ private static void processProperty( final Map<String, String> properties, final String buildKey, final String testKey) { final String value = JUnitTestCaseHelper.getProperty(buildKey); LOG.log(SessionLog.FINER, String.format("Property %s -> %s :: %s", buildKey, testKey, value != null ? value : "N/A")); if (value != null) { properties.put(testKey, value); } } /** * Create test properties {@link Map} from build properties. * @return Persistence unit properties {@link Map}. */ private static Map<String, String> buildProperties() { final Map<String, String> properties = new HashMap<>(); processNoSqlUrl(properties); processProperty(properties, DB_URL_KEY, PersistenceUnitProperties.JDBC_URL); processProperty(properties, DB_USER_KEY, PersistenceUnitProperties.JDBC_USER); processProperty(properties, DB_PWD_KEY, PersistenceUnitProperties.JDBC_PASSWORD); processProperty(properties, DB_DRIVER_KEY, PersistenceUnitProperties.JDBC_DRIVER); processProperty(properties, DB_PLATFORM_KEY, PersistenceUnitProperties.TARGET_DATABASE); return properties; } /** * Build NoSQL connection property containing host and port concatenated. * @param host NoSQL connection host property. * @param port NoSQL connection port property. * @return Property containing host and port concatenated. */ private static String buildHostPort(final String host, final String port) { if (host != null) { final StringBuilder hostPort = new StringBuilder(host.length() + (port != null ? port.length() + 1 : 0)); hostPort.append(host); if (port != null) { hostPort.append(':'); hostPort.append(port); } return hostPort.toString(); } else { return null; } } /** * Build NoSQL mapped connection property containing host and port concatenated. * @param host NoSQL connection host property. * @param port NoSQL connection port property. * @return Property containing host and port concatenated. */ private static String buildMappedHostPort(final String host, final String port) { if (host != null) { final StringBuilder hostPort = new StringBuilder( 2 * host.length() + (port != null ? 2 * port.length() + 3 : 1)); hostPort.append(host); if (port != null) { hostPort.append(':'); hostPort.append(port); } hostPort.append(','); hostPort.append(host); if (port != null) { hostPort.append(':'); hostPort.append(port); } return hostPort.toString(); } else { return null; } } /** * Set EIS login connection information for NoSQL database. * @param login Target {@link EISLogin} instance. * @param properties Persistence unit properties {@link Map}. */ public static void setEISLoginProperties(final EISLogin login) { final String hostPort = buildHostPort( properties.get(PROPERTY_NOSQL_HOST_KEY), properties.get(PROPERTY_NOSQL_PORT_KEY)); final String store = properties.get(PROPERTY_NOSQL_STORE_KEY); LOG.log(SessionLog.FINE, String.format("NoSQL connection: NoSQL://%s/%s", hostPort, store)); if (hostPort != null) { login.setProperty(OracleNoSQLConnectionSpec.HOST, hostPort); } if (store != null) { login.setProperty(OracleNoSQLConnectionSpec.STORE, store); } } /** * Build EIS login connection information for {@code EntityManager} NoSQL database connection. * Host and port pair property is normal (not mapped). * @return {@code EntityManager} NoSQL database connection properties. */ public static Map<String, String> createEMProperties() { return createEMProperties(false); } /** * Build EIS login connection information for {@code EntityManager} NoSQL database connection. * @param mapped Build mapped property for the same host and port pair when {@code true} or normal property * otherwise. * @return {@code EntityManager} NoSQL database connection properties. */ public static Map<String, String> createEMProperties(final boolean mapped) { final String host = properties.get(PROPERTY_NOSQL_HOST_KEY); final String port = properties.get(PROPERTY_NOSQL_PORT_KEY); final String store = properties.get(PROPERTY_NOSQL_STORE_KEY); final String hostPort = mapped ? buildMappedHostPort(host, port) : buildHostPort(host, port); final Map<String, String> emProperties = new HashMap<>(2); LOG.log(SessionLog.FINE, String.format("NoSQL connection: NoSQL://%s/%s", hostPort, store)); if (hostPort != null) { emProperties.put(PROPERTY_NOSQL_HOST_KEY, hostPort); } if (store != null) { emProperties.put(PROPERTY_NOSQL_STORE_KEY, store); } return emProperties; } }
3e0125854047613fd1e49cf18f0fed7af8e1d74c
2,257
java
Java
gdx-graph/src/com/gempukku/libgdx/graph/plugin/lighting3d/Lighting3DPluginRuntimeInitializer.java
MarcinSc/libgdx-graph
e53366140eed4b549574ae2546981ac200037972
[ "MIT" ]
49
2020-08-19T06:59:34.000Z
2022-01-06T08:26:12.000Z
gdx-graph/src/com/gempukku/libgdx/graph/plugin/lighting3d/Lighting3DPluginRuntimeInitializer.java
MarcinSc/libgdx-graph
e53366140eed4b549574ae2546981ac200037972
[ "MIT" ]
1
2021-11-17T03:42:36.000Z
2021-11-17T03:42:36.000Z
gdx-graph/src/com/gempukku/libgdx/graph/plugin/lighting3d/Lighting3DPluginRuntimeInitializer.java
MarcinSc/libgdx-graph
e53366140eed4b549574ae2546981ac200037972
[ "MIT" ]
6
2020-09-10T19:55:47.000Z
2021-09-08T01:22:44.000Z
49.065217
161
0.811697
475
package com.gempukku.libgdx.graph.plugin.lighting3d; import com.gempukku.libgdx.graph.plugin.PluginRegistry; import com.gempukku.libgdx.graph.plugin.PluginRegistryImpl; import com.gempukku.libgdx.graph.plugin.PluginRuntimeInitializer; import com.gempukku.libgdx.graph.plugin.lighting3d.producer.*; import com.gempukku.libgdx.graph.shader.common.CommonShaderConfiguration; public class Lighting3DPluginRuntimeInitializer implements PluginRuntimeInitializer { private static int maxNumberOfDirectionalLights; private static int maxNumberOfPointLights; private static int maxNumberOfSpotlights; public static void register() { register(5, 2, 2); } public static void register(int maxNumberOfDirectionalLights, int maxNumberOfPointLights, int maxNumberOfSpotlights) { Lighting3DPluginRuntimeInitializer.maxNumberOfDirectionalLights = maxNumberOfDirectionalLights; Lighting3DPluginRuntimeInitializer.maxNumberOfPointLights = maxNumberOfPointLights; Lighting3DPluginRuntimeInitializer.maxNumberOfSpotlights = maxNumberOfSpotlights; PluginRegistryImpl.register(Lighting3DPluginRuntimeInitializer.class); } private Lighting3DPrivateData data = new Lighting3DPrivateData(); @Override public void initialize(PluginRegistry pluginRegistry) { CommonShaderConfiguration.register(new BlinnPhongLightingShaderNodeBuilder(maxNumberOfDirectionalLights, maxNumberOfPointLights, maxNumberOfSpotlights)); CommonShaderConfiguration.register(new PhongLightingShaderNodeBuilder(maxNumberOfDirectionalLights, maxNumberOfPointLights, maxNumberOfSpotlights)); CommonShaderConfiguration.register(new ApplyNormalMapShaderNodeBuilder()); CommonShaderConfiguration.register(new AmbientLightShaderNodeBuilder()); CommonShaderConfiguration.register(new DirectionalLightShaderNodeBuilder()); CommonShaderConfiguration.register(new PointLightShaderNodeBuilder()); CommonShaderConfiguration.register(new SpotLightShaderNodeBuilder()); pluginRegistry.registerPrivateData(Lighting3DPrivateData.class, data); pluginRegistry.registerPublicData(Lighting3DPublicData.class, data); } @Override public void dispose() { } }
3e0125edfe9d30912ae8d8b297bdcdb3c4607926
1,276
java
Java
src/main/java/com/pointlion/handler/GlobalHandler.java
847967214/joa
b652f583bfbe3f55901119f1c8faf8918f8f5315
[ "Apache-2.0" ]
3
2021-03-27T02:17:45.000Z
2021-03-27T09:24:59.000Z
src/main/java/com/pointlion/handler/GlobalHandler.java
847967214/joa
b652f583bfbe3f55901119f1c8faf8918f8f5315
[ "Apache-2.0" ]
1
2020-05-08T13:55:08.000Z
2020-05-08T13:55:08.000Z
src/main/java/com/pointlion/handler/GlobalHandler.java
847967214/joa
b652f583bfbe3f55901119f1c8faf8918f8f5315
[ "Apache-2.0" ]
1
2020-11-09T23:59:45.000Z
2020-11-09T23:59:45.000Z
31.121951
114
0.738245
476
/** * @author Lion * @date 2017年1月24日 下午12:02:35 * @qq 439635374 */ package com.pointlion.handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jfinal.core.Action; import com.jfinal.core.JFinal; import com.jfinal.handler.Handler; import com.jfinal.render.RenderManager; import com.pointlion.mvc.common.utils.ContextUtil; /** * 全局Handler,设置一些通用功能 * 描述:主要是一些全局变量的设置,再就是日志记录开始和结束操作 */ public class GlobalHandler extends Handler { // private static final ServerLog log = ServerLog.getLog(GlobalHandler.class); private static final RenderManager renderManager = RenderManager.me(); @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled){ response.setHeader("Access-Control-Allow-Origin","*");//允许跨域请求 String ctx = request.getContextPath(); ContextUtil.setCtx(ctx); request.setAttribute("ctx", ctx);//设置全局上下文 String[] urlPara = {null}; Action action = JFinal.me().getAction(target, urlPara); if(action==null){ renderManager.getRenderFactory().getRender("/error/404.html").setContext(request, response).render(); return; } next.handle(target, request, response, isHandled); } }
3e0126d02b7d4d1fa697ef425911e2ee0986614f
4,669
java
Java
hw03-0036480046_old/src/test/java/hr/fer/zemris/java/custom/scripting/lexer/LexerSmartTest.java
Daria2002/Java_hw
017b245c622753ad56fe03be1aa099b6a8f7e140
[ "MIT" ]
null
null
null
hw03-0036480046_old/src/test/java/hr/fer/zemris/java/custom/scripting/lexer/LexerSmartTest.java
Daria2002/Java_hw
017b245c622753ad56fe03be1aa099b6a8f7e140
[ "MIT" ]
8
2020-09-14T19:45:12.000Z
2021-12-14T20:56:42.000Z
hw03-0036480046_old/src/test/java/hr/fer/zemris/java/custom/scripting/lexer/LexerSmartTest.java
Daria2002/Java_hw
017b245c622753ad56fe03be1aa099b6a8f7e140
[ "MIT" ]
null
null
null
34.843284
88
0.695652
477
package hr.fer.zemris.java.custom.scripting.lexer; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import com.sun.source.tree.AssertTree; public class LexerSmartTest { @Test void testNullInput() { assertThrows(NullPointerException.class, () -> new LexerSmart(null)); } @Test void testSimpeCode() { String text = "This is sample text.{$ FOR i 1 10 1 $}This is {$= i $}" + "-th time this message is generated.{$END$}"; LexerSmart lexer = new LexerSmart(text); assertEquals(lexer.nextToken().getType(), TokenSmartType.TEXT); assertEquals(lexer.getToken().getValue(), "This is sample text."); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_OPEN); assertEquals(lexer.getToken().getValue(), "{$"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_NAME); assertEquals(lexer.getToken().getValue(), "FOR"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_ELEMENT); assertEquals(lexer.getToken().getValue().toString().strip(), "i 1 10 1"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_CLOSE); assertEquals(lexer.getToken().getValue(), "$}"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TEXT); assertEquals(lexer.getToken().getValue(), "This is "); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_OPEN); assertEquals(lexer.getToken().getValue(), "{$"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_NAME); assertEquals(lexer.getToken().getValue(), "="); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_ELEMENT); assertEquals(lexer.getToken().getValue().toString().strip(), "i"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_CLOSE); assertEquals(lexer.getToken().getValue(), "$}"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TEXT); assertEquals(lexer.getToken().getValue(), "-th time this message is generated."); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_OPEN); assertEquals(lexer.getToken().getValue(), "{$"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_NAME); assertEquals(lexer.getToken().getValue(), "END"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_CLOSE); assertEquals(lexer.getToken().getValue(), "$}"); } @Test void testUnclosedLoop() { String text = "This is sample text.{$ FOR i 1 10 1 $}"; LexerSmart lexer = new LexerSmart(text); lexer.nextToken(); lexer.nextToken(); lexer.nextToken(); lexer.nextToken(); lexer.nextToken(); lexer.nextToken(); assertThrows(LexerSmartException.class, () -> lexer.nextToken()); } @Test void testCode() { String text = "This is text.{$ FOR \"i\" \"-101\" 10 1 $}" + "This is {$= i @sin \"h_el\\\\lo\" $}" + "-th time\\\\.\\{$END$}"; LexerSmart lexer = new LexerSmart(text); assertEquals(lexer.nextToken().getType(), TokenSmartType.TEXT); assertEquals(lexer.getToken().getValue(), "This is text."); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_OPEN); assertEquals(lexer.getToken().getValue(), "{$"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_NAME); assertEquals(lexer.getToken().getValue(), "FOR"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_ELEMENT); assertEquals(lexer.getToken().getValue().toString().strip(), "\"i\" \"-101\" 10 1"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_CLOSE); assertEquals(lexer.getToken().getValue(), "$}"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TEXT); assertEquals(lexer.getToken().getValue(), "This is "); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_OPEN); assertEquals(lexer.getToken().getValue(), "{$"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_NAME); assertEquals(lexer.getToken().getValue(), "="); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_ELEMENT); assertEquals(lexer.getToken().getValue().toString().strip(), "i @sin \"h_el\\\\lo\""); assertEquals(lexer.nextToken().getType(), TokenSmartType.TAG_CLOSE); assertEquals(lexer.getToken().getValue(), "$}"); assertEquals(lexer.nextToken().getType(), TokenSmartType.TEXT); assertEquals(lexer.getToken().getValue(), "-th time\\.{$END$}"); assertEquals(lexer.nextToken().getType(), TokenSmartType.EOF); assertEquals(lexer.getToken().getValue(), null); } @Test void testEmptyString() { LexerSmart lexer = new LexerSmart(""); lexer.nextToken(); assertThrows(LexerSmartException.class, () -> lexer.nextToken()); } }
3e01272d8474d29504943b07dace12bd17153db0
5,282
java
Java
src/test/java/com/github/zeroicq/executor/test/ExecutorTests.java
ZeroICQ/java-executor
a2ba3caef2d7e9631d6a20647d075290d887aa6f
[ "MIT" ]
null
null
null
src/test/java/com/github/zeroicq/executor/test/ExecutorTests.java
ZeroICQ/java-executor
a2ba3caef2d7e9631d6a20647d075290d887aa6f
[ "MIT" ]
null
null
null
src/test/java/com/github/zeroicq/executor/test/ExecutorTests.java
ZeroICQ/java-executor
a2ba3caef2d7e9631d6a20647d075290d887aa6f
[ "MIT" ]
null
null
null
33.220126
156
0.606588
478
package com.github.zeroicq.executor.test; import com.github.zeroicq.Executor; import org.junit.Assert; import org.junit.Test; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class ExecutorTests { @Test public void testExecuteCallable() throws ExecutionException, InterruptedException { Executor executor = new Executor(); Future<Integer> future = executor.execute(() -> TestHelper.sum(11, 10)); Assert.assertEquals(0, future.get().compareTo(21)); executor.stop(); } @Test public void testExecuteRunnable() throws ExecutionException, InterruptedException { Executor executor = new Executor(); State state = new State(); Assert.assertEquals(state.status, State.Status.NOT_PROCESSED); Future future = executor.execute(() -> TestHelper.processState(state)); future.get(); Assert.assertEquals(state.status, State.Status.PROCESSED); executor.stop(); } @Test public void testWhen() throws ExecutionException, InterruptedException { Executor executor = new Executor(); Future<Integer> longFuture = executor.execute(() -> TestHelper.longSum(20, 30)); Future fastFuture = executor.when(() -> TestHelper.sum(10, 20), longFuture); fastFuture.get(); Assert.assertTrue(longFuture.isDone()); executor.stop(); } @Test public void testWhenAll() throws ExecutionException, InterruptedException { Executor executor = new Executor(); ArrayList<Future<Integer>> longTasks = new ArrayList<>(); for (int i = 0; i < 10; i++) { longTasks.add(executor.execute(() -> TestHelper.longSum(1, 2))); } Future fastTask = executor.whenAll(() -> TestHelper.sum(10, 20), longTasks.toArray(new Future[0])); for (Future f : longTasks) { f.get(); Assert.assertFalse(fastTask.isDone()); } fastTask.get(); for (Future f : longTasks) { Assert.assertTrue(f.isDone()); } executor.stop(); } public static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() { public int compare(String str1, String str2) { int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2); return (res != 0) ? res : str1.compareTo(str2); } }; @Test public void testSort() throws ExecutionException, InterruptedException { Executor executor = new Executor(); Random rnd = new Random(1000); RandomString rndString = new RandomString(200, rnd, RandomString.alphanum); ArrayList<String> strings = new ArrayList<>(); for (int i = 0; i < 10; i++) { strings.add(rndString.nextString()); } ArrayList<String> stdSortStrings = new ArrayList<>(strings.size()); ArrayList<String> executorSortStrings = new ArrayList<>(strings.size()); for (String s : strings) { executorSortStrings.add(s); stdSortStrings.add(s); } stdSortStrings.sort(ALPHABETICAL_ORDER); mergeSort(executorSortStrings, executor, ALPHABETICAL_ORDER).get(); Assert.assertArrayEquals(stdSortStrings.toArray(new String[0]), executorSortStrings.toArray(new String[0])); executor.stop(); } public static Future mergeSort(ArrayList<String> arrayList, Executor executor, Comparator<String> cmp) throws ExecutionException, InterruptedException { if (arrayList.size() == 1) { CompletableFuture<Boolean> f = new CompletableFuture<>(); f.complete(true); return f; } ArrayList<String> left = new ArrayList<>(); ArrayList<String> right = new ArrayList<>(); int middle = arrayList.size() / 2; for (ListIterator<String> it = arrayList.listIterator(); it.nextIndex() != middle;) { left.add(it.next()); } for (ListIterator<String> it = arrayList.listIterator(middle); it.hasNext();) { right.add(it.next()); } Future leftFuture = mergeSort(left, executor, cmp); Future rightFuture = mergeSort(right, executor, cmp); return executor.whenAll(() -> merge(left, right, arrayList, cmp), leftFuture, rightFuture); } private static void merge(ArrayList<String> array1 , ArrayList<String> array2, ArrayList<String> destination, Comparator<String> cmp) { int curPos = 0; int pos1 = 0; int pos2 = 0; while (pos1 != array1.size() || pos2 != array2.size()) { if (pos1 == array1.size()) { destination.set(curPos, array2.get(pos2)); pos2++; } else if (pos2 == array2.size()) { destination.set(curPos, array1.get(pos1)); pos1++; } else if (cmp.compare(array1.get(pos1), array2.get(pos2)) >= 0 ) { destination.set(curPos, array2.get(pos2)); pos2++; } else { destination.set(curPos, array1.get(pos1)); pos1++; } curPos++; } } }
3e01275fbd86cba797ba688f5d79491d14401f37
6,723
java
Java
Future X/Method/Client/module/combat/Velocity.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
3
2022-02-28T17:34:51.000Z
2022-03-06T21:55:16.000Z
Future X/Method/Client/module/combat/Velocity.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
2
2022-02-25T20:10:14.000Z
2022-03-03T14:25:03.000Z
Future X/Method/Client/module/combat/Velocity.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
null
null
null
43.655844
166
0.64614
479
package Method.Client.module.combat; import Method.Client.Main; import Method.Client.managers.Setting; import Method.Client.module.Category; import Method.Client.module.Module; import Method.Client.utils.TimerUtils; import Method.Client.utils.Utils; import Method.Client.utils.system.Connection; import Method.Client.utils.system.Wrapper; import net.minecraft.network.Packet; import net.minecraft.network.play.client.CPacketPlayer; import net.minecraft.network.play.server.SPacketEntityVelocity; import net.minecraft.network.play.server.SPacketExplosion; import net.minecraftforge.fml.common.gameevent.TickEvent; public class Velocity extends Module { Setting mode = Main.setmgr.add(new Setting("Mode", this, "Simple", new String[] { "Simple", "AAC", "Fast", "YPort", "AAC4Flag", "Pull", "Airmove", "HurtPacket" })); Setting XMult = Main.setmgr.add(new Setting("XMultipl", this, 0.0D, 0.0D, 10.0D, false, this.mode, "Simple", 1)); Setting YMult = Main.setmgr.add(new Setting("YMultipl", this, 0.0D, 0.0D, 10.0D, false, this.mode, "Simple", 2)); Setting ZMult = Main.setmgr.add(new Setting("ZMultipl", this, 0.0D, 0.0D, 10.0D, false, this.mode, "Simple", 3)); Setting onPacket = Main.setmgr.add(new Setting("Only Packet", this, true, this.mode, "Simple", 4)); Setting CancelPacket = Main.setmgr.add(new Setting("CancelPacket", this, true, this.mode, "Simple", 5)); Setting Super = Main.setmgr.add(new Setting("Super", this, true, this.mode, "Pull", 1)); Setting Pushspeed = Main.setmgr.add(new Setting("Pushspeed", this, 0.25D, 1.0E-4D, 0.4D, false, this.mode, "Airmove", 2)); Setting Pushstart = Main.setmgr.add(new Setting("Pushstart", this, 8.0D, 2.0D, 9.0D, false, this.mode, "Airmove", 3)); private double motionX; private double motionZ; private final TimerUtils timer = new TimerUtils(); public Velocity() { super("Velocity", 0, Category.COMBAT, "Velocity"); } public void onClientTick(TickEvent.ClientTickEvent event) { if (this.mode.getValString().equalsIgnoreCase("AAC")) { if (mc.player.hurtTime > 0 && mc.player.hurtTime <= 7) { mc.player.motionX *= 0.5D; mc.player.motionZ *= 0.5D; } if (mc.player.hurtTime > 0 && mc.player.hurtTime < 6) { mc.player.motionX = 0.0D; mc.player.motionZ = 0.0D; } } if (this.mode.getValString().equalsIgnoreCase("Fast") && mc.player.hurtTime < 9 && !mc.player.onGround) { double yaw = mc.player.rotationYawHead; yaw = Math.toRadians(yaw); double dX = -Math.sin(yaw) * 0.08D; double dZ = Math.cos(yaw) * 0.08D; if (mc.player.getHealth() >= 6.0F) { mc.player.motionX = dX; mc.player.motionZ = dZ; } } if (this.mode.getValString().equalsIgnoreCase("Simple") && !this.onPacket.getValBoolean() && mc.player.hurtTime > 0 && mc.player.fallDistance < 3.0F && this.timer.isDelay(100L)) { if (Utils.isMovinginput()) { mc.player.motionX *= this.XMult.getValDouble(); mc.player.motionZ *= this.ZMult.getValDouble(); } else { mc.player.motionX *= this.XMult.getValDouble() + 0.2D; mc.player.motionZ *= this.ZMult.getValDouble() + 0.2D; } mc.player.motionY -= this.YMult.getValDouble(); mc.player.motionY += this.YMult.getValDouble(); this.timer.setLastMS(); } if (this.mode.getValString().equalsIgnoreCase("AAC4Flag") && (mc.player.hurtTime == 3 || mc.player.hurtTime == 4)) { double[] directionSpeedVanilla = Utils.directionSpeed(0.05D); mc.player.motionX = directionSpeedVanilla[0]; mc.player.motionZ = directionSpeedVanilla[1]; } if (this.mode.getValString().equalsIgnoreCase("Pull")) { if (mc.player.hurtTime == 9) { this.motionX = mc.player.motionX; this.motionZ = mc.player.motionZ; } if (this.Super.getValBoolean()) { if (mc.player.hurtTime == 8) { mc.player.motionX = -this.motionX * 0.45D; mc.player.motionZ = -this.motionZ * 0.45D; } } else if (mc.player.hurtTime == 4) { mc.player.motionX = -this.motionX * 0.6D; mc.player.motionZ = -this.motionZ * 0.6D; } } if (this.mode.getValString().equalsIgnoreCase("Airmove")) if (mc.player.hurtTime == 9) { this.motionX = mc.player.motionX; this.motionZ = mc.player.motionZ; } else if (mc.player.hurtTime == this.Pushstart.getValDouble() - 1.0D) { mc.player.motionX *= -this.Pushspeed.getValDouble(); mc.player.motionZ *= -this.Pushspeed.getValDouble(); } if (this.mode.getValString().equalsIgnoreCase("HurtPacket") && mc.player.hurtResistantTime > 18) Wrapper.INSTANCE.sendPacket((Packet)new CPacketPlayer.Position(mc.player.posX, mc.player.posY - 12.0D, mc.player.posZ, false)); super.onClientTick(event); } public boolean onPacket(Object packet, Connection.Side side) { if (this.mode.getValString().equalsIgnoreCase("Simple") && this.onPacket.getValBoolean()) { if (this.CancelPacket.getValBoolean()) { if (packet instanceof SPacketEntityVelocity) { SPacketEntityVelocity packet2 = (SPacketEntityVelocity)packet; return (packet2.getEntityID() != mc.player.getEntityId()); } if (packet instanceof SPacketExplosion && this.YMult.getValDouble() == 0.0D && this.XMult.getValDouble() == 0.0D && this.ZMult.getValDouble() == 0.0D) return false; return true; } if (this.timer.isDelay(100L)) { if (packet instanceof SPacketEntityVelocity) { SPacketEntityVelocity packet2 = (SPacketEntityVelocity)packet; packet2.motionY = (int)(packet2.motionY * this.YMult.getValDouble()); packet2.motionX = (int)(packet2.motionX * this.XMult.getValDouble()); packet2.motionZ = (int)(packet2.motionZ * this.ZMult.getValDouble()); } if (packet instanceof SPacketExplosion) { SPacketExplosion packet2 = (SPacketExplosion)packet; packet2.motionY = (float)(packet2.motionY * this.YMult.getValDouble()); packet2.motionX = (float)(packet2.motionX * this.XMult.getValDouble()); packet2.motionZ = (float)(packet2.motionZ * this.ZMult.getValDouble()); } this.timer.setLastMS(); } } if (this.mode.getValString().equalsIgnoreCase("YPort") && mc.player.hurtTime >= 8) { mc.player.setPosition(mc.player.lastTickPosX, mc.player.lastTickPosY + 2.0D, mc.player.lastTickPosZ); mc.player.motionY -= 0.3D; mc.player.motionX *= 0.8D; mc.player.motionZ *= 0.8D; } return true; } }
3e0127b4d03dacc5e91f8c8880567513b4e8394f
3,651
java
Java
HomeWork.Java.Final/src/io/gihub/c0de4un/prflb/salarymail/mail/BaseMailService.java
c0de4un/prflb_java_homework
ffb2143afbb8f34171a4a37f3eda4c3ffcc30bc0
[ "CC0-1.0" ]
1
2020-02-15T16:24:50.000Z
2020-02-15T16:24:50.000Z
HomeWork.Java.Final/src/io/gihub/c0de4un/prflb/salarymail/mail/BaseMailService.java
c0de4un/prflb_java_homework
ffb2143afbb8f34171a4a37f3eda4c3ffcc30bc0
[ "CC0-1.0" ]
null
null
null
HomeWork.Java.Final/src/io/gihub/c0de4un/prflb/salarymail/mail/BaseMailService.java
c0de4un/prflb_java_homework
ffb2143afbb8f34171a4a37f3eda4c3ffcc30bc0
[ "CC0-1.0" ]
null
null
null
30.940678
108
0.486168
480
/** * 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 COPYRIGHT HOLDERS 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 io.gihub.c0de4un.prflb.salarymail.mail; //----------------------------------------------------------- //=========================================================== // IMPORTS //=========================================================== import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.ArrayList; import java.util.HashMap; //=========================================================== // TYPES //=========================================================== /** * BaseMailService - MailService base. * <br/> * \^_^/ * <br/> * @version 0.1 * @since 20.02.2020 * @author Denis Z. ([email protected]) **/ public abstract class BaseMailService<T> implements IMailService<T>, Consumer<IMailMessage> { //----------------------------------------------------------- //=========================================================== // FIELDS //=========================================================== /** Messages content grouped by Sender. **/ protected Map<String, List<T>> mContents; //=========================================================== // CONSTRUCTOR //=========================================================== /** * BaseMailService default constructor. * * @thread_safety - not thread-safe. * @throws - can throw out-of-memory. **/ protected BaseMailService() { mContents = new HashMap<String, List<T>>( 4 ); } //=========================================================== // GETTERS & SETTERS //=========================================================== @Override public Map<String, List<T>> getMailBox() { return mContents; } //=========================================================== // INTERFACES //=========================================================== @Override public void accept( IMailMessage pMessage ) { if ( pMessage == null ) return; // Should NullPtrException being thrown ? // Sender. final String sender_ = pMessage.getFrom(); // Search messages list. List<T> messages_ = mContents.get( sender_ ); // Allocate if ( messages_ == null ) { messages_ = new ArrayList<T>( 2 ); // Array list to support manual sorting, add-order sotring as default. mContents.put(sender_, messages_); } // Get Message Content. T content_ = pMessage.<T>getContentAs( ); if ( content_ == null ) throw new ClassCastException( "BaseMailService.accept: uncompatable types !" ); // Add Message Content. messages_.add( content_ ); // Very not thread-safe. Copying would me more applicable. } //=========================================================== // METHODS //=========================================================== //----------------------------------------------------------- } /// BaseMailService //-----------------------------------------------------------
3e01285ccc4b4964cb0547f5ad80c42e6deb1d75
347
java
Java
src/main/java/com/jassuncao/docmap/domain/CrudRepository.java
jonassuncao/tied
7c66510e9101af0758149b5dc8c0af91d1fad0e2
[ "MIT" ]
null
null
null
src/main/java/com/jassuncao/docmap/domain/CrudRepository.java
jonassuncao/tied
7c66510e9101af0758149b5dc8c0af91d1fad0e2
[ "MIT" ]
null
null
null
src/main/java/com/jassuncao/docmap/domain/CrudRepository.java
jonassuncao/tied
7c66510e9101af0758149b5dc8c0af91d1fad0e2
[ "MIT" ]
null
null
null
20.529412
67
0.787966
481
package com.jassuncao.docmap.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.NoRepositoryBean; import java.util.UUID; /** * @author jonathas.assuncao - [email protected] * 09/09/2021 */ @NoRepositoryBean public interface CrudRepository<T> extends JpaRepository<T, UUID> { }
3e01286771ff08cf0369ecdae4ef8007b273b6f9
1,118
java
Java
Storage.java
jmcquaid87/storage
7feaf05ef8249c490aebe74b4c92348726b57ac8
[ "MIT" ]
null
null
null
Storage.java
jmcquaid87/storage
7feaf05ef8249c490aebe74b4c92348726b57ac8
[ "MIT" ]
null
null
null
Storage.java
jmcquaid87/storage
7feaf05ef8249c490aebe74b4c92348726b57ac8
[ "MIT" ]
null
null
null
22.36
79
0.448122
482
/* * 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 csc241hw01; /** * * @author justinmcquaid */ import java.util.ArrayList; public class Storage { ArrayList<String> names = new ArrayList<String>(); public boolean addItem(String s) { if (s != null) { names.add(s); return true; } else { return false; } } public String[] getItems() { String array[]; array = names.toArray(new String[names.size()]); return array; } public boolean isFull() { return false; } public boolean removeItem(String s) { if (s != null) { names.remove(s); return true; } else { return false; } } }
3e01287a235f3f4f7cf0f769fa4ffbf8a469de70
1,984
java
Java
Data-Structure-and-Algorithms/Java/Greedy-DP/Dijkstra.java
rghvgrv/Simple-Programs
1e0b3995fd6826e77d0d81f23f5547bb0ebdadcb
[ "MIT" ]
71
2021-09-30T11:25:12.000Z
2021-10-03T11:33:22.000Z
Data-Structure-and-Algorithms/Java/Greedy-DP/Dijkstra.java
rghvgrv/Simple-Programs
1e0b3995fd6826e77d0d81f23f5547bb0ebdadcb
[ "MIT" ]
186
2021-09-30T12:25:16.000Z
2021-10-03T13:45:04.000Z
Data-Structure-and-Algorithms/Java/Greedy-DP/Dijkstra.java
rghvgrv/Simple-Programs
1e0b3995fd6826e77d0d81f23f5547bb0ebdadcb
[ "MIT" ]
385
2021-09-30T11:34:23.000Z
2021-10-03T13:41:00.000Z
24.195122
75
0.405242
483
import java.util.*; import java.lang.*; import java.io.*; class Dijkstra{ static final int V = 9; // utility function for the minumum distance value, int minDis(int dist[], Boolean sptset[]){ // initialize the min value int min = Integer.MAX_VALUE, min_index = -1; for(int i = 0; i<V; i++){ if(sptset[i]==false && dist[i]<=min){ min = dist[i]; min_index = i; } } return min_index; } void dijkstra(int graph[][], int src){ int dist[] = new int[V]; Boolean sptset[] = new Boolean[V]; for(int i=0;i<V;++i){ dist[i] = Integer.MAX_VALUE; sptset[i] = false; } // itself as zero dist[src] = 0; // edge is V-1 for(int i=0; i<V-1;i++){ int u = minDis(dist, sptset); sptset[u] =true; for(int v = 0; v<V;v++){ if(!sptset[v] && graph[u][v]!=0 && dist[u]!=Integer.MAX_VALUE && dist[u]+graph[u][v]<dist[v]){ dist[v] = dist[u]+graph[u][v]; } } } printSolution(dist); } void printSolution(int dist[]) { System.out.println("Vertex \t\t Distance from source"); for(int i=0;i<V;i++){ System.out.println(i+"\t\t "+dist[i]); } } public static void main(String[] args){ int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; Dijkstra t = new Dijkstra(); t.dijkstra(graph,0); } }
3e0129d9131273a1917120beca15f2122e292ffe
4,856
java
Java
web/src/main/java/org/springframework/security/web/header/writers/ContentSecurityPolicyHeaderWriter.java
lenxin/spring-security
9cc4bd14b66afcb0142c9a0df35738342a5eeaa4
[ "Apache-2.0" ]
null
null
null
web/src/main/java/org/springframework/security/web/header/writers/ContentSecurityPolicyHeaderWriter.java
lenxin/spring-security
9cc4bd14b66afcb0142c9a0df35738342a5eeaa4
[ "Apache-2.0" ]
null
null
null
web/src/main/java/org/springframework/security/web/header/writers/ContentSecurityPolicyHeaderWriter.java
lenxin/spring-security
9cc4bd14b66afcb0142c9a0df35738342a5eeaa4
[ "Apache-2.0" ]
null
null
null
35.445255
113
0.750206
484
package org.springframework.security.web.header.writers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.util.Assert; /** * <p> * Provides support for <a href="https://www.w3.org/TR/CSP2/">Content Security Policy * (CSP) Level 2</a>. * </p> * * <p> * CSP provides a mechanism for web applications to mitigate content injection * vulnerabilities, such as cross-site scripting (XSS). CSP is a declarative policy that * allows web application authors to inform the client (user-agent) about the sources from * which the application expects to load resources. * </p> * * <p> * For example, a web application can declare that it only expects to load script from * specific, trusted sources. This declaration allows the client to detect and block * malicious scripts injected into the application by an attacker. * </p> * * <p> * A declaration of a security policy contains a set of security policy directives (for * example, script-src and object-src), each responsible for declaring the restrictions * for a particular resource type. The list of directives defined can be found at * <a href="https://www.w3.org/TR/CSP2/#directives">Directives</a>. * </p> * * <p> * Each directive has a name and value. For detailed syntax on writing security policies, * see <a href="https://www.w3.org/TR/CSP2/#syntax-and-algorithms">Syntax and * Algorithms</a>. * </p> * * <p> * This implementation of {@link HeaderWriter} writes one of the following headers: * </p> * <ul> * <li>Content-Security-Policy</li> * <li>Content-Security-Policy-Report-Only</li> * </ul> * * <p> * By default, the Content-Security-Policy header is included in the response. However, * calling {@link #setReportOnly(boolean)} with {@code true} will include the * Content-Security-Policy-Report-Only header in the response. <strong>NOTE:</strong> The * supplied security policy directive(s) will be used for whichever header is enabled * (included). * </p> * * <p> * <strong> CSP is not intended as a first line of defense against content injection * vulnerabilities. Instead, CSP is used to reduce the harm caused by content injection * attacks. As a first line of defense against content injection, web application authors * should validate their input and encode their output. </strong> * </p> * * @author Joe Grandja * @author Ankur Pathak * @since 4.1 */ public final class ContentSecurityPolicyHeaderWriter implements HeaderWriter { private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy"; private static final String CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER = "Content-Security-Policy-Report-Only"; private static final String DEFAULT_SRC_SELF_POLICY = "default-src 'self'"; private String policyDirectives; private boolean reportOnly; /** * Creates a new instance. Default value: default-src 'self' */ public ContentSecurityPolicyHeaderWriter() { setPolicyDirectives(DEFAULT_SRC_SELF_POLICY); this.reportOnly = false; } /** * Creates a new instance * @param policyDirectives maps to {@link #setPolicyDirectives(String)} * @throws IllegalArgumentException if policyDirectives is null or empty */ public ContentSecurityPolicyHeaderWriter(String policyDirectives) { setPolicyDirectives(policyDirectives); this.reportOnly = false; } /** * @see org.springframework.security.web.header.HeaderWriter#writeHeaders(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { String headerName = (!this.reportOnly) ? CONTENT_SECURITY_POLICY_HEADER : CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER; if (!response.containsHeader(headerName)) { response.setHeader(headerName, this.policyDirectives); } } /** * Sets the security policy directive(s) to be used in the response header. * @param policyDirectives the security policy directive(s) * @throws IllegalArgumentException if policyDirectives is null or empty */ public void setPolicyDirectives(String policyDirectives) { Assert.hasLength(policyDirectives, "policyDirectives cannot be null or empty"); this.policyDirectives = policyDirectives; } /** * If true, includes the Content-Security-Policy-Report-Only header in the response, * otherwise, defaults to the Content-Security-Policy header. * @param reportOnly set to true for reporting policy violations only */ public void setReportOnly(boolean reportOnly) { this.reportOnly = reportOnly; } @Override public String toString() { return getClass().getName() + " [policyDirectives=" + this.policyDirectives + "; reportOnly=" + this.reportOnly + "]"; } }
3e012a1a34011c6dc0b8e58a8408418ee5091007
639
java
Java
inventory-service/src/main/java/demo/domain/Warehouse.java
davimonteiro/reference-msa-application
6560a34de85ffcdeecc3a6c447ebac58f05a9e3f
[ "Apache-2.0" ]
6
2018-05-29T14:37:58.000Z
2020-02-02T15:03:47.000Z
inventory-service/src/main/java/demo/domain/Warehouse.java
davimonteiro/reference-msa-application
6560a34de85ffcdeecc3a6c447ebac58f05a9e3f
[ "Apache-2.0" ]
null
null
null
inventory-service/src/main/java/demo/domain/Warehouse.java
davimonteiro/reference-msa-application
6560a34de85ffcdeecc3a6c447ebac58f05a9e3f
[ "Apache-2.0" ]
null
null
null
16.815789
51
0.70579
485
package demo.domain; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; /** * A simple domain class for the {@link Warehouse}. * * @author Kenny Bastani * @author Josh Long * @author Davi Monteiro */ @Entity @Getter @Setter @ToString public class Warehouse { @Id @GeneratedValue private Long id; private String name; @OneToOne private Address address; public Warehouse() { } public Warehouse(String name) { this.name = name; } }
3e012a7c62256d01693abf0694c3e11fe5c40fc1
310
java
Java
pre-admin/src/main/java/com/xd/pre/modules/sys/mapper/SysRoleDeptMapper.java
mr-lee-1994/pre
fe51e026be49ad5d7517cfb963426bb16ec9b913
[ "Apache-2.0" ]
null
null
null
pre-admin/src/main/java/com/xd/pre/modules/sys/mapper/SysRoleDeptMapper.java
mr-lee-1994/pre
fe51e026be49ad5d7517cfb963426bb16ec9b913
[ "Apache-2.0" ]
null
null
null
pre-admin/src/main/java/com/xd/pre/modules/sys/mapper/SysRoleDeptMapper.java
mr-lee-1994/pre
fe51e026be49ad5d7517cfb963426bb16ec9b913
[ "Apache-2.0" ]
null
null
null
18.235294
68
0.732258
486
package com.xd.pre.modules.sys.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xd.pre.modules.sys.domain.SysRoleDept; /** * <p> * 角色与部门对应关系 Mapper 接口 * </p> * * @author lihaodong * @since 2019-04-21 */ public interface SysRoleDeptMapper extends BaseMapper<SysRoleDept> { }
3e012a9e942cad82f411a3dc26bf851f9f3c2c5f
22,250
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/leageAuto.java
DeltaRobotics-FTC/DR_20-21SDK6.1
2857db53dd107743c636d1ec53ab26759830c7b2
[ "MIT" ]
1
2020-10-23T15:35:40.000Z
2020-10-23T15:35:40.000Z
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/leageAuto.java
DeltaRobotics-FTC/DR_20-21SDK6.0
2857db53dd107743c636d1ec53ab26759830c7b2
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/leageAuto.java
DeltaRobotics-FTC/DR_20-21SDK6.0
2857db53dd107743c636d1ec53ab26759830c7b2
[ "MIT" ]
null
null
null
34.448171
395
0.594831
487
package org.firstinspires.ftc.teamcode; //imports import com.acmerobotics.dashboard.FtcDashboard; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.geometry.Vector2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import org.firstinspires.ftc.robotcore.external.ClassFactory; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import org.firstinspires.ftc.robotcore.external.tfod.Recognition; import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector; import org.firstinspires.ftc.teamcode.drive.DriveConstants; import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive; import java.util.Arrays; import java.util.List; @Config @Autonomous(name = "leageAuto") public class leageAuto extends LinearOpMode { //declare variables //Viewforia / TFOD variables private static final String TFOD_MODEL_ASSET = "UltimateGoal.tflite"; private static final String LABEL_FIRST_ELEMENT = "Quad"; private static final String LABEL_SECOND_ELEMENT = "Single"; private static final String VUFORIA_KEY = "949d1u22cbffbrarjh182eig55721odj"; private VuforiaLocalizer vuforia; private TFObjectDetector tfod; public String view = ""; //wobble goal variables public static int wobbleUp = 425; public static int wobbleDown = 825; public static int wobbleAway = 0; public static double wobbleArmPower = 0.7; public static double wobbleOpen = 1; public static double wobbleClosed = 0; public static int wobbleServoWait = 250; //shooter public static double flywheelHighSpeed = 1700; public static double flywheelPowerSpeed = 1550; public static double servoShoot = -.1; public static double servoRetract = .25; public static int shotTiming = 750; //RR pose //Pose2d _ = new Pose2d(_, _, Math.toRadians(_)); //Vector2d _ = new Vector2d(_, _); public static Pose2d startPose = new Pose2d(-63, 57, Math.toRadians(180)); @Override public void runOpMode() throws InterruptedException { //classes //dashboard init //FtcDashboard dashboard = FtcDashboard.getInstance(); //telemetry = dashboard.getTelemetry(); //robot hardware map init RobotHardware robot = new RobotHardware(hardwareMap); //roadrunner drive constants init SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); telemetry.addData("classes inited", ""); telemetry.update(); //cammera //veiwforia VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(); parameters.vuforiaLicenseKey = VUFORIA_KEY; parameters.cameraName = hardwareMap.get(WebcamName.class, "webcam"); vuforia = ClassFactory.getInstance().createVuforia(parameters); //TFOD int tfodMonitorViewId = hardwareMap.appContext.getResources().getIdentifier( "tfodMonitorViewId", "id", hardwareMap.appContext.getPackageName()); TFObjectDetector.Parameters tfodParameters = new TFObjectDetector.Parameters(tfodMonitorViewId); tfodParameters.minResultConfidence = 0.6f; //change to change mimimum confidence tfod = ClassFactory.getInstance().createTFObjectDetector(tfodParameters, vuforia); tfod.loadModelFromAsset(TFOD_MODEL_ASSET, LABEL_FIRST_ELEMENT, LABEL_SECOND_ELEMENT); if (tfod != null) { tfod.activate(); tfod.setZoom(3, 1.78); } telemetry.addData("classes inited", ""); telemetry.addData("cammera inited", ""); telemetry.update(); //other init stuff robot.wobble.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); robot.wobble.setTargetPosition(wobbleAway); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.servo2.setPosition(wobbleClosed); robot.servo.setPosition(servoRetract); telemetry.addData("classes inited", ""); telemetry.addData("cammera inited", ""); telemetry.addData("building trajectories", ""); telemetry.update(); //with roadrunner you basicly build auto in init then run the built auto //set start position drive.setPoseEstimate(startPose); //A trajectories //drive to wobble spot A Trajectory shotPosA = drive.trajectoryBuilder(startPose, true) .splineToConstantHeading(new Vector2d(-10, 48), Math.toRadians(0)) .build(); //drive to power shots Trajectory WobbleA = drive.trajectoryBuilder(shotPosA.end(), true) .splineToConstantHeading(new Vector2d(10, 40), Math.toRadians(0)) .build(); Trajectory Wobble2GrabA = drive.trajectoryBuilder(WobbleA.end()) .lineTo(new Vector2d(-55, 5)) .build(); Trajectory Wobble2strafeA = drive.trajectoryBuilder(Wobble2GrabA.end()) .lineTo(new Vector2d(-56, 23)) .build(); Trajectory Wobble2PlaceA = drive.trajectoryBuilder(Wobble2strafeA.end(), true) .splineToConstantHeading(new Vector2d(6, 40), Math.toRadians(20)) .build(); //park Trajectory ParkA = drive.trajectoryBuilder(Wobble2PlaceA.end()) .lineTo(new Vector2d(12, 35)) .build(); telemetry.addData("classes inited", ""); telemetry.addData("cammera inited", ""); telemetry.addData("building trajectories", ""); telemetry.addData("A built", ""); telemetry.update(); //B trajectories Trajectory shotPosB = drive.trajectoryBuilder(startPose, true) .splineToConstantHeading(new Vector2d(-9, 48), Math.toRadians(0)) .build(); //drive to power shots Trajectory WobbleB = drive.trajectoryBuilder(shotPosB.end(), true) .splineToConstantHeading(new Vector2d(30, 10), Math.toRadians(0)) .build(); Trajectory CollectionB = drive.trajectoryBuilder(WobbleB.end()) .lineTo(new Vector2d(-30, 40)) .build(); Trajectory Wobble2GrabB = drive.trajectoryBuilder(CollectionB.end().plus(new Pose2d(0, 0, Math.toRadians(10)))) .lineTo(new Vector2d(-49, 5)) .build(); Trajectory Wobble2strafeB = drive.trajectoryBuilder(Wobble2GrabB.end()) .lineTo(new Vector2d(-53, 21.5)) .build(); Trajectory Wobble2PlaceB = drive.trajectoryBuilder(Wobble2strafeB.end(), true) .splineToConstantHeading(new Vector2d(30, 10), Math.toRadians(20)) .build(); //park Trajectory ParkB = drive.trajectoryBuilder(Wobble2PlaceB.end()) .lineTo(new Vector2d(12, 25)) .build(); telemetry.addData("classes inited", ""); telemetry.addData("cammera inited", ""); telemetry.addData("building trajectories", ""); telemetry.addData("A built", ""); telemetry.addData("B built", ""); telemetry.update(); //C trajectories //drive to wobble spot trajectory Trajectory shotPosC = drive.trajectoryBuilder(startPose, true) .splineToConstantHeading(new Vector2d(-8, 48), Math.toRadians(0)) .build(); //drive to power shots Trajectory WobbleC = drive.trajectoryBuilder(shotPosC.end(), true) .splineToConstantHeading(new Vector2d(50, 40), Math.toRadians(0)) .build(); Trajectory CollectionC = drive.trajectoryBuilder(WobbleC.end()) .splineToConstantHeading(new Vector2d(0, 40), Math.toRadians(0)) .build(); Trajectory CollectC = drive.trajectoryBuilder(CollectionC.end()) .lineTo( new Vector2d(-30, 40), new MinVelocityConstraint( Arrays.asList( new AngularVelocityConstraint(DriveConstants.MAX_ANG_VEL), new MecanumVelocityConstraint(10, DriveConstants.TRACK_WIDTH) ) ), new ProfileAccelerationConstraint(DriveConstants.MAX_ACCEL) ) .build(); Trajectory shotPos2C = drive.trajectoryBuilder(CollectC.end(), true) .splineToConstantHeading(new Vector2d(-10, 48), Math.toRadians(0)) .build(); //park Trajectory ParkC = drive.trajectoryBuilder(shotPos2C.end()) .lineTo(new Vector2d(12, 35)) .build(); telemetry.addData("classes inited", ""); telemetry.addData("cammera inited", ""); telemetry.addData("building trajectories", ""); telemetry.addData("A built", ""); telemetry.addData("B built", ""); telemetry.addData("C built", ""); telemetry.update(); telemetry.addData(">", "Press Play to start op mode"); telemetry.addData("classes inited", ""); telemetry.addData("cammera inited", ""); telemetry.addData("building trajectories", ""); telemetry.addData("A built", ""); telemetry.addData("B built", ""); telemetry.addData("C built", ""); telemetry.update(); waitForStart(); //auto //get TFOD detection if (tfod != null) { // getUpdatedRecognitions() will return null if no new information is available since // the last time that call was made. List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions(); if (updatedRecognitions != null) { telemetry.addData("# Object Detected", updatedRecognitions.size()); // step through the list of recognitions and display boundary info. int i = 0; for (Recognition recognition : updatedRecognitions) { telemetry.addData(String.format("label (%d)", i), recognition.getLabel()); telemetry.addData(String.format(" left,top (%d)", i), "%.03f , %.03f", recognition.getLeft(), recognition.getTop()); telemetry.addData(String.format(" right,bottom (%d)", i), "%.03f , %.03f", recognition.getRight(), recognition.getBottom()); view = recognition.getLabel(); } telemetry.update(); if (tfod != null) { tfod.shutdown(); } } } // // switch statement for 0,1,4 rings // switch (view) { case LABEL_FIRST_ELEMENT: //drive to C robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } drive.followTrajectory(shotPosC); ((DcMotorEx) robot.flywheel).setVelocity(flywheelHighSpeed); sleep(shotTiming*2); robot.servo.setPosition(servoShoot); sleep(shotTiming); robot.servo.setPosition(servoRetract); sleep(shotTiming); robot.servo.setPosition(servoShoot); sleep(shotTiming); robot.servo.setPosition(servoRetract); sleep(shotTiming); robot.servo.setPosition(servoShoot); sleep(shotTiming); robot.servo.setPosition(servoRetract); ((DcMotorEx) robot.flywheel).setVelocity(0); drive.followTrajectory(WobbleC); robot.wobble.setTargetPosition(wobbleDown); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } robot.servo2.setPosition(wobbleOpen); sleep(wobbleServoWait); sleep(1000); robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } robot.intake1.setPower(-1); robot.intake2.setPower(1); drive.followTrajectory(CollectionC); drive.followTrajectory(CollectC); sleep(350); ((DcMotorEx) robot.flywheel).setVelocity(flywheelHighSpeed); drive.followTrajectory(shotPos2C); sleep(shotTiming*2); robot.servo.setPosition(servoShoot); sleep(shotTiming); robot.servo.setPosition(servoRetract); sleep(shotTiming); robot.servo.setPosition(servoShoot); sleep(shotTiming); robot.servo.setPosition(servoRetract); sleep(shotTiming); robot.servo.setPosition(servoShoot); sleep(shotTiming); robot.servo.setPosition(servoRetract); ((DcMotorEx) robot.flywheel).setVelocity(0); drive.followTrajectory(ParkC); robot.intake1.setPower(-1); robot.intake2.setPower(1); break; case LABEL_SECOND_ELEMENT: //drive to B robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } drive.followTrajectory(shotPosB); ((DcMotorEx) robot.flywheel).setVelocity(flywheelHighSpeed); sleep(shotTiming*2); robot.servo.setPosition(servoShoot); sleep(500); robot.servo.setPosition(servoRetract); sleep(500); robot.servo.setPosition(servoShoot); sleep(500); robot.servo.setPosition(servoRetract); sleep(500); robot.servo.setPosition(servoShoot); sleep(500); robot.servo.setPosition(servoRetract); ((DcMotorEx) robot.flywheel).setVelocity(0); drive.followTrajectory(WobbleB); robot.wobble.setTargetPosition(wobbleDown); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } robot.servo2.setPosition(wobbleOpen); sleep(wobbleServoWait); sleep(250); robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } robot.intake1.setPower(-1); robot.intake2.setPower(1); drive.followTrajectory(CollectionB); ((DcMotorEx) robot.flywheel).setVelocity(flywheelHighSpeed); drive.turn(Math.toRadians(10)); sleep(shotTiming*2); robot.servo.setPosition(servoShoot); sleep(500); robot.servo.setPosition(servoRetract); ((DcMotorEx) robot.flywheel).setVelocity(0); robot.intake1.setPower(-1); robot.intake2.setPower(1); robot.wobble.setTargetPosition(wobbleDown); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); drive.followTrajectory(Wobble2GrabB); drive.followTrajectory(Wobble2strafeB); robot.servo2.setPosition(wobbleClosed); sleep(wobbleServoWait); robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); drive.followTrajectory(Wobble2PlaceB); robot.wobble.setTargetPosition(wobbleDown); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } robot.servo2.setPosition(wobbleOpen); sleep(wobbleServoWait); robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); sleep(150); drive.followTrajectory(ParkB); break; default: //drive to A robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } drive.followTrajectory(shotPosA); ((DcMotorEx) robot.flywheel).setVelocity(flywheelHighSpeed); sleep(shotTiming*2); robot.servo.setPosition(servoShoot); sleep(shotTiming); robot.servo.setPosition(servoRetract); sleep(shotTiming); robot.servo.setPosition(servoShoot); sleep(shotTiming); robot.servo.setPosition(servoRetract); sleep(shotTiming); robot.servo.setPosition(servoShoot); sleep(shotTiming); robot.servo.setPosition(servoRetract); ((DcMotorEx) robot.flywheel).setVelocity(0); drive.followTrajectory(WobbleA); robot.wobble.setTargetPosition(wobbleDown); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } robot.servo2.setPosition(wobbleOpen); sleep(wobbleServoWait); robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); drive.followTrajectory(Wobble2GrabA); robot.wobble.setTargetPosition(wobbleDown); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); drive.followTrajectory(Wobble2strafeA); robot.servo2.setPosition(wobbleClosed); sleep(wobbleServoWait); robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } drive.followTrajectory(Wobble2PlaceA); robot.wobble.setTargetPosition(wobbleDown); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } robot.servo2.setPosition(wobbleOpen); sleep(wobbleServoWait); robot.wobble.setTargetPosition(wobbleUp); robot.wobble.setPower(wobbleArmPower); robot.wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); while (robot.wobble.isBusy()) { } sleep(1000); drive.followTrajectory(ParkA); } } } // auto list //~take pic: ~tensor flow, ~no variables //drive to floor goal: ~roadrunner, goal pose variable //drop wobble1: ~wobble arm, ~servo, ~up and down variables, ~open closed variables, ~time for servo variable //shoot power shots: ~roadrunner, first shot pose variable, strafe distance variable, PIDF (HWmap?) and ~flywheel variables, ~shoot and retract servo variables, ~how long between shots variable //grab wobble2: ~roadrunner, final pose variable, ~up and down variables, ~open closed variables, ~time for servo variable //deliver wobble2: ~roadrunner, wobble1 offset variable //shoot starter stack: ~roadrunner, pose varables plural, intake speed variable, drive speed variable, PIDF and ~flywheel variables, ~shoot and retract servo variables, ~how long between shots //park: ~roadrunner, pose variable //list remaining : RRPose variables, intake variables and intake
3e012bddbef372e78e3feb9886ec74fa369b1315
2,580
java
Java
modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheStat.java
liyuj/gridgain
9505c0cfd7235210993b2871b17f15acf7d3dcd4
[ "CC0-1.0" ]
218
2015-01-04T13:20:55.000Z
2022-03-28T05:28:55.000Z
modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheStat.java
liyuj/gridgain
9505c0cfd7235210993b2871b17f15acf7d3dcd4
[ "CC0-1.0" ]
175
2015-02-04T23:16:56.000Z
2022-03-28T18:34:24.000Z
modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheStat.java
liyuj/gridgain
9505c0cfd7235210993b2871b17f15acf7d3dcd4
[ "CC0-1.0" ]
93
2015-01-06T20:54:23.000Z
2022-03-31T08:09:00.000Z
29.655172
102
0.68062
488
/* * Copyright 2020 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.processors.query.schema; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.ignite.internal.processors.query.QueryTypeDescriptorImpl; import org.apache.ignite.internal.util.typedef.internal.A; /** * Class for accumulation of record types and number of indexed records in index tree. */ public class SchemaIndexCacheStat { /** Indexed types. */ private final Map<String, QueryTypeDescriptorImpl> types = new HashMap<>(); /** Number of indexed keys. */ private int scanned; /** * Adds statistics from {@code stat} to the current statistics. * * @param stat Statistics. */ public void accumulate(SchemaIndexCacheStat stat) { scanned += stat.scanned; types.putAll(stat.types); } /** * Adds type to indexed types. * * @param type Type. */ public void addType(QueryTypeDescriptorImpl type) { types.put(type.name(), type); } /** * Adds to number of scanned keys given {@code scanned}. * * @param scanned Number of scanned keys during partition processing. Must be positive or zero. */ public void add(int scanned) { A.ensure(scanned >= 0, "scanned is negative. Value: " + scanned); this.scanned += scanned; } /** * @return Number of scanned keys. */ public int scannedKeys() { return scanned; } /** * @return Unmodifiable collection of processed type names. */ public Collection<String> typeNames() { return Collections.unmodifiableCollection(types.keySet()); } /** * @return Unmodifiable collection of processed types. */ public Collection<QueryTypeDescriptorImpl> types() { return Collections.unmodifiableCollection(types.values()); } }
3e012cad76a9b5c10916ddd140d35f077d02b751
1,807
java
Java
example/src/com/cyphercove/covetools/utils/ClickRingIllustrator.java
CypherCove/CoveTools
34e4c1bbac3e61d57adb416affa87ae33f71f038
[ "Apache-2.0" ]
10
2019-06-14T12:25:41.000Z
2020-11-24T18:39:27.000Z
example/src/com/cyphercove/covetools/utils/ClickRingIllustrator.java
CypherCove/CoveTools
34e4c1bbac3e61d57adb416affa87ae33f71f038
[ "Apache-2.0" ]
2
2019-09-03T02:36:12.000Z
2020-10-08T03:28:35.000Z
example/src/com/cyphercove/covetools/utils/ClickRingIllustrator.java
CypherCove/CoveTools
34e4c1bbac3e61d57adb416affa87ae33f71f038
[ "Apache-2.0" ]
1
2020-03-21T16:11:53.000Z
2020-03-21T16:11:53.000Z
31.155172
144
0.644162
489
package com.cyphercove.covetools.utils; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pools; public class ClickRingIllustrator implements Disposable { Texture texture; Array<Click> clicks = new Array<>(); float endSize; float appearTime = 0.15f; float fadeTime = 0.8f; private static class Click implements Pool.Poolable { public float x, y, age; public void reset () { age = 0; } } public ClickRingIllustrator (float endSize){ texture = new Texture(Gdx.files.internal("clickring.png"), true); texture.setFilter(Texture.TextureFilter.MipMapLinearLinear, Texture.TextureFilter.Linear); this.endSize = endSize; } public void render (float dt, Batch batch){ batch.begin(); for (Click click : clicks){ click.age += dt; float size = click.age < appearTime ? Interpolation.fastSlow.apply(0, endSize, click.age / appearTime) : endSize; float alpha = click.age < appearTime ? 1 : Interpolation.fade.apply(MathUtils.clamp(1 - (click.age - appearTime) / fadeTime, 0, 1)); batch.setColor(1, 1, 1, alpha); batch.draw(texture, click.x - size / 2, click.y - size / 2, size, size); } batch.end(); } public void addClick (float x, float y){ Click click = Pools.obtain(Click.class); click.x = x; click.y = y; clicks.add(click); } @Override public void dispose () { } }
3e012d2535c0e6b9dbe9dbaf7ed7ed7f4811b48d
20,223
java
Java
blueflood-http/src/test/java/com/rackspacecloud/blueflood/tracker/TrackerTest.java
JLLeitschuh/blueflood
4722a3449b1a7f8e88889ea8c340c6f24396b5b0
[ "Apache-2.0" ]
390
2015-01-08T00:48:27.000Z
2022-01-21T09:48:33.000Z
blueflood-http/src/test/java/com/rackspacecloud/blueflood/tracker/TrackerTest.java
JLLeitschuh/blueflood
4722a3449b1a7f8e88889ea8c340c6f24396b5b0
[ "Apache-2.0" ]
428
2015-01-07T18:12:56.000Z
2022-01-05T16:58:00.000Z
blueflood-http/src/test/java/com/rackspacecloud/blueflood/tracker/TrackerTest.java
JLLeitschuh/blueflood
4722a3449b1a7f8e88889ea8c340c6f24396b5b0
[ "Apache-2.0" ]
91
2015-01-03T02:40:20.000Z
2022-01-16T08:03:15.000Z
45.444944
184
0.66103
490
package com.rackspacecloud.blueflood.tracker; import com.rackspacecloud.blueflood.http.HttpRequestWithDecodedQueryParams; import com.rackspacecloud.blueflood.types.Locator; import com.rackspacecloud.blueflood.types.Metric; import com.rackspacecloud.blueflood.utils.TimeValue; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.HttpHeaders; import junit.framework.Assert; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.hamcrest.CoreMatchers.not; import static org.junit.matchers.JUnitMatchers.containsString; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import static org.powermock.api.mockito.PowerMockito.mock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; @RunWith(PowerMockRunner.class) @PrepareForTest({LoggerFactory.class}) @PowerMockIgnore( {"javax.management.*"}) public class TrackerTest { Tracker tracker = Tracker.getInstance(); String testTenant1 = "tenant1"; String testTenant2 = "tenant2"; String tenantId = "121212"; private static Logger loggerMock; private HttpRequestWithDecodedQueryParams httpRequestMock; private HttpMethod httpMethodMock; private FullHttpResponse httpResponseMock; private HttpResponseStatus httpResponseStatusMock; private Map<String, List<String>> queryParams; private List<Metric> delayedMetrics; private long collectionTime; @Captor ArgumentCaptor argCaptor; @BeforeClass public static void setupClass() { // mock logger PowerMockito.mockStatic(LoggerFactory.class); loggerMock = mock(Logger.class); when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock); } @Before public void setUp() { // reset static logger mock for every new test setup reset(loggerMock); // mock HttpRequest, method, queryParams, channelBuffer, responseStatus httpRequestMock = mock(HttpRequestWithDecodedQueryParams.class); httpMethodMock = mock(HttpMethod.class); queryParams = new HashMap<String, List<String>>(); // mock HttpResponse and HttpResponseStatus httpResponseMock = mock(FullHttpResponse.class); httpResponseStatusMock = mock(HttpResponseStatus.class); // mock headers HttpHeaders headers = mock(HttpHeaders.class); Set<String> headerNames = new HashSet<String>(); headerNames.add("X-Auth-Token"); when(httpRequestMock.headers()).thenReturn(headers); when(headers.names()).thenReturn(headerNames); when(headers.get("X-Auth-Token")).thenReturn("AUTHTOKEN"); HttpHeaders responseHeaders = mock(HttpHeaders.class); when(httpResponseMock.headers()).thenReturn(responseHeaders); when(responseHeaders.names()).thenReturn(new HashSet<String>()); // setup delayed metrics Locator locator1 = Locator.createLocatorFromPathComponents(tenantId, "delayed", "metric1"); Locator locator2 = Locator.createLocatorFromPathComponents(tenantId, "delayed", "metric2"); collectionTime = 1451606400000L; // Jan 1, 2016 UTC TimeValue ttl = new TimeValue(3, TimeUnit.DAYS); Metric delayMetric1 = new Metric(locator1, 123, collectionTime, ttl, ""); Metric delayMetric2 = new Metric(locator2, 456, collectionTime, ttl, ""); delayedMetrics = new ArrayList<Metric>(); delayedMetrics.add(delayMetric1); delayedMetrics.add(delayMetric2); } @Test public void testRegister() { // register the tracker and verify tracker.register(); verify(loggerMock, times(1)).info("MBean registered as com.rackspacecloud.blueflood.tracker:type=Tracker"); } @Test public void testAddTenant() { tracker.addTenant(testTenant1); Set tenants = tracker.getTenants(); assertTrue( "tenant " + testTenant1 + " not added", tracker.isTracking( testTenant1 ) ); assertTrue( "tenants.size not 1", tenants.size() == 1 ); assertTrue( "tenants does not contain " + testTenant1, tenants.contains( testTenant1 ) ); } @Test public void testDoesNotAddTenantTwice() { tracker.addTenant(testTenant1); tracker.addTenant(testTenant1); Set tenants = tracker.getTenants(); assertTrue( "tenant " + testTenant1 + " not added", tracker.isTracking( testTenant1 ) ); assertTrue( "tenants.size not 1", tenants.size() == 1 ); } @Test public void testRemoveTenant() { tracker.addTenant(testTenant1); assertTrue( "tenant " + testTenant1 + " not added", tracker.isTracking( testTenant1 ) ); tracker.removeTenant(testTenant1); Set tenants = tracker.getTenants(); assertFalse( "tenant " + testTenant1 + " not removed", tracker.isTracking( testTenant1 ) ); assertEquals( "tenants.size not 0", tenants.size(), 0 ); assertFalse( "tenants contains " + testTenant1, tenants.contains( testTenant1 ) ); } @Test public void testAddAndRemoveMetricName() { String metric1 = "metricName"; String metric2 = "anotherMetricName"; tracker.addMetricName(metric1); assertTrue(metric1 + " not added", tracker.doesMessageContainMetricNames("Track.this." + metric1)); tracker.addMetricName(metric2); assertTrue(metric1 + " not being logged", tracker.doesMessageContainMetricNames("Track.this." + metric1)); assertTrue(metric2 + "not being logged", tracker.doesMessageContainMetricNames("Track.this." + metric2)); assertFalse("randomMetricNameNom should not be logged", tracker.doesMessageContainMetricNames("Track.this.randomMetricNameNom")); Set<String> metricNames = tracker.getMetricNames(); assertTrue("metricNames should contain " + metric1, metricNames.contains(metric1)); assertTrue("metricNames should contain " + metric2, metricNames.contains(metric2)); tracker.removeMetricName(metric1); assertFalse(metric1 + " should not be logged", tracker.doesMessageContainMetricNames("Track.this." + metric1)); metricNames = tracker.getMetricNames(); assertFalse("metricNames should not contain " + metric1, metricNames.contains(metric1)); assertTrue("metricNames should contain " + metric2, metricNames.contains(metric2)); } @Test public void testRemoveAllMetricNames() { tracker.addMetricName("metricName"); tracker.addMetricName("anotherMetricNom"); assertTrue("metricName not being logged",tracker.doesMessageContainMetricNames("Track.this.metricName")); assertTrue("anotherMetricNom not being logged",tracker.doesMessageContainMetricNames("Track.this.anotherMetricNom")); assertFalse("randomMetricNameNom should not be logged", tracker.doesMessageContainMetricNames("Track.this.randomMetricNameNom")); tracker.removeAllMetricNames(); assertTrue("Everything should be logged", tracker.doesMessageContainMetricNames("Track.this.metricName")); assertTrue("Everything should be logged", tracker.doesMessageContainMetricNames("Track.this.anotherMetricNom")); assertTrue("Everything should be logged", tracker.doesMessageContainMetricNames("Track.this.randomMetricNameNom")); } @Test public void testRemoveAllTenant() { tracker.addTenant(testTenant1); tracker.addTenant(testTenant2); assertTrue( "tenant " + testTenant1 + " not added", tracker.isTracking( testTenant1 ) ); assertTrue( "tenant " + testTenant2 + " not added", tracker.isTracking( testTenant2 ) ); tracker.removeAllTenants(); assertFalse( "tenant " + testTenant1 + " not removed", tracker.isTracking( testTenant1 ) ); assertFalse( "tenant " + testTenant2 + " not removed", tracker.isTracking( testTenant2 ) ); Set tenants = tracker.getTenants(); assertEquals( "tenants.size not 0", tenants.size(), 0 ); } @Test public void testFindTidFound() { assertEquals( tracker.findTid( "/v2.0/6000/views" ), "6000" ); } @Test public void testTrackTenantNoVersion() { assertEquals( tracker.findTid( "/6000/views" ), null ); } @Test public void testTrackTenantBadVersion() { assertEquals( tracker.findTid( "blah/6000/views" ), null ); } @Test public void testTrackTenantTrailingSlash() { assertEquals( tracker.findTid( "/v2.0/6000/views/" ), "6000" ); } @Test public void testSetIsTrackingDelayedMetrics() { tracker.resetIsTrackingDelayedMetrics(); tracker.setIsTrackingDelayedMetrics(); Assert.assertTrue("isTrackingDelayedMetrics should be true from setIsTrackingDelayedMetrics", tracker.getIsTrackingDelayedMetrics()); } @Test public void testResetIsTrackingDelayedMetricss() { tracker.setIsTrackingDelayedMetrics(); tracker.resetIsTrackingDelayedMetrics(); Assert.assertFalse("isTrackingDelayedMetrics should be false from resetIsTrackingDelayedMetrics", tracker.getIsTrackingDelayedMetrics()); } @Test public void testTrackTenant() throws Exception { // setup mock returns for ingest POST when(httpRequestMock.getUri()).thenReturn("/v2.0/" + tenantId + "/ingest"); when(httpMethodMock.toString()).thenReturn("POST"); when(httpRequestMock.getMethod()).thenReturn(httpMethodMock); List<String> paramValues = new ArrayList<String>(); paramValues.add("value1"); paramValues.add("value2"); queryParams.put("param1", paramValues); when((httpRequestMock).getQueryParams()).thenReturn(queryParams); String payload = "[\n" + " {\n" + " \"collectionTime\": 1376509892612,\n" + " \"ttlInSeconds\": 172800,\n" + " \"metricValue\": 65,\n" + " \"metricName\": \"example.metric.one\"\n" + " },\n" + " {\n" + " \"collectionTime\": 1376509892612,\n" + " \"ttlInSeconds\": 172800,\n" + " \"metricValue\": 66,\n" + " \"metricName\": \"example.metric.two\"\n" + " },\n" + " ]'"; when(httpRequestMock.content()).thenReturn(Unpooled.copiedBuffer(payload.getBytes("UTF-8"))); // add tenant and track tracker.addTenant(tenantId); tracker.track(httpRequestMock); // verify verify(loggerMock, atLeastOnce()).info("[TRACKER] tenantId " + tenantId + " added."); verify(loggerMock, atLeastOnce()).info((String)argCaptor.capture()); assertThat(argCaptor.getValue().toString(), containsString("[TRACKER] POST request for tenantId " + tenantId + ": /v2.0/" + tenantId + "/ingest?param1=value1&param1=value2\n" + "HEADERS: \n" + "X-Auth-Token\tAUTHTOKEN\n" + "REQUEST_CONTENT:\n" + "[\n" + " {\n" + " \"collectionTime\": 1376509892612,\n" + " \"ttlInSeconds\": 172800,\n" + " \"metricValue\": 65,\n" + " \"metricName\": \"example.metric.one\"\n" + " },\n" + " {\n" + " \"collectionTime\": 1376509892612,\n" + " \"ttlInSeconds\": 172800,\n" + " \"metricValue\": 66,\n" + " \"metricName\": \"example.metric.two\"\n" + " },\n" + " ]'")); } @Test public void testTrackNullRequest() { when(httpRequestMock.getUri()).thenReturn("/v2.0/" + tenantId + "/ingest"); // add tenant to track but provide a null request for tracking tracker.addTenant(tenantId); tracker.track(null); // verify logger does not get called for tracking request verify(httpRequestMock, never()).getUri(); verify(loggerMock, atLeastOnce()).info((String)argCaptor.capture()); assertThat(argCaptor.getValue().toString(), not(containsString("[TRACKER] POST request for tenantId " + tenantId))); assertThat(argCaptor.getValue().toString(), not(containsString("[TRACKER] GET request for tenantId " + tenantId))); assertThat(argCaptor.getValue().toString(), not(containsString("[TRACKER] PUT request for tenantId " + tenantId))); } @Test public void testDoesNotTrackTenant() { // setup mock returns URI when(httpRequestMock.getUri()).thenReturn("/v2.0/" + tenantId + "/ingest"); // make sure tenantId is removed and track tracker.removeTenant(tenantId); tracker.track(httpRequestMock); // verify does not log for tenantId verify(loggerMock, atLeastOnce()).info((String)argCaptor.capture()); assertThat(argCaptor.getValue().toString(), not(containsString("[TRACKER] POST request for tenantId " + tenantId))); assertThat(argCaptor.getValue().toString(), not(containsString("[TRACKER] GET request for tenantId " + tenantId))); assertThat(argCaptor.getValue().toString(), not(containsString("[TRACKER] PUT request for tenantId " + tenantId))); } @Test public void testTrackResponse() throws Exception { // setup mock returns for query POST String requestUri = "/v2.0/" + tenantId + "/metrics/search"; when(httpRequestMock.getUri()).thenReturn(requestUri); when(httpMethodMock.toString()).thenReturn("GET"); when(httpRequestMock.getMethod()).thenReturn(httpMethodMock); List<String> paramValues = new ArrayList<String>(); paramValues.add("locator1"); queryParams.put("query", paramValues); when((httpRequestMock).getQueryParams()).thenReturn(queryParams); when(httpResponseStatusMock.code()).thenReturn(200); when(httpResponseMock.getStatus()).thenReturn(httpResponseStatusMock); //when(channelBufferMock.toString(any(Charset.class))).thenReturn( String result = "[TRACKER] Response for tenantId " + tenantId; when(httpResponseMock.content()).thenReturn(Unpooled.copiedBuffer(result.getBytes("UTF-8"))); // add tenant and track tracker.addTenant(tenantId); tracker.trackResponse(httpRequestMock, httpResponseMock); // verify verify(loggerMock, atLeastOnce()).info("[TRACKER] tenantId " + tenantId + " added."); verify(loggerMock, times(1)).info("[TRACKER] Response for tenantId " + tenantId + " GET request " + requestUri + "?query=locator1\n" + "RESPONSE_STATUS: 200\n" + "RESPONSE HEADERS: \n" + "RESPONSE_CONTENT:\n" + "[TRACKER] Response for tenantId " + tenantId); } @Test public void testTrackNullResponse() { String requestUri = "/v2.0/" + tenantId + "/metrics/search"; when(httpRequestMock.getUri()).thenReturn(requestUri); // add tenant to track but provide a null response for tracking tracker.addTenant(tenantId); tracker.trackResponse(httpRequestMock, null); // verify logger does not get called for tracking response verify(httpRequestMock, never()).getUri(); verify(loggerMock, atLeastOnce()).info((String)argCaptor.capture()); assertThat(argCaptor.getValue().toString(), not(containsString("[TRACKER] Response for tenantId " + tenantId))); } @Test public void testDoesNotTrackTenantResponse() { // setup mock returns URI when(httpRequestMock.getUri()).thenReturn("/v2.0/" + tenantId + "/metrics/search"); // make sure tenantId is removed and track tracker.removeTenant(tenantId); tracker.trackResponse(httpRequestMock, httpResponseMock); // verify does not log for tenantId verify(loggerMock, atLeastOnce()).info((String)argCaptor.capture()); assertThat(argCaptor.getValue().toString(), not(containsString("[TRACKER] Response for tenantId " + tenantId))); } @Test public void testTrackDelayedMetricsTenant() { // enable tracking delayed metrics and track tracker.setIsTrackingDelayedMetrics(); tracker.trackDelayedMetricsTenant(tenantId, delayedMetrics); // verify verify(loggerMock, atLeastOnce()).info("[TRACKER] Tracking delayed metrics started"); verify(loggerMock, atLeastOnce()).info("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics " + tenantId); verify(loggerMock, atLeastOnce()).info(contains("[TRACKER][DELAYED METRIC] " + tenantId + ".delayed.metric1 has collectionTime 2016-01-01 00:00:00 which is delayed")); verify(loggerMock, atLeastOnce()).info(contains("[TRACKER][DELAYED METRIC] " + tenantId + ".delayed.metric2 has collectionTime 2016-01-01 00:00:00 which is delayed")); } @Test public void testDoesNotTrackDelayedMetricsTenant() { // disable tracking delayed metrics and track tracker.resetIsTrackingDelayedMetrics(); tracker.trackDelayedMetricsTenant(tenantId, delayedMetrics); // verify verify(loggerMock, atLeastOnce()).info("[TRACKER] Tracking delayed metrics stopped"); verify(loggerMock, never()).info("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics " + tenantId); verify(loggerMock, never()).info(contains("[TRACKER][DELAYED METRIC] " + tenantId + ".delayed.metric1 has collectionTime 2016-01-01 00:00:00")); verify(loggerMock, never()).info(contains("[TRACKER][DELAYED METRIC] " + tenantId + ".delayed.metric2 has collectionTime 2016-01-01 00:00:00")); } @Test public void testTrackDelayedAggregatedMetricsTenant() { // enable tracking delayed metrics and track tracker.setIsTrackingDelayedMetrics(); List<String> delayedMetricNames = new ArrayList<String>() {{ for ( Metric metric : delayedMetrics ) { add(metric.getLocator().toString()); } }}; long ingestTime = System.currentTimeMillis(); tracker.trackDelayedAggregatedMetricsTenant(tenantId, delayedMetrics.get(0).getCollectionTime(), ingestTime, delayedMetricNames); // verify verify(loggerMock, atLeastOnce()).info("[TRACKER] Tracking delayed metrics started"); verify(loggerMock, atLeastOnce()).info("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics " + tenantId); verify(loggerMock, atLeastOnce()).info(contains("[TRACKER][DELAYED METRIC] " + tenantId + ".delayed.metric1" + "," + tenantId + ".delayed.metric2 have collectionTime 2016-01-01 00:00:00 which is delayed")); } @Test public void testDoesNotTrackDelayedAggregatedMetricsTenant() { // disable tracking delayed metrics and track tracker.resetIsTrackingDelayedMetrics(); tracker.trackDelayedMetricsTenant(tenantId, delayedMetrics); // verify verify(loggerMock, atLeastOnce()).info("[TRACKER] Tracking delayed metrics stopped"); verify(loggerMock, never()).info("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics " + tenantId); verify(loggerMock, never()).info(contains("[TRACKER][DELAYED METRIC] " + tenantId + ".delayed.metric1" + "," + tenantId + ".delayed.metric2 have collectionTime 2016-01-01 00:00:00 which is delayed")); } }
3e012d9c175ed615b1ee8408a41acc9467758232
1,116
java
Java
app/src/main/java/com/bx/philosopher/ui/adapter/view/MyRecordHolder.java
leeef/Novel
4d06403bbb8783b2273d2905f29645b3adb0676f
[ "MIT" ]
null
null
null
app/src/main/java/com/bx/philosopher/ui/adapter/view/MyRecordHolder.java
leeef/Novel
4d06403bbb8783b2273d2905f29645b3adb0676f
[ "MIT" ]
null
null
null
app/src/main/java/com/bx/philosopher/ui/adapter/view/MyRecordHolder.java
leeef/Novel
4d06403bbb8783b2273d2905f29645b3adb0676f
[ "MIT" ]
null
null
null
29.368421
105
0.721326
491
package com.bx.philosopher.ui.adapter.view; import android.widget.TextView; import com.bx.philosopher.R; import com.bx.philosopher.base.adapter.ViewHolderImpl; import com.bx.philosopher.model.bean.response.RecordBean; import java.text.SimpleDateFormat; import java.util.Date; public class MyRecordHolder extends ViewHolderImpl<RecordBean> { private TextView record_time; private TextView record_name; private TextView record_money; private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); @Override protected int getItemLayoutId() { return R.layout.my_record_item; } @Override public void initView() { record_time = findById(R.id.record_time); record_name = findById(R.id.record_name); record_money = findById(R.id.record_money); } @Override public void onBind(RecordBean data, int pos) { record_name.setText(data.getContent()); record_time.setText(simpleDateFormat.format(new Date(Long.parseLong(data.getAddtime()) * 1000))); record_money.setText("$ " + data.getTotal()); } }
3e012d9e975c9a056007ac53ee47afda9d49f90d
1,035
java
Java
container-service/domain/src/main/java/com/oc/hawk/container/domain/model/runtime/config/volume/InstanceVolume.java
kangta123/hawk
d1c70e3528ace69c5d705c606c8562ddd8402639
[ "BSD-2-Clause" ]
34
2021-03-04T02:19:22.000Z
2022-01-25T08:11:23.000Z
container-service/domain/src/main/java/com/oc/hawk/container/domain/model/runtime/config/volume/InstanceVolume.java
kangta123/hawk
d1c70e3528ace69c5d705c606c8562ddd8402639
[ "BSD-2-Clause" ]
8
2021-01-05T08:36:33.000Z
2021-02-02T08:37:08.000Z
container-service/domain/src/main/java/com/oc/hawk/container/domain/model/runtime/config/volume/InstanceVolume.java
kangta123/hawk
d1c70e3528ace69c5d705c606c8562ddd8402639
[ "BSD-2-Clause" ]
8
2021-01-25T06:42:23.000Z
2022-01-21T23:55:54.000Z
24.642857
77
0.682126
492
package com.oc.hawk.container.domain.model.runtime.config.volume; import com.google.common.base.Objects; import com.oc.hawk.ddd.DomainValueObject; import lombok.Getter; import lombok.NoArgsConstructor; @DomainValueObject @Getter @NoArgsConstructor public abstract class InstanceVolume { private String mountPath; private String volumeName; private String type; public InstanceVolume(String volumeName, String mountPath, String type) { this.volumeName = volumeName; this.mountPath = mountPath; this.type = type; } public InstanceVolume(String volumeName, String mountPath) { this.volumeName = volumeName; this.mountPath = mountPath; } @Override public boolean equals(Object o) { if (this == o) { return true; } InstanceVolume volume = (InstanceVolume) o; return Objects.equal(volumeName, volume.volumeName); } @Override public int hashCode() { return Objects.hashCode(volumeName); } }
3e012e391127064ff9b7dec7530849182d2278fd
1,695
java
Java
java_bank_Project/Java File/BMS/src/bms/custser.java
turzoahsan/java_atm_project
1465aaa479f0a4bcd23ae3d8603f3615f04830b9
[ "Apache-2.0" ]
null
null
null
java_bank_Project/Java File/BMS/src/bms/custser.java
turzoahsan/java_atm_project
1465aaa479f0a4bcd23ae3d8603f3615f04830b9
[ "Apache-2.0" ]
null
null
null
java_bank_Project/Java File/BMS/src/bms/custser.java
turzoahsan/java_atm_project
1465aaa479f0a4bcd23ae3d8603f3615f04830b9
[ "Apache-2.0" ]
null
null
null
23.219178
63
0.533923
493
package bms; import java.sql.*; import javax.swing.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class custser extends sqlquary implements ActionListener { public JFrame cus; private JButton cr,dp,mt,ci,bac,cracc; public custser() { cus = new JFrame(); cr = new JButton("Credit"); dp = new JButton("Deposit"); mt = new JButton("Tranfer Balance"); ci = new JButton("Customer information"); cracc = new JButton("Create Account"); bac = new JButton("Back"); cus.setTitle("Customer Service"); cus.setSize(200,200); cus.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cus.setLayout(new FlowLayout()); cus.add(cr); cus.add(dp); cus.add(mt); cus.add(ci); cus.add(cracc); cus.add(bac); cus.setResizable(false); cus.setVisible(true); cr.addActionListener(this); dp.addActionListener(this); mt.addActionListener(this); ci.addActionListener(this); cracc.addActionListener(this); bac.addActionListener(this); } public void actionPerformed(ActionEvent e) { Object o = e.getSource(); if (o == bac) { cus.setVisible(false); main.h.ho.setVisible(true); } else if (o == cr) { main.c.cus.setVisible(false); main.cred.cr.setVisible(true); } else if (o == dp) { main.c.cus.setVisible(false); main.depo.dp.setVisible(true); } } }
3e012e6c22280e0c7bc11de39705017e6a09c650
366
java
Java
sdk/src/main/java/org/zstack/sdk/sns/AddSNSSmsReceiverResult.java
MatheMatrix/zstack
8da3508c624c0bd8f819da91eb28f7ebf34b8cba
[ "ECL-2.0", "Apache-2.0" ]
879
2017-02-16T02:01:44.000Z
2022-03-31T15:44:28.000Z
sdk/src/main/java/org/zstack/sdk/sns/AddSNSSmsReceiverResult.java
Abortbeen/zstack
40f195893250b84881798a702f3b2455c83336a1
[ "Apache-2.0" ]
482
2017-02-13T09:57:37.000Z
2022-03-31T07:17:29.000Z
sdk/src/main/java/org/zstack/sdk/sns/AddSNSSmsReceiverResult.java
Abortbeen/zstack
40f195893250b84881798a702f3b2455c83336a1
[ "Apache-2.0" ]
306
2017-02-13T08:31:29.000Z
2022-03-14T07:58:46.000Z
24.4
65
0.748634
494
package org.zstack.sdk.sns; import org.zstack.sdk.sns.SNSSmsReceiverInventory; public class AddSNSSmsReceiverResult { public SNSSmsReceiverInventory inventory; public void setInventory(SNSSmsReceiverInventory inventory) { this.inventory = inventory; } public SNSSmsReceiverInventory getInventory() { return this.inventory; } }
3e012f7a881f82352c35c5996a229ddbfd68424a
443
java
Java
src/main/java/lambdasinaction/chap03/RunnableTest.java
soft5/lambdasinaction
ba56863dd0f80d1e18ced98094159bdad7a55ee0
[ "Apache-2.0" ]
null
null
null
src/main/java/lambdasinaction/chap03/RunnableTest.java
soft5/lambdasinaction
ba56863dd0f80d1e18ced98094159bdad7a55ee0
[ "Apache-2.0" ]
null
null
null
src/main/java/lambdasinaction/chap03/RunnableTest.java
soft5/lambdasinaction
ba56863dd0f80d1e18ced98094159bdad7a55ee0
[ "Apache-2.0" ]
null
null
null
17.72
58
0.620767
495
package lambdasinaction.chap03; public class RunnableTest { public static void main(String ... args) { Runnable r1 = () -> System.out.println("Hello World 1"); Runnable r2 = new Runnable() { @Override public void run() { System.out.println("Hello World 2"); } }; process(r1); process(r2); process(() -> System.out.println("Hello World 3")); } public static void process(Runnable r) { r.run(); } }
3e012fd801f59db411e277bc58549465efdff9bf
1,748
java
Java
pinot-common/src/main/java/org/apache/pinot/common/config/ChildKeyHandler.java
liuyu81/apache-pinot
f58ba2db8cd794992659a83003aa9f9e58e71c56
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
2
2019-03-25T23:42:42.000Z
2019-04-01T23:07:01.000Z
pinot-common/src/main/java/org/apache/pinot/common/config/ChildKeyHandler.java
liuyu81/apache-pinot
f58ba2db8cd794992659a83003aa9f9e58e71c56
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
43
2019-10-14T16:22:39.000Z
2021-08-02T16:58:41.000Z
pinot-common/src/main/java/org/apache/pinot/common/config/ChildKeyHandler.java
liuyu81/apache-pinot
f58ba2db8cd794992659a83003aa9f9e58e71c56
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
38
114
0.741419
496
/** * 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.pinot.common.config; import io.vavr.collection.Map; /** * Child key handler interface, used to convert the child keys of a given configuration object into a Java object. */ public interface ChildKeyHandler<T> { /** * Convert child keys of a given configuration object into a value for this configuration object. * * @param childKeys The child keys of the configuration object * @param pathPrefix The current path in the configuration map * @return The newly created configuration object */ T handleChildKeys(Map<String, ?> childKeys, String pathPrefix); /** * Transform a configuration object into a map of child keys. * * @param value The value to turn into a map of child keys * @param pathPrefix The current path of the configuration object * @return A map representation of the configuration object */ Map<String, ?> unhandleChildKeys(T value, String pathPrefix); }
3e0130cf6c742b6822960872919b87c346d56da5
2,451
java
Java
components/core-services-exec/src/main/groovy/org/squonk/execution/steps/impl/DatasetSelectSliceStep.java
InformaticsMatters/lac
34183eab1dea692c79ef42efe8e32adbcfdd4b11
[ "Apache-2.0" ]
null
null
null
components/core-services-exec/src/main/groovy/org/squonk/execution/steps/impl/DatasetSelectSliceStep.java
InformaticsMatters/lac
34183eab1dea692c79ef42efe8e32adbcfdd4b11
[ "Apache-2.0" ]
null
null
null
components/core-services-exec/src/main/groovy/org/squonk/execution/steps/impl/DatasetSelectSliceStep.java
InformaticsMatters/lac
34183eab1dea692c79ef42efe8e32adbcfdd4b11
[ "Apache-2.0" ]
null
null
null
35.014286
118
0.671563
497
package org.squonk.execution.steps.impl; import org.apache.camel.CamelContext; import org.squonk.dataset.Dataset; import org.squonk.dataset.DatasetMetadata; import org.squonk.execution.steps.AbstractStep; import org.squonk.execution.steps.StepDefinitionConstants; import org.squonk.execution.variable.VariableManager; import java.util.logging.Logger; import java.util.stream.Stream; /** * * @author timbo */ public class DatasetSelectSliceStep extends AbstractStep { private static final Logger LOG = Logger.getLogger(DatasetSelectSliceStep.class.getName()); public static final String OPTION_SKIP = StepDefinitionConstants.DatasetSelectSlice.OPTION_SKIP; public static final String OPTION_COUNT = StepDefinitionConstants.DatasetSelectSlice.OPTION_COUNT; /** * Create a slice of the dataset skipping a number of records specified by the skip option (or 0 if not specified) * and including only the number of records specified by the count option (or till teh end if not specified). * * @param varman * @param context * @throws Exception */ @Override public void execute(VariableManager varman, CamelContext context) throws Exception { statusMessage = MSG_PREPARING_INPUT; Dataset ds = fetchMappedInput("input", Dataset.class, varman); if (ds == null) { throw new IllegalStateException("Input variable not found: input"); } LOG.fine("Input Dataset: " + ds); Integer skip = getOption(OPTION_SKIP, Integer.class); Integer count = getOption(OPTION_COUNT, Integer.class); statusMessage = "Setting filters ..."; Stream stream = (Stream)ds.getStream().sequential(); if (skip != null) { LOG.info("Setting skip to " + skip); stream = stream.skip(skip); } if (count != null) { LOG.info("Setting count to " + count); stream = stream.limit(count); } DatasetMetadata meta = ds.getMetadata(); meta.setSize(0); // will be recalculated Dataset results = new Dataset(stream, meta); String outFldName = mapOutputVariable("output"); if (outFldName != null) { createVariable(outFldName, Dataset.class, results, varman); } statusMessage = generateStatusMessage(ds.getSize(), results.getSize(), -1); LOG.info("Results: " + ds.getMetadata()); } }
3e01319ac9a1f1f1cb8a79f884d62329f738c9ba
315
java
Java
app/src/main/java/ywcai/ls/mina/socket/protocal/CodeFactory.java
ywcai/LsSocketForAndroid
939fc921cb1c95c8ed4dd7d98ba20e52d6af7396
[ "Apache-2.0" ]
1
2017-12-17T08:42:04.000Z
2017-12-17T08:42:04.000Z
app/src/main/java/ywcai/ls/mina/socket/protocal/CodeFactory.java
ywcai/LsSocketForAndroid
939fc921cb1c95c8ed4dd7d98ba20e52d6af7396
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ywcai/ls/mina/socket/protocal/CodeFactory.java
ywcai/LsSocketForAndroid
939fc921cb1c95c8ed4dd7d98ba20e52d6af7396
[ "Apache-2.0" ]
null
null
null
28.636364
71
0.761905
498
package ywcai.ls.mina.socket.protocal; import org.apache.mina.filter.codec.demux.DemuxingProtocolCodecFactory; public class CodeFactory extends DemuxingProtocolCodecFactory { public CodeFactory() { addMessageDecoder(MesDecode.class); addMessageEncoder(MesInf.class, new MesEncode()); } }
3e0132bfa486445e35d31cbd1529f08accecfbeb
2,998
java
Java
jetty-plus/src/main/java/org/eclipse/jetty/plus/annotation/PreDestroyCallback.java
simple569/jetty.project
d681f108536442f29b6bde54042e56220ad2bc82
[ "Apache-2.0" ]
4
2017-07-19T23:27:10.000Z
2021-01-02T11:12:53.000Z
jetty-plus/src/main/java/org/eclipse/jetty/plus/annotation/PreDestroyCallback.java
simple569/jetty.project
d681f108536442f29b6bde54042e56220ad2bc82
[ "Apache-2.0" ]
6
2021-12-19T02:33:51.000Z
2022-01-26T08:48:34.000Z
jetty-plus/src/main/java/org/eclipse/jetty/plus/annotation/PreDestroyCallback.java
simple569/jetty.project
d681f108536442f29b6bde54042e56220ad2bc82
[ "Apache-2.0" ]
1
2020-08-16T15:44:13.000Z
2020-08-16T15:44:13.000Z
31.229167
131
0.624416
499
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under // the terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0 // // This Source Code may also be made available under the following // Secondary Licenses when the conditions for such availability set // forth in the Eclipse Public License, v. 2.0 are satisfied: // the Apache License v2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.plus.annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * PreDestroyCallback */ public class PreDestroyCallback extends LifeCycleCallback { private static final Logger LOG = LoggerFactory.getLogger(PreDestroyCallback.class); /** * @param clazz the class object to be injected * @param methodName the name of the method to inject */ public PreDestroyCallback(Class<?> clazz, String methodName) { super(clazz, methodName); } /** * @param className the name of the class to inject * @param methodName the name of the method to inject */ public PreDestroyCallback(String className, String methodName) { super(className, methodName); } /** * Commons Annotations Specification section 2.6: * - no params to method * - returns void * - no checked exceptions * - not static * * @see org.eclipse.jetty.plus.annotation.LifeCycleCallback#validate(java.lang.Class, java.lang.reflect.Method) */ @Override public void validate(Class<?> clazz, Method method) { if (method.getExceptionTypes().length > 0) throw new IllegalArgumentException(clazz.getName() + "." + method.getName() + " cannot not throw a checked exception"); if (!method.getReturnType().equals(Void.TYPE)) throw new IllegalArgumentException(clazz.getName() + "." + method.getName() + " cannot not have a return type"); if (Modifier.isStatic(method.getModifiers())) throw new IllegalArgumentException(clazz.getName() + "." + method.getName() + " cannot be static"); } @Override public void callback(Object instance) { try { super.callback(instance); } catch (Exception e) { LOG.warn("Ignoring exception thrown on preDestroy call to " + getTargetClass() + "." + getTarget().getName(), e); } } @Override public boolean equals(Object o) { if (super.equals(o) && (o instanceof PreDestroyCallback)) return true; return false; } }
3e01330ce263ddd327d65d8c3e8b65578ab16b49
8,172
java
Java
src/main/java/ru/nanolive/draconicplus/common/fusioncrafting/network/PacketSyncableObject.java
Asek3/DraconicMinus-
32be5a8be5bd25334dd70cb48bdf4cb6735f28e4
[ "MIT" ]
null
null
null
src/main/java/ru/nanolive/draconicplus/common/fusioncrafting/network/PacketSyncableObject.java
Asek3/DraconicMinus-
32be5a8be5bd25334dd70cb48bdf4cb6735f28e4
[ "MIT" ]
1
2022-03-23T07:29:07.000Z
2022-03-23T07:29:07.000Z
src/main/java/ru/nanolive/draconicplus/common/fusioncrafting/network/PacketSyncableObject.java
Asek3/DraconicMinus-
32be5a8be5bd25334dd70cb48bdf4cb6735f28e4
[ "MIT" ]
null
null
null
36.482143
128
0.637298
500
package ru.nanolive.draconicplus.common.fusioncrafting.network; import java.io.IOException; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.relauncher.Side; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; import net.minecraft.tileentity.TileEntity; import ru.nanolive.draconicplus.common.fusioncrafting.BlockPos; import ru.nanolive.draconicplus.common.fusioncrafting.Vec3D; import ru.nanolive.draconicplus.common.fusioncrafting.tiles.TileInventoryBase; import ru.nanolive.draconicplus.network.AbstractMessage; public class PacketSyncableObject extends AbstractMessage.AbstractClientMessage<PacketSyncableObject> { public static final byte BOOLEAN_INDEX = 0; public static final byte BYTE_INDEX = 1; public static final byte INT_INDEX = 2; public static final byte DOUBLE_INDEX = 3; public static final byte FLOAT_INDEX = 4; public static final byte STRING_INDEX = 5; public static final byte TAG_INDEX = 6; public static final byte VEC3I_INDEX = 7; public static final byte LONG_INDEX = 8; public static final byte SHORT_INDEX = 9; public static final byte VEC3D_INDEX = 10; public BlockPos tilePos; public byte index; public String stringValue = ""; public float floatValue = 0F; public double doubleValue = 0; public int intValue = 0; public short shortValue = 0; public byte byteValue = 0; public boolean booleanValue = false; public NBTTagCompound compound; public Vec3D vec3D; public long longValue; public boolean updateOnReceived; public byte dataType; public PacketSyncableObject() { } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, boolean booleanValue, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.booleanValue = booleanValue; this.dataType = BOOLEAN_INDEX; } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, byte byteValue, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.byteValue = byteValue; this.dataType = BYTE_INDEX; } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, short shortValue, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.shortValue = shortValue; this.dataType = SHORT_INDEX; } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, int intValue, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.intValue = intValue; this.dataType = INT_INDEX; } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, double doubleValue, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.doubleValue = doubleValue; this.dataType = DOUBLE_INDEX; } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, float floatValue, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.floatValue = floatValue; this.dataType = FLOAT_INDEX; } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, String stringValue, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.stringValue = stringValue; this.dataType = STRING_INDEX; } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, NBTTagCompound compound, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.compound = compound; this.dataType = TAG_INDEX; } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, long longValue, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.longValue = longValue; this.dataType = LONG_INDEX; } public PacketSyncableObject(TileInventoryBase tile, byte syncableIndex, Vec3D vec3D, boolean updateOnReceived) { this.tilePos = new BlockPos(tile.xCoord, tile.yCoord, tile.zCoord); this.index = syncableIndex; this.vec3D = vec3D; this.dataType = VEC3D_INDEX; } @Override protected void read(PacketBuffer buffer) throws IOException { dataType = buffer.readByte(); index = buffer.readByte(); int x = buffer.readInt(); int y = buffer.readInt(); int z = buffer.readInt(); tilePos = new BlockPos(x, y, z); switch (dataType) { case BOOLEAN_INDEX: booleanValue = buffer.readBoolean(); break; case BYTE_INDEX: byteValue = buffer.readByte(); break; case INT_INDEX: intValue = buffer.readInt(); break; case DOUBLE_INDEX: doubleValue = buffer.readDouble(); break; case FLOAT_INDEX: floatValue = buffer.readFloat(); break; case STRING_INDEX: stringValue = ByteBufUtils.readUTF8String(buffer); break; case TAG_INDEX: compound = ByteBufUtils.readTag(buffer); break; case VEC3D_INDEX: vec3D = new Vec3D(0, 0, 0); vec3D.x = (int) buffer.readDouble(); vec3D.y = (int) buffer.readDouble(); vec3D.z = (int) buffer.readDouble(); break; case LONG_INDEX: longValue = buffer.readLong(); break; case SHORT_INDEX: shortValue = buffer.readShort(); break; } } @Override protected void write(PacketBuffer buffer) throws IOException { buffer.writeByte(dataType); buffer.writeByte(index); buffer.writeInt(tilePos.x); buffer.writeInt(tilePos.y); buffer.writeInt(tilePos.z); switch (dataType) { case BOOLEAN_INDEX: buffer.writeBoolean(booleanValue); break; case BYTE_INDEX: buffer.writeByte(byteValue); break; case INT_INDEX: buffer.writeInt(intValue); break; case DOUBLE_INDEX: buffer.writeDouble(doubleValue); break; case FLOAT_INDEX: buffer.writeFloat(floatValue); break; case STRING_INDEX: ByteBufUtils.writeUTF8String(buffer, stringValue); break; case TAG_INDEX: ByteBufUtils.writeTag(buffer, compound); break; case VEC3D_INDEX: buffer.writeDouble(vec3D.x); buffer.writeDouble(vec3D.y); buffer.writeDouble(vec3D.z); break; case LONG_INDEX: buffer.writeLong(longValue); break; case SHORT_INDEX: buffer.writeShort(shortValue); break; } } @Override protected void process(EntityPlayer player, Side side) { if(side.isClient()) { TileEntity tile = FMLClientHandler.instance().getWorldClient().getTileEntity(tilePos.x, tilePos.y, tilePos.z); if (tile instanceof TileInventoryBase) { ((TileInventoryBase) tile).receiveSyncPacketFromServer(this); } } } }