hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
b663f26fdec575077a86030f80644e2d8c9f3cd8
7,250
/** */ package de.fhdo.lemma.service.intermediate; import de.fhdo.lemma.data.intermediate.IntermediateImport; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Interface Reference</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * * * Reference to an interface required by a microservice * <!-- end-model-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getName <em>Name</em>}</li> * <li>{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getQualifiedName <em>Qualified Name</em>}</li> * <li>{@link de.fhdo.lemma.service.intermediate.InterfaceReference#isImported <em>Imported</em>}</li> * <li>{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getImport <em>Import</em>}</li> * <li>{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getLocalInterface <em>Local Interface</em>}</li> * <li>{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getRequiringMicroservice <em>Requiring Microservice</em>}</li> * </ul> * * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getInterfaceReference() * @model * @generated */ public interface InterfaceReference extends EObject { /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getInterfaceReference_Name() * @model unique="false" * @generated */ String getName(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Qualified Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Qualified Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Qualified Name</em>' attribute. * @see #setQualifiedName(String) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getInterfaceReference_QualifiedName() * @model unique="false" * @generated */ String getQualifiedName(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getQualifiedName <em>Qualified Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Qualified Name</em>' attribute. * @see #getQualifiedName() * @generated */ void setQualifiedName(String value); /** * Returns the value of the '<em><b>Imported</b></em>' attribute. * The default value is <code>"false"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Imported</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Imported</em>' attribute. * @see #setImported(boolean) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getInterfaceReference_Imported() * @model default="false" unique="false" * @generated */ boolean isImported(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.InterfaceReference#isImported <em>Imported</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Imported</em>' attribute. * @see #isImported() * @generated */ void setImported(boolean value); /** * Returns the value of the '<em><b>Import</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Import</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Import</em>' reference. * @see #setImport(IntermediateImport) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getInterfaceReference_Import() * @model * @generated */ IntermediateImport getImport(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getImport <em>Import</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Import</em>' reference. * @see #getImport() * @generated */ void setImport(IntermediateImport value); /** * Returns the value of the '<em><b>Local Interface</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Local Interface</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Local Interface</em>' reference. * @see #setLocalInterface(IntermediateInterface) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getInterfaceReference_LocalInterface() * @model * @generated */ IntermediateInterface getLocalInterface(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getLocalInterface <em>Local Interface</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Local Interface</em>' reference. * @see #getLocalInterface() * @generated */ void setLocalInterface(IntermediateInterface value); /** * Returns the value of the '<em><b>Requiring Microservice</b></em>' container reference. * It is bidirectional and its opposite is '{@link de.fhdo.lemma.service.intermediate.IntermediateMicroservice#getRequiredInterfaces <em>Required Interfaces</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Requiring Microservice</em>' container reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Requiring Microservice</em>' container reference. * @see #setRequiringMicroservice(IntermediateMicroservice) * @see de.fhdo.lemma.service.intermediate.IntermediatePackage#getInterfaceReference_RequiringMicroservice() * @see de.fhdo.lemma.service.intermediate.IntermediateMicroservice#getRequiredInterfaces * @model opposite="requiredInterfaces" transient="false" * @generated */ IntermediateMicroservice getRequiringMicroservice(); /** * Sets the value of the '{@link de.fhdo.lemma.service.intermediate.InterfaceReference#getRequiringMicroservice <em>Requiring Microservice</em>}' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Requiring Microservice</em>' container reference. * @see #getRequiringMicroservice() * @generated */ void setRequiringMicroservice(IntermediateMicroservice value); } // InterfaceReference
36.989796
167
0.682897
eeaf495cb61b4a9c871853984503bdb6c4f12f0a
5,643
// ========================================================================= // <editor-fold defaultstate="collapsed" desc="The MIT License"> // ------------------------------------------------------------------------- // // Copyright 2018 QuikMod. // // 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. // // ------------------------------------------------------------------------- // </editor-fold> // ========================================================================= package com.github.quikmod.quikutil.configuration; import com.google.common.collect.ImmutableList; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; /** * Class representing a configuration entry. * * @author Ryan * * @param <V> the type of the element. */ public interface ConfigEntry<V> { /** * Retrieves the key associated with this configuration entry. * * @return the key associated with this entry. */ @Nonnull String getKey(); /** * Retrieves the comment associated with this configuration entry. * * Required to return non-null, to prevent null pointer exceptions. In the * case there is no comment associated with the entry this method should * instead return the empty string. * * @return the comment associated with this entry. */ @Nonnull String getComment(); /** * Retrieves the type token representing this entry's type. * * @return the class representing this entry's type. */ @Nonnull Class<V> getValueType(); /** * Retrieves the default value associated with this entry, as defined by the * application. * * @return the default value associated with this entry. */ @Nonnull V getDefaultValue(); /** * Retrieves the value that was previously associated with this entry. In * the case that there was no previous value this will return the default * value instead. * * @return the value to be associated with this configuration entry next, or * the current value if there exists no upcoming value. */ @Nonnull V getPriorValue(); /** * Retrieves the value associated with this entry. * * @return the value associated with this entry. */ @Nonnull V getValue(); /** * Retrieves the value that is to be associated with this entry on the next * configuration reload of adequate level. * * @return the value to be associated with this configuration entry next, or * the current value if there exists no upcoming value. */ @Nonnull V getFutureValue(); /** * Determines the reload level required for the future value of the * configuration entry to become the current value. * * As level {@literal 255} is the maximum value, a full configuration reload * will occur at level 255. * * @return the reload level required for the configuration entry to fully * reload. */ @Nonnegative short getReloadLevel(); /** * Retrieves an immutable list of constraints on this configuration entry's * value, as defined by the application at the time that the configuration * was constructed. * * @return an immutable list containing all the constraints on the entry's * value. */ @Nonnull ImmutableList<ConfigEntryConstraint<V>> getConstraints(); /** * Retrieves the configuration adapter used internally by this configuration * entry. * * @return the configuration adapter used by this configuration entry. */ @Nonnull ConfigAdapter getAdapter(); /** * Suggests that the configuration entry should be reloaded, at the lowest * possible reload level. */ void refresh(); /** * Reloads the configuration element at the given update level, by * transcribing the elements value from the configuration source. * * Specifically this method will do the following: * <ol> * <li>Fetch the entry's new value from the configuration source.</li> * <li>Validate the new fetched value against all constraints.</li> * <li>Set the next value to the validated fetched value.</li> * <li>Checks if the {@code reloadLevel} is less than * {@link #getReloadLevel()}</li> * <li>Set the previous value to the current value.</li> * <li>Set the current value to the next value.</li> * </ol> * * @param reloadLevel the level to reload the configuration entry at. */ void reload(@Nonnegative short reloadLevel); }
33.589286
80
0.64168
3527468404a00b5abc0c3e0499009ccff811d8ca
13,436
package br.ufc.mdcc.benchimage; import java.io.File; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.graphics.Color; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Process; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import br.ufc.mdcc.benchimage.data.Config; import br.ufc.mdcc.benchimage.data.Result; import br.ufc.mdcc.benchimage.task.BitmapProcessLocalTask; import br.ufc.mdcc.benchimage.task.BitmapProcessRemoteTask; import br.ufc.mdcc.benchimage.util.OnItemSelectedListenerAdapter; import br.ufc.mdcc.benchimage.util.WidgetUtil; import br.ufc.mdcc.mpos.util.ExportDatabase; import br.ufc.mdcc.mpos.util.TaskResultAdapter; /** * @author Philipp */ public final class MainActivity extends Activity { private WidgetUtil wu; private Config config; private final String LOG = MainActivity.class.getSimpleName(); private SharedPreferences preferences; private String photoName; private String outputDir; private long vmSize = 0L; private String cloudletIp = "192.168.42.133"; private String cloudIp = "200.129.39.120"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wu = new WidgetUtil(this); config = new Config(); configureSpinner(); configureButton(); configureStatusView(); preferencesLoading(); createDirOutput(); processImage(); Log.i(LOG, "Iniciou PicFilter"); } private void preferencesLoading() { preferences = getSharedPreferences("picfilter", Context.MODE_PRIVATE); cloudletIp = preferences.getString("cloudletIp", "192.168.42.133"); } private void processImage() { TaskResultAdapter<Result> taskResultAdapter = new TaskResultAdapter<Result>() { @Override public void completedTask(Result obj) { if (obj != null) { ImageView imageView = (ImageView) findViewById(R.id.imageView); imageView.setImageBitmap(obj.getBitmap()); TextView tv_tamanho = (TextView) findViewById(R.id.tv_tamanho); tv_tamanho.setText("Tamanho/Foto: " + config.getSize() + "/" + photoName); TextView tv_execucao = (TextView) findViewById(R.id.tv_execucao); if (obj.getTotalTime() != 0) { double segundos = obj.getTotalTime() / 1000.0; tv_execucao.setText("Tempo de\nExecução: " + String.format("%.3f", segundos) + "s"); } else { tv_execucao.setText("Tempo de\nExecução: 0s"); } if (obj.getConfig().getFilter().equals("Benchmark")) { double segundos = obj.getTotalTime() / 1000.0; tv_execucao.setText("Tempo de\nExecução: " + String.format("%.3f", segundos) + "s"); } buttonStatusChange(R.id.buttonExecute, true, "Inicia"); } else { TextView tv_status = (TextView) findViewById(R.id.tv_status); tv_status.setText("Status: Algum Error na transmissão!"); buttonStatusChange(R.id.buttonExecute, true, "Inicia"); } } @Override public void taskOnGoing(int completed, String statusText) { TextView tv_status = (TextView) findViewById(R.id.tv_status); tv_status.setText("Status: " + statusText); } }; TextView tv_execucao = (TextView) findViewById(R.id.tv_execucao); tv_execucao.setText("Tempo de\nExecução: 0s"); TextView tv_tamanho = (TextView) findViewById(R.id.tv_tamanho); tv_tamanho.setText("Tamanho/Foto: " + config.getSize() + "/" + photoName); ImageView imageView = (ImageView) findViewById(R.id.imageView); imageView.setImageBitmap(null); // obtem as config from spinner getConfigFromSpinner(); System.gc(); if (config.getFilter().equals("Cartoonizer") && vmSize <= 64 && (config.getSize().equals("8MP") || config.getSize().equals("6MP") || config.getSize().equals("4MP"))) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle("Celular limitado!"); alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); alertDialogBuilder.setNegativeButton(R.string.button_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialogBuilder.setMessage("Celular não suporta o Cartoonizer, minimo recomendo é 128MB de VMSize"); // cria e mostra alertDialogBuilder.create().show(); buttonStatusChange(R.id.buttonExecute, true, "Inicia"); TextView tv_status = (TextView) findViewById(R.id.tv_status); tv_status.setText("Status: Requisição anterior não suporta Filtro!"); } else { if (config.getLocal().equals("Local")) { executeTask(new BitmapProcessLocalTask(taskResultAdapter, outputDir, getApplicationContext(), config)); } else { if (config.getLocal().equals("Cloudlet")) { // cloudlet executeTask(new BitmapProcessRemoteTask(taskResultAdapter, outputDir, getApplicationContext(), config, cloudletIp)); } else { // cloud on Internet executeTask(new BitmapProcessRemoteTask(taskResultAdapter, outputDir, getApplicationContext(), config, cloudIp)); } } } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void executeTask(AsyncTask<Void, String, Result> bitmapTask) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { bitmapTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { bitmapTask.execute(); } } private void createDirOutput() { File storage = Environment.getExternalStorageDirectory(); outputDir = storage.getAbsolutePath() + File.separator + "PicFilter_Temp"; File dir = new File(outputDir); if (!dir.exists()) { dir.mkdir(); } } @Override protected void onDestroy() { super.onDestroy(); Process.killProcess(Process.myPid()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); switch (item.getItemId()) { case R.id.menu_action_ip_cloudlet: // instancia um EditText final EditText editText = new EditText(this); editText.setText(cloudletIp); editText.setRawInputType(Configuration.KEYBOARD_12KEY); alertDialogBuilder.setTitle("Cloudlet IP"); alertDialogBuilder.setMessage("Digite o IP do Cloudlet"); alertDialogBuilder.setView(editText); alertDialogBuilder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { cloudletIp = editText.getText().toString(); Editor edit = preferences.edit(); edit.putString("cloudletIp", cloudletIp); edit.apply(); } }); alertDialogBuilder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); alertDialogBuilder.create().show(); break; case R.id.menu_action_export: alertDialogBuilder.setTitle("Exportação de Banco de dados"); alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); alertDialogBuilder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // invoca o classe que exporta banco de dados... new ExportDatabase(MainActivity.this, "app.db", "benchimage_backup.db").execute(); } }); alertDialogBuilder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialogBuilder.setMessage("Deseja exportar banco de dados?"); // cria e mostra alertDialogBuilder.create().show(); break; } return true; } public void onBackPressed() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle(R.string.alert_exit_title); alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); alertDialogBuilder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); alertDialogBuilder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialogBuilder.setMessage(R.string.alert_exit_message); // cria e mostra alertDialogBuilder.create().show(); } private void configureButton() { wu.setListeningButton(R.id.buttonExecute, new Button.OnClickListener() { @Override public void onClick(View v) { buttonStatusChange(R.id.buttonExecute, false, "Processando"); processImage(); } }); } private void buttonStatusChange(int id, boolean state, String text) { Button but = (Button) findViewById(id); but.setEnabled(state); but.setText(text); } private void configureSpinner() { Spinner spinnerImage = (Spinner) findViewById(R.id.spin_image); Spinner spinnerFilter = (Spinner) findViewById(R.id.spin_filter); Spinner spinnerSize = (Spinner) findViewById(R.id.spin_size); Spinner spinnerLocal = (Spinner) findViewById(R.id.spin_local); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.spinner_img, R.layout.spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerImage.setAdapter(adapter); spinnerImage.setSelection(2); adapter = ArrayAdapter.createFromResource(this, R.array.spinner_filter, R.layout.spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerFilter.setAdapter(adapter); adapter = ArrayAdapter.createFromResource(this, R.array.spinner_local, R.layout.spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerLocal.setAdapter(adapter); adapter = ArrayAdapter.createFromResource(this, R.array.spinner_size, R.layout.spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerSize.setAdapter(adapter); spinnerSize.setSelection(6); spinnerImage.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { photoName = (String) parent.getItemAtPosition(pos); config.setImage(photoToFileName(photoName)); } }); spinnerFilter.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { config.setFilter((String) parent.getItemAtPosition(pos)); } }); spinnerSize.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { config.setSize((String) parent.getItemAtPosition(pos)); } }); spinnerLocal.setOnItemSelectedListener(new OnItemSelectedListenerAdapter() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { config.setLocal((String) parent.getItemAtPosition(pos)); } }); getConfigFromSpinner(); } private void getConfigFromSpinner() { Spinner spinnerImage = (Spinner) findViewById(R.id.spin_image); Spinner spinnerFilter = (Spinner) findViewById(R.id.spin_filter); Spinner spinnerSize = (Spinner) findViewById(R.id.spin_size); Spinner spinnerLocal = (Spinner) findViewById(R.id.spin_local); photoName = (String) spinnerImage.getSelectedItem(); config.setImage(photoToFileName(photoName)); config.setFilter((String) spinnerFilter.getSelectedItem()); config.setSize((String) spinnerSize.getSelectedItem()); config.setLocal((String) spinnerLocal.getSelectedItem()); } private void configureStatusView() { TextView tv_vmsize = (TextView) findViewById(R.id.tv_vmsize); vmSize = Runtime.getRuntime().maxMemory() / (1024 * 1024); tv_vmsize.setText("VMSize " + vmSize + "MB"); if (vmSize < 128) { tv_vmsize.setTextColor(Color.RED); } else if (vmSize == 128) { tv_vmsize.setTextColor(Color.YELLOW); } else { tv_vmsize.setTextColor(Color.GREEN); } TextView tv_execucao = (TextView) findViewById(R.id.tv_execucao); tv_execucao.setText("Tempo de\nExecução: 0s"); TextView tv_tamanho = (TextView) findViewById(R.id.tv_tamanho); tv_tamanho.setText("Tamanho/Foto: " + config.getSize() + "/" + photoName); TextView tv_status = (TextView) findViewById(R.id.tv_status); tv_status.setText("Status: Sem Atividade"); } private String photoToFileName(String name) { if (name.equals("FAB Show")) { return "img1.jpg"; } else if (name.equals("Cidade")) { return "img4.jpg"; } else if (name.equals("SkyLine")) { return "img5.jpg"; } return null; } }
33.175309
169
0.739208
4b23f4431dedd5878fb0c5ead08f6dc996fe4efc
416
package com.nodeunify.jupiter.postman; import java.util.Calendar; public class CalendarTest { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); int ctpYear = cal.get(Calendar.YEAR); int ctpMonth = cal.get(Calendar.MONTH); int ctpDay = cal.get(Calendar.DAY_OF_MONTH); System.out.println(ctpYear + " - " + ctpMonth + " - " + ctpDay); } }
29.714286
72
0.644231
9868d8ae5cb9fb57773f66859607c1d3e413878e
1,846
/* * Copyright (c) Numerical Method Inc. * http://www.numericalmethod.com/ * * THIS SOFTWARE IS LICENSED, NOT SOLD. * * YOU MAY USE THIS SOFTWARE ONLY AS DESCRIBED IN THE LICENSE. * IF YOU ARE NOT AWARE OF AND/OR DO NOT AGREE TO THE TERMS OF THE LICENSE, * DO NOT USE THIS SOFTWARE. * * THE SOFTWARE IS PROVIDED "AS IS", WITH NO WARRANTY WHATSOEVER, * EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, * ANY WARRANTIES OF ACCURACY, ACCESSIBILITY, COMPLETENESS, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, NON-INFRINGEMENT, * TITLE AND USEFULNESS. * * IN NO EVENT AND UNDER NO LEGAL THEORY, * WHETHER IN ACTION, CONTRACT, NEGLIGENCE, TORT, OR OTHERWISE, * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIMS, DAMAGES OR OTHER LIABILITIES, * ARISING AS A RESULT OF USING OR OTHER DEALINGS IN THE SOFTWARE. */ package com.numericalmethod.suanshu.analysis.sequence; /** * A sequence is an ordered list of (real) numbers. * Although some sequences, e.g., Fibonacci, have infinitely many elements, * we can, in practice, compute only finitely many of them. * * @author Haksun Li * @see <a href="http://en.wikipedia.org/wiki/Sequence">Wikipedia: Sequence</a> */ public interface Sequence { /** * Get the number of <em>computed</em> terms in the sequence. * * @return the length of sequence */ public int length(); /** * Get the <i>i</i>-th entry in the sequence, counting from 1. * * @param i an index * @return the <i>i</i>-th entry in the sequence */ public double get(int i); /** * Get a copy of the whole (finite) sequence in {@code double[]}. * * @return a copy of all the computed terms in the sequence */ public double[] getAll(); }
32.385965
80
0.655471
435fdbf232a29cf4a923247764afebc91870f5c4
23,223
package com.seleniumsimplified.webdriver.manager; import org.openqa.selenium.Platform; import org.openqa.selenium.UnsupportedCommandException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.firefox.MarionetteDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.Properties; import java.util.Set; /** * A singleton style manager to maintain Drivers to prevent * test slowdown for creating a browser for each class with tests. * * Also counts time to start a browser and extrapolates from that how much * time you have saved using such hacky code. */ public class Driver extends Thread{ private static WebDriver aDriver=null; private static long browserStartTime = 0L; private static long savedTimecount = 0L; public static final long DEFAULT_TIMEOUT_SECONDS = 10; private static boolean avoidRecursiveCall=false; public static final String BROWSER_PROPERTY_NAME = "selenium2basics.webdriver"; private static final String DEFAULT_BROWSER = "GOOGLECHROME"; public enum BrowserName{FIREFOX, FIREFOXLEGACY, GOOGLECHROME, SAUCELABS, IE, HTMLUNIT, GRID, FIREFOXPORTABLE, FIREFOXMARIONETTE, APPIUM, EDGE} public static BrowserName currentDriver; private static BrowserName useThisDriver = null; // default for browsermob localhost:8080 // default for fiddler: localhost:8888 public static String PROXYHOST="localhost"; public static String PROXYPORT="8888"; public static String PROXY=PROXYHOST+":"+PROXYPORT; public static void set(BrowserName aBrowser){ useThisDriver = aBrowser; // close any existing driver if(aDriver != null){ aDriver.quit(); aDriver = null; } } public static WebDriver get() { if(useThisDriver == null){ //String defaultBrowser = System.getProperty(BROWSER_PROPERTY_NAME, DEFAULT_BROWSER); // to allow setting the browser as a property or an environment variable String defaultBrowser = EnvironmentPropertyReader.getPropertyOrEnv(BROWSER_PROPERTY_NAME, DEFAULT_BROWSER); /* Note: I generally use the Java 1.7 format that you can see below this chunk of code. where the switch statement uses a String. Java 1.6 does not support this, since people have tried to use this code on older versions of Java, and this is really the only Java 1.7 specific functionality that I use. I have converted this code to Java 1.6 with a series of if statements to replicate the switch statement. I could have used an enum, or refactored it to use objects but I wanted to keep the code simple. Hence the reason this code is different from what you might see in the lecture. But I have left this comment in to explain the situation. */ if("FIREFOX".contentEquals(defaultBrowser)) useThisDriver = BrowserName.FIREFOX; if("FIREFOXLEGACY".contentEquals(defaultBrowser)) useThisDriver = BrowserName.FIREFOXLEGACY; if("FIREFOXPORTABLE".contentEquals(defaultBrowser)) useThisDriver = BrowserName.FIREFOXPORTABLE; // Firefox is for the inbuilt plugin driver, marionette is the newer .exe driver // see the // package com.seleniumsimplified.webdriver.drivers; // FirefoxMarionetteDriverTest.java for more details if("FIREFOXMARIONETTE".contentEquals(defaultBrowser)) useThisDriver = BrowserName.FIREFOXMARIONETTE; if("CHROME".contentEquals(defaultBrowser)) useThisDriver = BrowserName.GOOGLECHROME; if("GOOGLECHROME".contentEquals(defaultBrowser)) useThisDriver = BrowserName.GOOGLECHROME; if("IE".contentEquals(defaultBrowser)) useThisDriver = BrowserName.IE; if("EDGE".contentEquals(defaultBrowser)) useThisDriver = BrowserName.EDGE; if("SAUCELABS".contentEquals(defaultBrowser)) useThisDriver = BrowserName.SAUCELABS; if("HTMLUNIT".contentEquals(defaultBrowser)) useThisDriver = BrowserName.HTMLUNIT; // generic grid if("GRID".contentEquals(defaultBrowser)) useThisDriver = BrowserName.GRID; if("APPIUM".contentEquals(defaultBrowser)) useThisDriver = BrowserName.APPIUM; // if none of the previous if statements were exercised then useThisDriver will // still be none, this is the 'default' line from the Switch statement. if(useThisDriver==null) throw new RuntimeException("Unknown Browser in " + BROWSER_PROPERTY_NAME + ": " + defaultBrowser); /* Code below requires Java 1.7 to switch on String * This would be my default way of writing the code, but have * not made it the default in this code base because people often compile * against 1.6 settings. */ /* switch (defaultBrowser){ case "FIREFOX": useThisDriver = BrowserName.FIREFOX; break; case "CHROME": useThisDriver = BrowserName.GOOGLECHROME; break; case "IE": useThisDriver = BrowserName.IE; break; case "SAUCELABS": useThisDriver = BrowserName.SAUCELABS; break; case "HTMLUNIT": useThisDriver = BrowserName.HTMLUNIT; break; case "GRID": useThisDriver = BrowserName.GRID; break; default: throw new RuntimeException("Unknown Browser in " + BROWSER_PROPERTY_NAME + ": " + defaultBrowser); } */ } if(aDriver==null){ long startBrowserTime = System.currentTimeMillis(); // see the \docs\firefox47.pdf for a discussion on why we have Firefox and FirefoxPortable etc. switch (useThisDriver) { case FIREFOX: FirefoxProfile profile = new FirefoxProfile(); profile.setEnableNativeEvents(true); /** Webdriver 3 **/ /* To use legacy Firefox driver we can set capability for Marionette to be false and it will use the legacy firefox driver FirefoxDriver.MARIONETTE == "marionette" */ DesiredCapabilities firefoxCapabilities = DesiredCapabilities.firefox(); //firefoxCapabilities.setCapability("marionette", false); setDriverPropertyIfNecessary("webdriver.gecko.driver", "/../tools/marionette/geckodriver.exe", "C://webdrivers/marionette/geckodriver.exe"); aDriver = new FirefoxDriver(firefoxCapabilities);//profile); /* NOTE: 20160729 this property doesn't seem to be honoured in the code yet so use the capability above. or I can run the test with a property -Dwebdriver.firefox.marionette=false I could set that in code with System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE, "false"); */ // currentDriver = BrowserName.FIREFOX; break; case FIREFOXLEGACY: // use the legacy selenium driver with the built in firefox DesiredCapabilities legacyCapabilities = DesiredCapabilities.firefox(); legacyCapabilities.setCapability("marionette", false); aDriver = new FirefoxDriver(legacyCapabilities); currentDriver = BrowserName.FIREFOX; break; case FIREFOXPORTABLE: setDriverPropertyIfNecessary("seleniumsimplified.firefoxportable", "/../tools/FirefoxPortable/FirefoxPortable.exe", "C://webdrivers/FirefoxPortable/FirefoxPortable.exe"); //System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE, "false"); // for WebDriver 3 compatibility I need to set the FirefoxDriver to use the legacy driver rather than marionette DesiredCapabilities portableCapabilities = DesiredCapabilities.firefox(); portableCapabilities.setCapability("marionette", false); portableCapabilities.setCapability("firefox_binary", new File(System.getProperty("seleniumsimplified.firefoxportable")).getAbsolutePath()); //aDriver = new FirefoxDriver( // new FirefoxBinary( // new File(System.getProperty("seleniumsimplified.firefoxportable"))), // new FirefoxProfile(), // portableCapabilities); aDriver = new FirefoxDriver(portableCapabilities); currentDriver = BrowserName.FIREFOX; break; case FIREFOXMARIONETTE: // prior to Selenium 3 this was wires.exe setDriverPropertyIfNecessary("webdriver.gecko.driver", "/../tools/marionette/geckodriver.exe", "C://webdrivers/marionette/geckodriver.exe"); aDriver = new MarionetteDriver();//profile); currentDriver = BrowserName.FIREFOXMARIONETTE; break; case HTMLUNIT: // HtmlUnitDriver added as a maven dependency - no paths required aDriver = new HtmlUnitDriver(true); // enable javascript currentDriver = BrowserName.HTMLUNIT; break; case IE: setDriverPropertyIfNecessary("webdriver.ie.driver", "/../tools/iedriver_32/IEDriverServer.exe", "C://webdrivers/iedriver_32/IEDriverServer.exe"); //setDriverPropertyIfNecessary("webdriver.ie.driver", "/../tools/iedriver_64/IEDriverServer.exe", "C://webdrivers/iedriver_64/IEDriverServer.exe"); aDriver = new InternetExplorerDriver(); currentDriver = BrowserName.IE; break; case EDGE: setDriverPropertyIfNecessary("webdriver.edge.driver", "/../tools/edgedriver/MicrosoftWebDriver.exe", "C://webdrivers/edgedriver/MicrosoftWebDriver.exe"); aDriver = new EdgeDriver(); currentDriver = BrowserName.EDGE; break; case GOOGLECHROME: setDriverPropertyIfNecessary("webdriver.chrome.driver","/../tools/chromedriver/chromedriver.exe","C://webdrivers/chromedriver/chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.addArguments("disable-plugins"); options.addArguments("disable-extensions"); // with Chrome v35 it now reports an error on --ignore-certificate-errors // so call with args "test-type" // https://code.google.com/p/chromedriver/issues/detail?id=799 options.addArguments("test-type"); DesiredCapabilities chromeCapabilities = DesiredCapabilities.chrome(); // http://stackoverflow.com/questions/26772793/org-openqa-selenium-unhandledalertexception-unexpected-alert-open //chromeCapabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE); // convert theoptions to capabilities chromeCapabilities.setCapability(ChromeOptions.CAPABILITY, options); aDriver = new ChromeDriver(chromeCapabilities); currentDriver = BrowserName.GOOGLECHROME; break; case SAUCELABS: DesiredCapabilities sauceCapabilities = DesiredCapabilities.firefox(); sauceCapabilities.setCapability("version", "5"); sauceCapabilities.setCapability("platform", Platform.XP); try { // add url to environment variables to avoid releasing with source String sauceURL = System.getenv("SAUCELABS_URL"); aDriver = new RemoteWebDriver( new URL(sauceURL), sauceCapabilities); } catch (MalformedURLException e) { e.printStackTrace(); } currentDriver = BrowserName.SAUCELABS; break; case APPIUM: // quick hack code to get appium running // only one env variable, your APPIUM_DEVICE_NAME // so amend code for your local version DesiredCapabilities appiumCapabilities = new DesiredCapabilities(); // the device name can be seen when you do "adb devices" appiumCapabilities.setCapability("deviceName", EnvironmentPropertyReader.getPropertyOrEnv("APPIUM_DEVICE_NAME", "")); appiumCapabilities.setCapability("platformName", Platform.ANDROID); appiumCapabilities.setCapability("app", EnvironmentPropertyReader.getPropertyOrEnv("APPIUM_BROWSER", "browser")); try { // add url to environment variables to avoid releasing with source String appiumURL = "http://127.0.0.1:4723/wd/hub"; aDriver = new RemoteWebDriver( new URL(appiumURL), appiumCapabilities); } catch (MalformedURLException e) { e.printStackTrace(); } currentDriver = BrowserName.APPIUM; break; case GRID: String gridBrowser = EnvironmentPropertyReader.getPropertyOrEnv("WEBDRIVER_GRID_BROWSER", "firefox"); String gridBrowserVersion = EnvironmentPropertyReader.getPropertyOrEnv("WEBDRIVER_GRID_BROWSER_VERSION", ""); String gridBrowserPlatform = EnvironmentPropertyReader.getPropertyOrEnv("WEBDRIVER_GRID_BROWSER_PLATFORM", ""); DesiredCapabilities gridCapabilities = new DesiredCapabilities(); gridCapabilities.setBrowserName(gridBrowser); if(gridBrowserVersion.length()>0) gridCapabilities.setVersion(gridBrowserVersion); if(gridBrowserPlatform.length()>0) gridCapabilities.setPlatform(Platform.fromString(gridBrowserPlatform)); // Allow adding any capability defined as an environment variable // extra environment capabilities start with "WEBDRIVER_GRID_CAP_X_" // e.g. WEBDRIVER_GRID_CAP_X_os_version XP // e.g. WEBDRIVER_GRID_CAP_X_browserstack.debug true Map<String, String> anyExtraCapabilities = System.getenv(); addAnyValidExtraCapabilityTo(gridCapabilities, anyExtraCapabilities.keySet()); // Now check properties for extra capabilities Properties anyExtraCapabilityProperties = System.getProperties(); addAnyValidExtraCapabilityTo(gridCapabilities, anyExtraCapabilityProperties.stringPropertyNames()); try { // add url to environment variables to avoid releasing with source String gridURL = EnvironmentPropertyReader.getPropertyOrEnv("WEBDRIVER_GRID_URL", "http://localhost:4444/wd/hub"); aDriver = new RemoteWebDriver(new URL(gridURL), gridCapabilities); } catch (MalformedURLException e) { e.printStackTrace(); } currentDriver = BrowserName.GRID; break; } long browserStartedTime = System.currentTimeMillis(); browserStartTime = browserStartedTime - startBrowserTime; // we want to shutdown the shared brower when the tests finish Runtime.getRuntime().addShutdownHook( new Thread(){ public void run(){ Driver.quit(); } } ); }else{ try{ // is browser still alive if(aDriver.getWindowHandle()!=null){ // assume it is still alive } }catch(Exception e){ if(avoidRecursiveCall){ // something has gone wrong as we have been here already throw new RuntimeException("something has gone wrong as we have been in Driver.get already"); } quit(); aDriver=null; avoidRecursiveCall = true; return get(); } savedTimecount += browserStartTime; System.out.println("Saved another " + browserStartTime + "ms : total saved " + savedTimecount + "ms"); } avoidRecursiveCall = false; return aDriver; } /* Initially, the tests didn't really run on Grid, and I have code in the tests, to handle workarounds on different browsers. But as I use grid more, my current approach of using currentDriver to code workarounds for specific browsers, doesn't work because I'll just get GRID when I want to know FIREFOX. So I added a method called currentBrowser to Driver which returns the Browser in use. I can still find out what currentDriver is with `Driver.currentDriver`. But if I want to know the browser, I should use `Driver.currentBrowser()` */ public static BrowserName currentBrowser(){ // TODO: handle marionette in grid if(currentDriver == Driver.BrowserName.GRID){ // get the current browser from the property or environment // if not set then default to firefox // make lowercase for consistent comparison String gridBrowser = EnvironmentPropertyReader.getPropertyOrEnv("WEBDRIVER_GRID_BROWSER", "firefox").toLowerCase(); if(gridBrowser.contains("firefox")){ return BrowserName.FIREFOX; } if(gridBrowser.contains("chrome")){ return BrowserName.GOOGLECHROME; } if(gridBrowser.contains("ie")){ return BrowserName.IE; } if(gridBrowser.contains("html")){ return BrowserName.HTMLUNIT; } } if(currentDriver == BrowserName.SAUCELABS){ // we hard coded sauce to use firefox return BrowserName.FIREFOX; } return currentDriver; } private static void addAnyValidExtraCapabilityTo(DesiredCapabilities gridCapabilities, Set<String> possibleCapabilityKeys) { String extraCapabilityPrefix = "WEBDRIVER_GRID_CAP_X_"; for(String capabilityName : possibleCapabilityKeys){ if(capabilityName.startsWith(extraCapabilityPrefix)){ String capabilityValue = EnvironmentPropertyReader.getPropertyOrEnv(capabilityName, ""); if(capabilityValue.length()>0){ String capability = capabilityName.replaceFirst(extraCapabilityPrefix,""); System.out.println("To Set Capability " + capability + " with value " + capabilityValue); gridCapabilities.setCapability(capability, capabilityValue); } } } } private static void setDriverPropertyIfNecessary(String propertyKey, String relativeToUserPath, String absolutePath) { // http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html if(!System.getProperties().containsKey(propertyKey)){ String currentDir = System.getProperty("user.dir"); String chromeDriverLocation = currentDir + relativeToUserPath; File driverExe = new File(chromeDriverLocation); if(driverExe.exists()){ System.setProperty(propertyKey, chromeDriverLocation); }else{ driverExe = new File(absolutePath); if(driverExe.exists()){ System.setProperty(propertyKey, absolutePath); }else{ // expect an error on the follow through when we try to use the driver // unless the user has it in their Path in which case WebDriver will use that } } } } public static WebDriver get(String aURL, boolean maximize){ get(); aDriver.get(aURL); if(maximize){ try{ aDriver.manage().window().maximize(); }catch(UnsupportedCommandException e){ System.out.println("Remote Driver does not support maximise"); }catch(WebDriverException e){ if(currentDriver == BrowserName.APPIUM){ System.out.println("Appium does not support maximise"); } } } return aDriver; } public static WebDriver get(String aURL){ return get(aURL,true); } public static void quit(){ if(aDriver!=null){ System.out.println("total time saved by reusing browsers " + savedTimecount + "ms"); try{ aDriver.quit(); aDriver=null; }catch(Exception e){ // I don't care about errors at this point } } } }
42.147005
190
0.58933
05ce024529468fafac94336f24114b1907b9e156
10,041
/********************************************************************* SOURNEXT CONFIDENTIAL Copyright (C) SOURNEXT Corporation *********************************************************************/ package com.reversecoder.library.customview.storehouse; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.HashMap; /** * @author Md. Rashadul Alam * *This class is for handling session. */ public class SessionManager { /** * Set string value into the shared preference. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param value the string value that will be stored into the shared * preference against the string key. */ public static void setStringSetting(Context context, String key, String value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sp.edit(); editor.putString(key, value); editor.commit(); } /** * Get string value from shared preference. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @return string the string value that is stored into the shared * preference against the string key. */ public static String getStringSetting(Context context, String key) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString(key, null); } /** * Get string value from shared preference if not found return * given default value. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param defaultValue the default string value that is returned if * any value is not stored into the shared preference. * @return string the string value that is stored into the shared * preference against the string key. */ public static String getStringSetting(Context context, String key, String defaultValue) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString(key, defaultValue); } /** * Set boolean value into the shared preference. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param value the boolean value that will be stored into the shared * preference against the string key. */ public static void setBooleanSetting(Context context, String key, boolean value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sp.edit(); editor.putBoolean(key, value); editor.commit(); } /** * Get boolean value from shared preference if not found return * given default value. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param defaultValue the default boolean value that is returned if * any value is not stored into the shared preference. * @return boolean the boolean value that is stored into the shared * preference against the string key. */ public static boolean getBooleanSetting(Context context, String key, boolean defaultValue) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getBoolean(key, defaultValue); } /** * Set integer value into the shared preference. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param value the integer value that will be stored into the shared * preference against the string key. */ public static void setIntegerSetting(Context context, String key, int value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sp.edit(); editor.putInt(key, value); editor.commit(); } /** * Get integer value from shared preference if not found return * given default value. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param defaultValue the default integer value that is returned if * any value is not stored into the shared preference. * @return integer the string value that is stored into the shared * preference against the string key. */ public static int getIntegerSetting(Context context, String key, int defaultValue) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getInt(key, defaultValue); } /** * Set long value into the shared preference. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param value the long value that will be stored into the shared * preference against the string key. */ public static void setLongSetting(Context context, String key, long value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sp.edit(); editor.putLong(key, value); editor.commit(); } /** * Get long value from shared preference if not found return * given default value. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param defaultValue the default long value that is returned if * any value is not stored into the shared preference. * @return long the long value that is stored into the shared * preference against the string key. */ public static long getLongSetting(Context context, String key, long defaultValue) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getLong(key, defaultValue); } /** * Set float value into the shared preference. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param value the float value that will be stored into the shared * preference against the string key. */ public static void setFloatSetting(Context context, String key, float value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sp.edit(); editor.putFloat(key, value); editor.commit(); } /** * Get float value from shared preference if not found return * given default value. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param defaultValue the default float value that is returned if * any value is not stored into the shared preference. * @return float the float value that is stored into the shared * preference against the string key. */ public static float getFloatSetting(Context context, String key, float defValue) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getFloat(key, defValue); } /** * Set HashMap value into the shared preference. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @param value the HashMap value that will be stored into the shared * preference against the string key. */ public static void setHashMapSetting(Context context, String key, HashMap value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sp.edit(); Gson gson = new Gson(); String json = gson.toJson(value); editor.putString(key, json); editor.commit(); } /** * Get HashMap value from shared preference if not found return * given default value. * * @param context the context of the activity or application itself. * @param key the string key of shared preference. * @return HashMap the HashMap value that is stored into the shared * preference against the string key. */ public static HashMap getHashMapSetting(Context context, String key) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Gson gson = new Gson(); String json = sp.getString(key, ""); java.lang.reflect.Type type = new TypeToken<HashMap>() { }.getType(); return gson.fromJson(json, type); } /** * remove item from shared preference * * @param context the context of the activity or application itself. * @param key the string key of the shared preference. */ public static void removeSetting(Context context, String key) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sp.edit(); editor.remove(key); editor.commit(); } /** *Get boolean value about the key is exist or not. * * @param context the context of the activity or application itself. * @param key the string key of the shared preference. * @return boolean the boolean value of key's existence. */ public static boolean isExistKey(Context context, String key) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.contains(key); } }
38.918605
96
0.678219
1308db5d0e41646cf5ee1c0fb68de4b586543d20
4,178
package es.uned.peda; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * The Class IOData. */ public class IOData { /** The number of objects. */ private int numberOfObjects; /** The knapsack volume. */ private int knapsackVolume; /** The values. */ private double[] values; /** The volumes. */ private int[] volumes; /** * Read input. * * @param inputFile * the input file * @return the problem data */ public ProblemData readInput(String inputFile) { final Path inputPath = Paths.get(inputFile); if (!Files.exists(inputPath)) { throw new IllegalArgumentException("Input file does not exist"); } try (BufferedReader br = Files.newBufferedReader(inputPath)) { int lineNumber = 1; numberOfObjects = readInteger(br.readLine(), lineNumber++); values = new double[numberOfObjects]; volumes = new int[numberOfObjects]; for (int i = 0; i < numberOfObjects; i++) { readObject(br.readLine(), lineNumber++); } knapsackVolume = readInteger(br.readLine(), lineNumber++); checkEOF(br.readLine()); return new ProblemData(values, volumes, numberOfObjects, knapsackVolume); } catch (final Exception e) { throw new RuntimeException(e); } } /** * Check EOF. * * @param line * the line */ private void checkEOF(String line) { if (line != null) { throw new IllegalArgumentException("Invalid number of lines in file"); } } /** * Read and store object volume and value. * * @param line * the line * @param lineNumber * the line number */ private void readObject(String line, int lineNumber) { if (line == null) { throw new IllegalArgumentException( "Error reading arguments. " + (numberOfObjects - lineNumber + 1) + " more elements were expected"); } final String[] arr = line.split(" +"); if (arr.length != 2) { throw new IllegalArgumentException( "Error reading argument. Line " + lineNumber + " contains an invalid number of arguments"); } final int idx = lineNumber - 2; volumes[idx] = readInteger(arr[0], lineNumber); values[idx] = readDouble(arr[1], lineNumber); } /** * Read double. * * @param line * the line * @param lineNumber * the line number * @return the double */ private double readDouble(String line, int lineNumber) { final double n; try { n = Double.parseDouble(line); } catch (final Exception e) { throw new IllegalArgumentException("Error reading value (floating point number) in line " + lineNumber); } if (n <= 0.0) { throw new IllegalArgumentException("Value should be greater than zero (line " + lineNumber + ")"); } return n; } /** * Read integer. * * @param line * the line * @param lineNumber * the line number * @return the int */ private int readInteger(String line, int lineNumber) { final int n; try { n = Integer.parseInt(line.trim()); } catch (final Exception e) { throw new RuntimeException("Error reading volume (integer number) in line " + lineNumber); } if (n < 1) { if (lineNumber == 1) { throw new IllegalArgumentException( "Number of objects must be greater than zero (line " + lineNumber + ")"); } else if (lineNumber == (numberOfObjects + 2)) { throw new IllegalArgumentException("Total volume must be greater than zero (line " + lineNumber + ")"); } else { throw new IllegalArgumentException( "Object's volume must be greater than zero (line " + lineNumber + ")"); } } return n; } /** * Gets the output. * * @param outputFile * the output file * @return the output */ public PrintStream getOutput(String outputFile) { final Path outputPath = Paths.get(outputFile); if (Files.exists(outputPath)) { throw new IllegalArgumentException("Output file already exists"); } try { return new PrintStream(Files.newOutputStream(outputPath)); } catch (final IOException e) { throw new RuntimeException(e); } } }
22.583784
107
0.645045
4fd7d005db0d1c280ac6dfdd2a2a5f93bc6ca6b0
227
package ru.r2cloud.fcdw; public class AuthenticationException extends Exception { private static final long serialVersionUID = 6812784411157195284L; public AuthenticationException(String message) { super(message); } }
18.916667
67
0.801762
a1732d76ad66493c32cf9cb44323054573819f01
80
package com.javadude.factories.cars; public class Camry implements Sedan { }
11.428571
37
0.775
eaac1e9b5e3f9cd8552d4b8a2a9907af63dea1b4
950
package cn.javastack; public class PublicVar { public String username = "A"; public String password = "AA"; //同步实例方法 public void setValue(String username, String password) { try { this.username = username; Thread.sleep(5000); this.password = password; System.out.println("method=setValue " +"\t" + "threadName=" + Thread.currentThread().getName() + "\t" + "username=" + username + ", password=" + password); } catch (InterruptedException e) { e.printStackTrace(); } } //非同步实例方法 public void getValue() { System.out.println("method=getValue " + "\t" + "threadName=" + Thread.currentThread().getName()+ "\t" + " username=" + username + ", password=" + password); } }
32.758621
86
0.482105
88f82cb123896440f6ee8d58d7e0bd7e4cfaca8f
3,153
package ca.bc.gov.educ.api.pen.trax.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; import java.math.BigDecimal; /** * The type Provincially examinable course entity. */ @Data @Builder @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "PROV_EXAM") public class ProvExamEntity { @EmbeddedId private ProvExamId provExamId; @Column(name = "PRED_LG") private String predLg; @Column(name = "PROV_IB_FLAG") private String provIbFlag; @Column(name = "ADJUD_FLAG") private String adjudFlag; @Column(name = "PREPRINT_FLAG") private String preprintFlag; @Column(name = "WROTE_FLAG") private String wroteFlag; @Column(name = "PROV_SCHOOL_PCT") private Long provSchoolPct; @Column(name = "PROV_SPEC_CASE") private String provSpecCase; @Column(name = "RAW_SCORE", precision = 4, scale = 1) private BigDecimal rawScore; @Column(name = "PROV_EXAM_PCT") private Long provExamPct; @Column(name = "PROV_FINAL_PCT") private Long provFinalPct; @Column(name = "FINAL_LG") private String finalLg; @Column(name = "LOCAL_CRSE_ID") private String localCrseId; @Column(name = "LOCAL_CRSE_PER") private String localCrsePer; @Column(name = "LOCAL_CRSE_SEC") private String localCrseSec; @Column(name = "LOCAL_CRSE_SEM") private String localCrseSem; @Column(name = "MINCODE_EXAM") private String mincodeExam; @Column(name = "BEST_SCHOOL_PCT") private Long bestSchoolPct; @Column(name = "BEST_EXAM_PCT") private Long bestExamPct; @Column(name = "MINCODE_HOME") private String mincodeHome; @Column(name = "PRED_PCT") private Long predPct; @Column(name = "NUM_CREDITS") private Long numCredits; @Column(name = "STUDY_TYPE") private String studyType; @Column(name = "USED_FOR_GRAD") private String usedForGrad; @Column(name = "CRSE_TYPE") private String crseType; @Column(name = "FND_CREDITS") private String fndCredits; @Column(name = "SCHOL_SMS") private Long scholSms; @Column(name = "SCHOL_SPEC_CASE") private String scholSpecCase; @Column(name = "BEST_EXAM_SESSION") private String bestExamSession; @Column(name = "E_FILE_DELETE_FLAG") private String eFileDeleteFlag; @Column(name = "PROV_PREBUMP_FINAL_PCT") private Long provPrebumpFinalPct; @Column(name = "FORM_CODE") private String formCode; @Column(name = "MC_TOTAL", precision = 4, scale = 1) private BigDecimal mcTotal; @Column(name = "OE_TOTAL", precision = 4, scale = 1) private BigDecimal oeTotal; @Column(name = "IRT_SCORE", precision = 9, scale = 4) private BigDecimal irtScore; @Column(name = "EXAM_SOURCE_CODE") private String examSourceCode; @Column(name = "TO_WRITE_FLAG") private String toWriteFlag; @Column(name = "EXAM_PRINT_CODE") private String examPrintCode; @Column(name = "BLEND_OPTIONAL") private String blendOptional; @Column(name = "MET_LIT_NUM_REQT") private String metLitNumReqt; }
21.744828
55
0.730098
8e3e7f1b28685b9e6839988647c364589d55f9a0
10,060
package com.ferreusveritas.dynamictrees.api; import java.util.List; import com.ferreusveritas.dynamictrees.ModConstants; import com.ferreusveritas.dynamictrees.api.cells.ICellKit; import com.ferreusveritas.dynamictrees.api.treedata.ILeavesProperties; import com.ferreusveritas.dynamictrees.blocks.BlockDynamicLeaves; import com.ferreusveritas.dynamictrees.blocks.BlockDynamicSapling; import com.ferreusveritas.dynamictrees.blocks.LeavesProperties; import com.ferreusveritas.dynamictrees.trees.TreeFamily; import com.ferreusveritas.dynamictrees.trees.Species; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; /** * A {@link TreeFamily} builder class to ease in the creation of new trees for other mods. * * * @author ferreusveritas * */ public class TreeBuilder { private ResourceLocation name; private int seqNum = -1; //Drops private IBlockState primitiveLeavesBlockState = Blocks.LEAVES.getDefaultState(); private IBlockState primitiveLogBlockState = Blocks.LOG.getDefaultState(); private ItemStack stickItemStack; //Leaves private ILeavesProperties dynamicLeavesProperties; private int dynamicLeavesSmotherMax = 4; private int dynamicLeavesLightRequirement = 13; private ResourceLocation dynamicLeavesCellKit; //Common Species private ISpeciesCreator speciesCreator; private IBlockState speciesSaplingBlockState; private Block speciesSaplingBlock; private boolean speciesCreateSeed = true; private boolean speciesCreateSapling = true; /** * Name your tree and give me that name. * * REQUIRED * * Each tree is given a unique name per mod. We use a {@link ResourceLocation} to get the * job done as it contains the ModId and the Name of the object. * * @param name A unique {@link ResourceLocation} giving the tree a simple name. * @return TreeBuilder for chaining */ public TreeBuilder setName(ResourceLocation name) { this.name = name; return this; } //Convenience function for the above member public TreeBuilder setName(String domain, String path) { return setName(new ResourceLocation(domain, path)); } /** * Serially number your trees and give me that number. * * REQUIRED(if not using mutually exclusive member setDynamicLeaves(...)) * * Each {@link BlockDynamicLeaves} can handle 4 different trees by using metadata. It's the mod authors * responsibility to assign and maintain an ordered set of numbers that each represent a tree. The sequence * should start from 0 for each Mod and incremented for each {@link TreeFamily} that the mod creates. Gaps in * the numbered list are okay(if a tree is removed for instance), duplicates will result in undefined behavior. * DynamicTrees internally maintains a mapping of {@link BlockDynamicLeaves} for each mod. This is done to * reduce the number of registered blocks. * * @param seqNum The registration sequence number for this MODID. Used for registering 4 leaves types per {@link BlockDynamicLeaves}. * @return TreeBuilder for chaining */ public TreeBuilder setDynamicLeavesSequence(int seqNum) { if(dynamicLeavesProperties == null) { this.seqNum = seqNum; } return this; } /** * Set a custom {@link BlockDynamicLeaves} * * REQUIRED(if not using mutually exclusive member setDynamicLeavesSequence(...)) * * @param leaves The {@link BlockDynamicLeaves} to set for this tree * @param subBlockNum The number used to select the correct subblock of the {@link BlockDynamicLeaves} (typically 0-3 for a standard {@link BlockDynamicLeaves}) * @return */ public TreeBuilder setDynamicLeavesProperties(ILeavesProperties leavesProperties) { this.seqNum = -1; dynamicLeavesProperties = leavesProperties; return this; } /** * RECOMMENDED * * If not defined the default leaves will be plain Vanilla oak leaves and that's what will drop when sheared. * * @param primLeaves The primitive leaves which are used for many purposes including drops, branch reinforcing and some other basic behavior. * @return TreeBuilder for chaining */ public TreeBuilder setPrimitiveLeaves(IBlockState primLeaves) { primitiveLeavesBlockState = primLeaves; return this; } /** * RECOMMENDED * * If not defined the default log will be plain Vanilla oak log and that's what will drop when harvested. * * @param primLog The primitive(vanilla) log to base the drops, and other behavior from * @param primLogStack The cached ItemStack of primitive logs(what is returned when wood is harvested) * @return TreeBuilder for chaining */ public TreeBuilder setPrimitiveLog(IBlockState primLog) { primitiveLogBlockState = primLog; return this; } /** * OPTIONAL * * Generally this is not used. Some mods have custom sticks like iron sticks and this is for them. * * @param stick The sticks to drop when there's not enough harvested material to produce another whole log. * @return TreeBuilder for chaining */ public TreeBuilder setStick(ItemStack stick) { this.stickItemStack = stick; return this; } /** * OPTIONAL * * @param smotherMax The maximum amount of leaves in a stack before the bottom-most leaf block dies [default = 4] * @return TreeBuilder for chaining */ public TreeBuilder setSmotherLeavesMax(int smotherMax) { dynamicLeavesSmotherMax = smotherMax; return this; } /** * OPTIONAL * * @param light The minimum amount of light necessary for a leaves block to be created. * @return TreeBuilder for chaining */ public TreeBuilder setLightRequirement(int light) { dynamicLeavesLightRequirement = light; return this; } /** * OPTIONAL * * Sets the cellular automata kit to use for the {@link BlockDynamicLeaves} for this * {@link TreeFamily} * * A CellKit contains all the algorithms and data to make a leaves grow a certain way. * * @param kit The Cell Kit to use. * @return TreeBuilder for chaining */ public TreeBuilder setCellKit(ResourceLocation kit) { dynamicLeavesCellKit = kit; return this; } /** * OPTIONAL * * Provides a way to inject a custom common species. If this is not used * a default Species will be created for you. * * @param speciesCreator * @return TreeBuilder for chaining */ public TreeBuilder setCommonSpecies(ISpeciesCreator speciesCreator) { this.speciesCreator = speciesCreator; return this; } /** * OPTIONAL * * @param state A blockState that will turn into the common species of this tree * @return TreeBuilder for chaining */ public TreeBuilder setCommonSpeciesDynamicSapling(IBlockState state) { speciesCreateSapling = false; speciesSaplingBlockState = state; return this; } /** * OPTIONAL * * Can be used to turn off automatic seed creation. * When enabled a seed will automatically be created and * a standard seed dropper will be added to the common * species. * * @param isStandard true to enable automatic seed creation(default), false to disable * @return TreeBuilder for chaining */ public TreeBuilder setCreateSeed(boolean isStandard) { speciesCreateSeed = isStandard; return this; } /** * OPTIONAL * * Can be used to turn off automatic dynamic sapling creation. * * @param doCreate true to enable automatic sapling creation(default), false to disable * @return TreeBuilder for chaining */ public TreeBuilder setCreateSapling(boolean doCreate) { speciesCreateSapling = doCreate && speciesSaplingBlockState == null; return this; } /** * Builds a {@link TreeFamily} according to the specs provided. Called last in the builder chain. * Repeated calls can be made but be sure to change the Name and Sequence for the tree before * creating multiple trees. * * @return The newly built {@link TreeFamily} */ public TreeFamily build() { if(name == null) { System.err.println("Error: Attempted to build an nameless tree"); return null; } if(seqNum == -1 && dynamicLeavesProperties == null) { System.err.println("Error: Attempted to build an unsequenced tree(or a tree without dynamic leaves properties)"); return null; } TreeFamily treeFamily = new TreeFamily(name) { { if(dynamicLeavesProperties == null) { dynamicLeavesProperties = new LeavesProperties(primitiveLeavesBlockState) { @Override public int getLightRequirement() { return dynamicLeavesLightRequirement; } public int getSmotherLeavesMax() { return dynamicLeavesSmotherMax; }; @Override public ICellKit getCellKit() { return TreeRegistry.findCellKit(dynamicLeavesCellKit); } }; TreeHelper.getLeavesBlockForSequence(ModConstants.MODID, seqNum, dynamicLeavesProperties); } this.setPrimitiveLog(primitiveLogBlockState); dynamicLeavesProperties.setTree(this); if(stickItemStack != null) { setStick(stickItemStack); } } @Override public void createSpecies() { setCommonSpecies(speciesCreator != null ? speciesCreator.create(this) : new Species(name, this, dynamicLeavesProperties)); if(speciesCreateSeed) { getCommonSpecies().generateSeed(); getCommonSpecies().setupStandardSeedDropping(); } if(speciesCreateSapling) { speciesSaplingBlock = new BlockDynamicSapling(name.getResourcePath() + "sapling"); speciesSaplingBlockState = speciesSaplingBlock.getDefaultState(); } if(speciesSaplingBlockState != null) { getCommonSpecies().setDynamicSapling(speciesSaplingBlockState); } } @Override public List<Block> getRegisterableBlocks(List<Block> blockList) { if(speciesCreateSapling) { blockList.add(speciesSaplingBlock); } return super.getRegisterableBlocks(blockList); } }; return treeFamily; } public interface ISpeciesCreator { Species create(TreeFamily tree); } }
30.029851
161
0.732505
8dc86e9c8fe1444c3b4d3104e440a200c52d5514
896
package cn.dyaoming.outman.dubbo.constrollers; import cn.dyaoming.outman.dubbo.servers.UserServer; import cn.dyaoming.outman.dubbo.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserServer userServer; @Autowired private UserService hessianService; @RequestMapping("/getName") public String getName(String code) { return userServer.getName(code); } @RequestMapping("/sayHello") public String sayHello(String name) { return userServer.sayHello(name); } @RequestMapping("/getName2") public String getName2(String code) { return hessianService.sayHello(code); } }
27.151515
62
0.747768
8ab71af8d2b2c3ec8500a790a10c64199fad50f3
824
package com.regitiny.catiny.advance.service.mapper; import com.regitiny.catiny.advance.controller.model.HanhChinhVNModel; import com.regitiny.catiny.domain.HanhChinhVN; import com.regitiny.catiny.service.dto.HanhChinhVNDTO; import com.regitiny.catiny.service.mapper.EntityMapper; import org.mapstruct.Mapper; import java.util.List; @Mapper( componentModel = "spring", uses = {} ) public interface HanhChinhVNAdvanceMapper extends EntityAdvanceMapper<HanhChinhVNModel, HanhChinhVNDTO>, EntityMapper<HanhChinhVNDTO, HanhChinhVN> { HanhChinhVNDTO requestToDto(HanhChinhVNModel.Request request); List<HanhChinhVNDTO> requestToDto(List<HanhChinhVNModel.Request> request); HanhChinhVNModel.Response dtoToResponse(HanhChinhVNDTO dto); List<HanhChinhVNModel.Response> dtoToResponse(List<HanhChinhVNDTO> dto); }
29.428571
146
0.825243
03772a8616ff1d89bf62d75f0f69d4485b126773
1,664
package com.xms.structure.graph; import java.util.Arrays; /** * Created by xms on 2017/8/19. */ public class DijKatra { public static int M = Integer.MAX_VALUE; public int MAXNUM = 10; int[] dist = new int[MAXNUM]; int[] prev = new int[MAXNUM]; public static int[][] G = { /********A B C D E F ********/ /* A */{ 0, 6, 3, M, M, M }, /* B */{ 6, 0, 2, 5, M, M }, /* C */{ 3, 2, 0, 3, 4, M }, /* D */{ M, 5, 3, 0, 2, 3 }, /* E */{ M, M, 4, 2, 0, 5 }, /* F */{ M, M, M, 3, 5, 0 } }; static char[] sets = {'A','B','C','D','E','F'}; public static void DijDatra(int[][] G, int v0) { int n = G[0].length; boolean[] S = new boolean[n]; int[] dist = new int[n]; int[] prev = new int[n]; for (int i = 0; i < n; i++) { dist[i] = G[v0][i]; S[i] = false; if (dist[i] == Integer.MAX_VALUE) { prev[i] = -1; } else { prev[i] = v0; } } dist[v0] = 0; S[v0] = true; for (int i = 1; i < n; i++) { int mindist = Integer.MAX_VALUE; int u = v0; for (int j = 0; j <n; ++j) if ((!S[j]) && dist[j] < mindist) { u = j; mindist = dist[j]; } S[u] = true; for (int j = 0; j <n; j++) if ((!S[j]) && G[u][j] < Integer.MAX_VALUE) { if (dist[u] + G[u][j] < dist[j]) { dist[j] = dist[u] + G[u][j]; prev[j] = u; } } } System.out.println(Arrays.toString(dist)); String str =""; // print(5,prev,str); } private static void print(int i,int[] prev,String s) { if(i==0){ s=sets[i]+s; System.out.print(s); } else{ s=sets[i]+s; print(prev[i],prev,s); } } public static void main(String[] args) { DijDatra(G,1); } }
21.063291
55
0.466947
316aece670b7f364c05331e059ff3ec9a71bbd71
1,379
package com.ara.network.download; /** * Created by XieXin on 2021/12/1. * 下载管理 */ public class DownloadInfo { /** * 下载状态 */ public static final String DOWNLOAD = "download"; public static final String DOWNLOAD_PAUSE = "pause"; public static final String DOWNLOAD_CANCEL = "cancel"; public static final String DOWNLOAD_OVER = "over"; public static final String DOWNLOAD_ERROR = "error"; public static final long TOTAL_ERROR = -1;//获取进度失败 private final String url; private String fileName; private String downloadStatus; private long total; private long progress; public DownloadInfo(String url) { this.url = url; } public String getUrl() { return url; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public long getProgress() { return progress; } public void setProgress(long progress) { this.progress = progress; } public String getDownloadStatus() { return downloadStatus; } public void setDownloadStatus(String downloadStatus) { this.downloadStatus = downloadStatus; } }
21.215385
58
0.634518
6a5afc82abfb02ab0bc6d590bdd6df4179d3d1ea
508
package com.binarskugga.skugga.api.annotation; import com.binarskugga.skugga.api.enums.InclusionMode; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface UpdateField { // Defaults to the updatable value of the entity. String[] roles() default {"*"}; InclusionMode inclusion() default InclusionMode.INCLUDE; }
25.4
57
0.80315
922074ba7c9ce626417ba0515f0a895cb470a652
56,077
package io.smallrye.reactive.messaging.amqp; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.awaitility.Awaitility.await; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.apache.qpid.proton.amqp.Binary; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.messaging.Accepted; import org.apache.qpid.proton.amqp.messaging.AmqpValue; import org.apache.qpid.proton.amqp.messaging.Data; import org.apache.qpid.proton.amqp.messaging.Section; import org.apache.qpid.proton.amqp.transport.Target; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.spi.ConnectorFactory; import org.eclipse.microprofile.reactive.streams.operators.SubscriberBuilder; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.reactivestreams.Subscriber; import io.smallrye.config.SmallRyeConfigProviderResolver; import io.smallrye.mutiny.Multi; import io.smallrye.reactive.messaging.test.common.config.MapBasedConfig; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.mutiny.core.buffer.Buffer; public class AmqpSinkTest extends AmqpTestBase { private static final String FOO = "foo"; private static final String ID = "id"; private static final String HELLO = "hello-"; private WeldContainer container; private AmqpConnector provider; private MockServer server; @AfterEach public void cleanup() { if (provider != null) { provider.terminate(null); } if (container != null) { container.shutdown(); } if (server != null) { server.close(); } MapBasedConfig.cleanup(); SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig()); } @Test @Timeout(30) public void testSinkUsingIntegerUsingDefaultAnonymousSender() throws Exception { int msgCount = 10; String topic = UUID.randomUUID().toString(); CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); AtomicReference<String> attachAddress = new AtomicReference<>("non-null-initialisation-value"); server = setupMockServerForTypeTest(messagesReceived, msgsReceived, attachAddress); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(topic, server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, msgCount) .map(Message::of) .subscribe((Subscriber<? super Message<Integer>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); List<Object> payloadsReceived = new ArrayList<>(msgCount); messagesReceived.forEach(msg -> { Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); payloadsReceived.add(((AmqpValue) body).getValue()); }); assertThat(payloadsReceived).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // Should have used an anonymous sender link, verify null target address assertThat(attachAddress.get()).isNull(); } @Test @Timeout(30) public void testSinkUsingIntegerUsingNonAnonymousSender() throws Exception { int msgCount = 10; String topic = UUID.randomUUID().toString(); CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); AtomicReference<String> attachAddress = new AtomicReference<>("non-null-initialisation-value"); server = setupMockServerForTypeTest(messagesReceived, msgsReceived, attachAddress); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndNonAnonymousSink(topic, server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(Message::of) .subscribe((Subscriber<? super Message<Integer>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); List<Object> payloadsReceived = new ArrayList<>(msgCount); messagesReceived.forEach(msg -> { Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); payloadsReceived.add(((AmqpValue) body).getValue()); }); assertThat(payloadsReceived).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // Should have used a fixed-address sender link, vertify target address assertThat(attachAddress.get()).isEqualTo(topic); } @Test @Timeout(30) public void testSinkUsingString() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndNonAnonymousSink( UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(i -> Integer.toString(i)) .map(Message::of) .subscribe((Subscriber<? super Message<String>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); List<Object> payloadsReceived = new ArrayList<>(msgCount); messagesReceived.forEach(msg -> { Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); payloadsReceived.add(((AmqpValue) body).getValue()); }); assertThat(payloadsReceived).containsExactly("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); } private MockServer setupMockServerForTypeTest(List<org.apache.qpid.proton.message.Message> messages, CountDownLatch latch) throws Exception { //noinspection Convert2Diamond return setupMockServerForTypeTest(messages, latch, new AtomicReference<String>()); } private MockServer setupMockServerForTypeTest(List<org.apache.qpid.proton.message.Message> messages, CountDownLatch latch, AtomicReference<String> attachAddress) throws Exception { return new MockServer(executionHolder.vertx().getDelegate(), serverConnection -> { serverConnection.openHandler(serverSender -> { serverConnection.closeHandler(x -> serverConnection.close()); serverConnection.open(); }); serverConnection.sessionOpenHandler(serverSession -> { serverSession.closeHandler(x -> serverSession.close()); serverSession.open(); }); serverConnection.receiverOpenHandler(serverReceiver -> { Target remoteTarget = serverReceiver.getRemoteTarget(); attachAddress.set(remoteTarget.getAddress()); serverReceiver.setTarget(remoteTarget.copy()); serverReceiver.handler((delivery, message) -> { delivery.disposition(Accepted.getInstance(), true); messages.add(message); latch.countDown(); }); serverReceiver.open(); }); }); } static class Person { String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } @Test @Timeout(30) public void testSinkUsingObject() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(i -> { Person p = new Person(); p.setName(HELLO + i); return p; }) .map(Message::of) .subscribe((Subscriber<? super Message<Person>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("application/json"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); Binary bin = ((Data) body).getValue(); byte[] bytes = Binary.copy(bin).getArray(); Person p = Buffer.buffer(bytes).toJsonObject().mapTo(Person.class); assertThat(p.getName()).isEqualTo(HELLO + count.get()); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } /** * Extension of Person that cannot be serialized to JSON. */ @SuppressWarnings("unused") public static class Bad extends Person { public Person getPerson() { return this; } } @Test @Timeout(30) public void testSinkUsingObjectThatCannotBeSerialized() throws Exception { int msgCount = 10; AtomicInteger nack = new AtomicInteger(); CountDownLatch msgsReceived = new CountDownLatch(msgCount / 2); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(i -> { Person p; if (i % 2 == 0) { p = new Person(); p.setName(HELLO + i); } else { p = new Bad(); p.setName(HELLO + i); } return p; }) .map(p -> Message.of(p, () -> CompletableFuture.completedFuture(null), e -> { nack.incrementAndGet(); return CompletableFuture.completedFuture(null); })) .subscribe((Subscriber<? super Message<Person>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); await().until(() -> nack.get() == 5); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("application/json"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); Binary bin = ((Data) body).getValue(); byte[] bytes = Binary.copy(bin).getArray(); JsonObject json = Buffer.buffer(bytes).toJsonObject(); Person p = json.mapTo(Person.class); assertThat(p.getName()).startsWith("hello-"); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount / 2); assertThat(nack).hasValue(5); } @Test @Timeout(30) public void testSinkUsingJsonObject() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(i -> new JsonObject().put(ID, HELLO + i)) .map(Message::of) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("application/json"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); Binary bin = ((Data) body).getValue(); byte[] bytes = Binary.copy(bin).getArray(); JsonObject json = Buffer.buffer(bytes).toJsonObject(); assertThat(json.getString(ID)).isEqualTo(HELLO + count.get()); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) public void testSinkUsingJsonArray() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(i -> new JsonArray().add(HELLO + i).add(FOO)) .map(Message::of) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("application/json"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); Binary bin = ((Data) body).getValue(); byte[] bytes = Binary.copy(bin).getArray(); JsonArray json = Buffer.buffer(bytes).toJsonArray(); assertThat(json.getString(0)).isEqualTo(HELLO + count.get()); assertThat(json.getString(1)).isEqualTo(FOO); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) public void testSinkUsingList() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(i -> { List<String> res = new ArrayList<>(); res.add(HELLO + i); res.add(FOO); return res; }) .map(Message::of) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isNull(); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); assertThat(((AmqpValue) body).getValue()).isInstanceOf(List.class); List<?> list = (List<?>) ((AmqpValue) body).getValue(); assertThat(list.get(0)).isEqualTo(HELLO + count.get()); assertThat(list.get(1)).isEqualTo(FOO); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) public void testSinkUsingVertxBuffer() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(i -> new JsonObject().put(ID, HELLO + i).toBuffer()) .map(Message::of) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("application/octet-stream"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); byte[] receievedBytes = Binary.copy(((Data) body).getValue()).getArray(); byte[] expectedBytes = new JsonObject().put(ID, HELLO + count.get()).toBuffer().getBytes(); assertThat(receievedBytes).isEqualTo(expectedBytes); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) public void testSinkUsingMutinyBuffer() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(i -> new Buffer(new JsonObject().put(ID, HELLO + i).toBuffer())) .map(Message::of) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("application/octet-stream"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); byte[] receievedBytes = Binary.copy(((Data) body).getValue()).getArray(); byte[] expectedBytes = new JsonObject().put(ID, HELLO + count.get()).toBuffer().getBytes(); assertThat(receievedBytes).isEqualTo(expectedBytes); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) public void testSinkUsingByteArray() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(i -> new JsonObject().put(ID, HELLO + i).toBuffer().getBytes()) .map(Message::of) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("application/octet-stream"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); byte[] receievedBytes = Binary.copy(((Data) body).getValue()).getArray(); byte[] expectedBytes = new JsonObject().put(ID, HELLO + count.get()).toBuffer().getBytes(); assertThat(receievedBytes).isEqualTo(expectedBytes); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) public void testABeanProducingMessagesSentToAMQP() throws Exception { int msgCount = 10; String address = "sink"; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); AtomicReference<String> attachAddress = new AtomicReference<>("non-null-initialisation-value"); server = setupMockServerForTypeTest(messagesReceived, msgsReceived, attachAddress); Weld weld = new Weld(); weld.addBeanClass(ProducingBean.class); new MapBasedConfig() .with("mp.messaging.outgoing.sink.address", address) .with("mp.messaging.outgoing.sink.connector", AmqpConnector.CONNECTOR_NAME) .with("mp.messaging.outgoing.sink.host", "localhost") .with("mp.messaging.outgoing.sink.port", server.actualPort()) .with("mp.messaging.outgoing.sink.tracing-enabled", false) .write(); container = weld.initialize(); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); List<Object> payloadsReceived = new ArrayList<>(msgCount); messagesReceived.forEach(msg -> { assertThat(msg.getAddress()).isEqualTo(address); assertThat(msg.getSubject()).isNull(); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); payloadsReceived.add(((AmqpValue) body).getValue()); }); assertThat(payloadsReceived).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Should have used an anonymous sender link, verify null target address assertThat(attachAddress.get()).isNull(); } @Test @Timeout(30) public void testABeanProducingMessagesSentToAMQPWithOutboundMetadata() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); AtomicReference<String> attachAddress = new AtomicReference<>("non-null-initialisation-value"); server = setupMockServerForTypeTest(messagesReceived, msgsReceived, attachAddress); Weld weld = new Weld(); weld.addBeanClass(ProducingBeanUsingOutboundMetadata.class); new MapBasedConfig() .with("mp.messaging.outgoing.sink.address", "not-used") .with("mp.messaging.outgoing.sink.connector", AmqpConnector.CONNECTOR_NAME) .with("mp.messaging.outgoing.sink.host", "localhost") .with("mp.messaging.outgoing.sink.port", server.actualPort()) .with("mp.messaging.outgoing.sink.tracing-enabled", false) .write(); container = weld.initialize(); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); List<Object> payloadsReceived = new ArrayList<>(msgCount); messagesReceived.forEach(msg -> { assertThat(msg.getAddress()).isEqualTo("metadata-address"); // Set in ProducingBeanUsingOutboundMetadata assertThat(msg.getSubject()).isEqualTo("metadata-subject"); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); payloadsReceived.add(((AmqpValue) body).getValue()); }); assertThat(payloadsReceived).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Should have used an anonymous sender link, verify null target address assertThat(attachAddress.get()).isNull(); } @Test @Timeout(30) public void testABeanProducingMessagesSentToAMQPWithOutboundMetadataUsingNonAnonymousSender() throws Exception { int msgCount = 10; String address = "sink-foo"; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); AtomicReference<String> attachAddress = new AtomicReference<>("non-null-initialisation-value"); server = setupMockServerForTypeTest(messagesReceived, msgsReceived, attachAddress); Weld weld = new Weld(); weld.addBeanClass(ProducingBeanUsingOutboundMetadata.class); new MapBasedConfig() .with("mp.messaging.outgoing.sink.address", address) .with("mp.messaging.outgoing.sink.connector", AmqpConnector.CONNECTOR_NAME) .with("mp.messaging.outgoing.sink.host", "localhost") .with("mp.messaging.outgoing.sink.port", server.actualPort()) .with("mp.messaging.outgoing.sink.use-anonymous-sender", false) .with("mp.messaging.outgoing.sink.tracing-enabled", false) .write(); container = weld.initialize(); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); List<Object> payloadsReceived = new ArrayList<>(msgCount); messagesReceived.forEach(msg -> { assertThat(msg.getAddress()).isEqualTo( address); // Matches the one from the config, not metadata, due to not using an anonymous sender assertThat(msg.getSubject()).isEqualTo("metadata-subject"); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); payloadsReceived.add(((AmqpValue) body).getValue()); }); assertThat(payloadsReceived).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Should have used an fixed-address sender link, verify target address assertThat(attachAddress.get()).isEqualTo(address); } @Test @Timeout(30) @SuppressWarnings("deprecation") public void testSinkUsingAmqpMessage() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(v -> AmqpMessage.<String> builder() .withBody(HELLO + v) .withSubject("foo") .build()) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isNull(); assertThat(msg.getSubject()).isEqualTo("foo"); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); Object payload = ((AmqpValue) body).getValue(); assertThat(HELLO + count).isEqualTo(payload); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) @SuppressWarnings("deprecation") public void testSinkUsingAmqpMessageWithNonAnonymousSender() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); AtomicReference<String> attachAddress = new AtomicReference<>("non-null-initialisation-value"); server = setupMockServerForTypeTest(messagesReceived, msgsReceived, attachAddress); String address = UUID.randomUUID().toString(); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndNonAnonymousSink(address, server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(v -> AmqpMessage.<String> builder() .withBody(HELLO + v) .withSubject("foo") .withAddress("unused") .build()) .subscribe((Subscriber<? super AmqpMessage<String>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isNull(); assertThat(msg.getSubject()).isEqualTo("foo"); assertThat(msg.getAddress()).isEqualTo( address); // Matches the one from the config, not message, due to not using an anonymous sender Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); Object payload = ((AmqpValue) body).getValue(); assertThat(HELLO + count).isEqualTo(payload); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); // Should have used an fixed-address sender link, verify target address assertThat(attachAddress.get()).isEqualTo(address); } @Test @Timeout(30) public void testSinkUsingProtonMessage() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(v -> { org.apache.qpid.proton.message.Message message = org.apache.qpid.proton.message.Message.Factory .create(); message.setBody(new Data(new Binary((HELLO + v).getBytes(StandardCharsets.UTF_8)))); message.setContentType("text/plain"); message.setSubject("bar"); return Message.of(message); }) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("text/plain"); assertThat(msg.getSubject()).isEqualTo("bar"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); byte[] receievedBytes = Binary.copy(((Data) body).getValue()).getArray(); byte[] expectedBytes = (HELLO + count.get()).getBytes(StandardCharsets.UTF_8); assertThat(receievedBytes).isEqualTo(expectedBytes); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) public void testSinkUsingMutinyMessage() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(v -> io.vertx.mutiny.amqp.AmqpMessage.create() .withBufferAsBody(Buffer.buffer((HELLO + v).getBytes(StandardCharsets.UTF_8))) .contentType("text/plain") .subject("bar") .build()) .map(Message::of) .subscribe((Subscriber<? super Message<io.vertx.mutiny.amqp.AmqpMessage>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("text/plain"); assertThat(msg.getSubject()).isEqualTo("bar"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); byte[] receievedBytes = Binary.copy(((Data) body).getValue()).getArray(); byte[] expectedBytes = (HELLO + count.get()).getBytes(StandardCharsets.UTF_8); assertThat(receievedBytes).isEqualTo(expectedBytes); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) public void testSinkUsingMutinyMessageViaBuilder() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(v -> { io.vertx.mutiny.amqp.AmqpMessageBuilder builder = io.vertx.mutiny.amqp.AmqpMessageBuilder.create(); builder.withBufferAsBody(Buffer.buffer((HELLO + v).getBytes(StandardCharsets.UTF_8))) .contentType("text/plain") .subject("baz"); return Message.of(builder.build()); }) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("text/plain"); assertThat(msg.getSubject()).isEqualTo("baz"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); byte[] receievedBytes = Binary.copy(((Data) body).getValue()).getArray(); byte[] expectedBytes = (HELLO + count.get()).getBytes(StandardCharsets.UTF_8); assertThat(receievedBytes).isEqualTo(expectedBytes); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) public void testSinkUsingVertxAmqpClientMessage() throws Exception { int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(UUID.randomUUID().toString(), server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(v -> { io.vertx.amqp.AmqpMessageBuilder builder = io.vertx.amqp.AmqpMessageBuilder.create(); builder.subject("baz") .withBufferAsBody(io.vertx.core.buffer.Buffer.buffer((HELLO + v).getBytes(StandardCharsets.UTF_8))) .contentType("text/plain"); return Message.of(builder.build()); }) .subscribe((Subscriber<? super Message<?>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getContentType()).isEqualTo("text/plain"); assertThat(msg.getSubject()).isEqualTo("baz"); Section body = msg.getBody(); assertThat(body).isInstanceOf(Data.class); byte[] receievedBytes = Binary.copy(((Data) body).getValue()).getArray(); byte[] expectedBytes = (HELLO + count.get()).getBytes(StandardCharsets.UTF_8); assertThat(receievedBytes).isEqualTo(expectedBytes); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @Test @Timeout(30) @SuppressWarnings({ "deprecation" }) public void testSinkUsingAmqpMessageAndChannelNameProperty() throws Exception { int msgCount = 10; String topic = UUID.randomUUID().toString(); CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); AtomicReference<String> attachAddress = new AtomicReference<>("non-null-initialisation-value"); server = setupMockServerForTypeTest(messagesReceived, msgsReceived, attachAddress); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSinkUsingChannelName(topic, server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(v -> AmqpMessage.<String> builder().withBody(HELLO + v).withSubject("foo").build()) .subscribe((Subscriber<? super AmqpMessage<String>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getAddress()).isEqualTo(topic); assertThat(msg.getSubject()).isEqualTo("foo"); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); Object payload = ((AmqpValue) body).getValue(); assertThat(HELLO + count).isEqualTo(payload); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); // Should have used an anonymous sender link, verify null target address assertThat(attachAddress.get()).isNull(); } @SuppressWarnings("unchecked") @Test @Timeout(30) public void testOutgoingMetadata() throws Exception { String address = UUID.randomUUID().toString(); int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(address, server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(Message::of) .map(m -> m.addMetadata(OutgoingAmqpMetadata.builder() .withSubject("subject") .withMessageId("my-id") .withReplyTo("reply-to") .withReplyToGroupId("reply-to-group") .withPriority((short) 6) .withTtl(2000) .withGroupId("group") .withContentType("text/plain") .withCorrelationId("correlation-" + m.getPayload()) .withUserId("user") .withDeliveryAnnotations("some-delivery-annotation", "da-value") .withMessageAnnotations("some-msg-annotation", "ma-value") .withApplicationProperties(new JsonObject().put("key", "value")) .withFooter("my-trailer", "hello-footer") .build())) .subscribe((Subscriber<? super Message<Integer>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getAddress()).isEqualTo(address); assertThat(msg.getSubject()).isEqualTo("subject"); assertThat(msg.getMessageId()).isEqualTo("my-id"); assertThat(msg.getReplyTo()).isEqualTo("reply-to"); assertThat(msg.getReplyToGroupId()).isEqualTo("reply-to-group"); assertThat(msg.getPriority()).isEqualTo((short) 6); assertThat(msg.getTtl()).isEqualTo(2000); assertThat(msg.getGroupId()).isEqualTo("group"); assertThat(msg.getContentType()).isEqualTo("text/plain"); assertThat(msg.getCorrelationId()).isEqualTo("correlation-" + count.get()); assertThat(msg.isFirstAcquirer()).isFalse(); assertThat(msg.getUserId()).isEqualTo("user".getBytes(StandardCharsets.UTF_8)); assertThat(msg.getDeliveryAnnotations()).isNotNull(); assertThat(msg.getDeliveryAnnotations().getValue()) .containsExactly(entry(Symbol.valueOf("some-delivery-annotation"), "da-value")); assertThat(msg.getMessageAnnotations()).isNotNull(); assertThat(msg.getMessageAnnotations().getValue()) .containsExactly(entry(Symbol.valueOf("some-msg-annotation"), "ma-value")); assertThat(msg.getApplicationProperties()).isNotNull(); assertThat(msg.getApplicationProperties().getValue()).containsExactly(entry("key", "value")); assertThat(msg.getFooter()).isNotNull(); //noinspection unchecked assertThat(msg.getFooter().getValue()).containsExactly(entry("my-trailer", "hello-footer")); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); assertThat(((AmqpValue) body).getValue()).isEqualTo(count.get()); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @SuppressWarnings("unchecked") @Test @Timeout(30) public void testOutgoingMetadataWithTtlSetOnConnector() throws Exception { String address = UUID.randomUUID().toString(); int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSinkWithConnectorTtl(address, server.actualPort(), 3000); //noinspection unchecked Multi.createFrom().range(0, 10) .map(Message::of) .map(m -> m.addMetadata(OutgoingAmqpMetadata.builder() .withSubject("subject") .withMessageId("my-id") .withReplyTo("reply-to") .withReplyToGroupId("reply-to-group") .withPriority((short) 6) .withGroupId("group") .withContentType("text/plain") .withCorrelationId("correlation-" + m.getPayload()) .withUserId("user") .withDeliveryAnnotations("some-delivery-annotation", "da-value") .withMessageAnnotations("some-msg-annotation", "ma-value") .withApplicationProperties(new JsonObject().put("key", "value")) .withFooter("my-trailer", "hello-footer") .build())) .subscribe((Subscriber<? super Message<Integer>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getAddress()).isEqualTo(address); assertThat(msg.getSubject()).isEqualTo("subject"); assertThat(msg.getMessageId()).isEqualTo("my-id"); assertThat(msg.getReplyTo()).isEqualTo("reply-to"); assertThat(msg.getReplyToGroupId()).isEqualTo("reply-to-group"); assertThat(msg.getPriority()).isEqualTo((short) 6); assertThat(msg.getTtl()).isEqualTo(3000); assertThat(msg.getGroupId()).isEqualTo("group"); assertThat(msg.getContentType()).isEqualTo("text/plain"); assertThat(msg.getCorrelationId()).isEqualTo("correlation-" + count.get()); assertThat(msg.isFirstAcquirer()).isFalse(); assertThat(msg.getUserId()).isEqualTo("user".getBytes(StandardCharsets.UTF_8)); assertThat(msg.getDeliveryAnnotations()).isNotNull(); assertThat(msg.getDeliveryAnnotations().getValue()) .containsExactly(entry(Symbol.valueOf("some-delivery-annotation"), "da-value")); assertThat(msg.getMessageAnnotations()).isNotNull(); assertThat(msg.getMessageAnnotations().getValue()) .containsExactly(entry(Symbol.valueOf("some-msg-annotation"), "ma-value")); assertThat(msg.getApplicationProperties()).isNotNull(); assertThat(msg.getApplicationProperties().getValue()).containsExactly(entry("key", "value")); assertThat(msg.getFooter()).isNotNull(); //noinspection unchecked assertThat(msg.getFooter().getValue()).containsExactly(entry("my-trailer", "hello-footer")); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); assertThat(((AmqpValue) body).getValue()).isEqualTo(count.get()); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @SuppressWarnings("unchecked") @Test @Timeout(30) public void testOutgoingMetadataWithTtlSetOnConnectorButOverriddenInMessage() throws Exception { String address = UUID.randomUUID().toString(); int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSinkWithConnectorTtl(address, server.actualPort(), 3000); //noinspection unchecked Multi.createFrom().range(0, 10) .map(Message::of) .map(m -> m.addMetadata(OutgoingAmqpMetadata.builder() .withSubject("subject") .withMessageId("my-id") .withReplyTo("reply-to") .withReplyToGroupId("reply-to-group") .withPriority((short) 6) .withTtl(4000) .withGroupId("group") .withContentType("text/plain") .withCorrelationId("correlation-" + m.getPayload()) .withUserId("user") .withDeliveryAnnotations("some-delivery-annotation", "da-value") .withMessageAnnotations("some-msg-annotation", "ma-value") .withApplicationProperties(new JsonObject().put("key", "value")) .withFooter("my-trailer", "hello-footer") .build())) .subscribe((Subscriber<? super Message<Integer>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getAddress()).isEqualTo(address); assertThat(msg.getSubject()).isEqualTo("subject"); assertThat(msg.getMessageId()).isEqualTo("my-id"); assertThat(msg.getReplyTo()).isEqualTo("reply-to"); assertThat(msg.getReplyToGroupId()).isEqualTo("reply-to-group"); assertThat(msg.getPriority()).isEqualTo((short) 6); assertThat(msg.getTtl()).isEqualTo(4000); assertThat(msg.getGroupId()).isEqualTo("group"); assertThat(msg.getContentType()).isEqualTo("text/plain"); assertThat(msg.getCorrelationId()).isEqualTo("correlation-" + count.get()); assertThat(msg.isFirstAcquirer()).isFalse(); assertThat(msg.getUserId()).isEqualTo("user".getBytes(StandardCharsets.UTF_8)); assertThat(msg.getDeliveryAnnotations()).isNotNull(); assertThat(msg.getDeliveryAnnotations().getValue()) .containsExactly(entry(Symbol.valueOf("some-delivery-annotation"), "da-value")); assertThat(msg.getMessageAnnotations()).isNotNull(); assertThat(msg.getMessageAnnotations().getValue()) .containsExactly(entry(Symbol.valueOf("some-msg-annotation"), "ma-value")); assertThat(msg.getApplicationProperties()).isNotNull(); assertThat(msg.getApplicationProperties().getValue()).containsExactly(entry("key", "value")); assertThat(msg.getFooter()).isNotNull(); //noinspection unchecked assertThat(msg.getFooter().getValue()).containsExactly(entry("my-trailer", "hello-footer")); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); assertThat(((AmqpValue) body).getValue()).isEqualTo(count.get()); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } @SuppressWarnings("unchecked") @Test @Timeout(30) public void testUnusedMessagesSectionsNotSent() throws Exception { String address = UUID.randomUUID().toString(); int msgCount = 10; CountDownLatch msgsReceived = new CountDownLatch(msgCount); List<org.apache.qpid.proton.message.Message> messagesReceived = Collections .synchronizedList(new ArrayList<>(msgCount)); server = setupMockServerForTypeTest(messagesReceived, msgsReceived); SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(address, server.actualPort()); //noinspection unchecked Multi.createFrom().range(0, 10) .map(Message::of) .subscribe((Subscriber<? super Message<Integer>>) sink.build()); assertThat(msgsReceived.await(6, TimeUnit.SECONDS)).isTrue(); AtomicInteger count = new AtomicInteger(); messagesReceived.forEach(msg -> { assertThat(msg.getAddress()).isEqualTo(address); Section body = msg.getBody(); assertThat(body).isInstanceOf(AmqpValue.class); assertThat(((AmqpValue) body).getValue()).isEqualTo(count.get()); // Check that the header, delivery annotations, message annotations, application properties, // and footer sections are null/not-present, as we didnt populate anything that goes in them. assertThat(msg.getHeader()).isNull(); assertThat(msg.getDeliveryAnnotations()).isNull(); assertThat(msg.getMessageAnnotations()).isNull(); assertThat(msg.getApplicationProperties()).isNull(); assertThat(msg.getFooter()).isNull(); count.incrementAndGet(); }); assertThat(count.get()).isEqualTo(msgCount); } private SubscriberBuilder<? extends Message<?>, Void> getSubscriberBuilder(Map<String, Object> config) { this.provider = new AmqpConnector(); provider.setup(executionHolder); return this.provider.getSubscriberBuilder(new MapBasedConfig(config)); } private Map<String, Object> createBaseConfig(String topic, int port) { Map<String, Object> config = new HashMap<>(); config.put(ConnectorFactory.CHANNEL_NAME_ATTRIBUTE, topic); config.put("name", "the name"); config.put("host", "localhost"); config.put("port", port); return config; } private SubscriberBuilder<? extends Message<?>, Void> createProviderAndSink(String topic, int port) { Map<String, Object> config = createBaseConfig(topic, port); config.put("address", topic); return getSubscriberBuilder(config); } @SuppressWarnings("SameParameterValue") private SubscriberBuilder<? extends Message<?>, Void> createProviderAndSinkWithConnectorTtl(String topic, int port, long ttl) { Map<String, Object> config = createBaseConfig(topic, port); config.put("address", topic); config.put("ttl", ttl); return getSubscriberBuilder(config); } private SubscriberBuilder<? extends Message<?>, Void> createProviderAndNonAnonymousSink(String topic, int port) { Map<String, Object> config = createBaseConfig(topic, port); config.put("address", topic); config.put("use-anonymous-sender", false); return getSubscriberBuilder(config); } private SubscriberBuilder<? extends Message<?>, Void> createProviderAndSinkUsingChannelName(String topic, int port) { Map<String, Object> config = createBaseConfig(topic, port); // We don't add the address config element, relying on the channel name instead return getSubscriberBuilder(config); } }
42.547041
127
0.619862
1981228a2bb2ef3abaae5aea44a8df9daae68488
2,400
/* * Copyright 2016 TUM Technische Universität München * * 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 de.tumitfahrer.daos.impl; import de.tumitfahrer.daos.IGenericDao; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.criterion.Criterion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional public abstract class GenericDao<T> implements IGenericDao<T> { protected Class<T> clazz; @Autowired protected SessionFactory sessionFactory; public GenericDao(Class<T> clazz) { this.clazz = clazz; } @Override @SuppressWarnings("unchecked") public T load(Integer id) { if (id == null) { return null; } return (T) sessionFactory.getCurrentSession().get(clazz, id); } @Override public void save(T object) { sessionFactory.getCurrentSession().save(object); } @Override public void update(T object) { sessionFactory.getCurrentSession().update(object); } @Override public void delete(T object) { sessionFactory.getCurrentSession().delete(object); } @SuppressWarnings("unchecked") protected List<T> findByCriterion(Criterion... criterion) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(clazz); for (Criterion c : criterion) { criteria.add(c); } return criteria.list(); } @SuppressWarnings("unchecked") protected List<T> findByCriterion(List<Criterion> criterion) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(clazz); for (Criterion c : criterion) { criteria.add(c); } return criteria.list(); } }
29.62963
85
0.683333
846898fd7e65186049c53f8961fe7761bd3d6257
14,419
package com.downloader.certificate; import javax.net.ssl.*; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.Socket; import java.net.URL; import java.security.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Arrays; /** * Created by Administrator on 2016/11/7. */ public class SSLTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager, HostnameVerifier { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } public boolean isServerTrusted( java.security.cert.X509Certificate[] certs) { return true; } public boolean isClientTrusted( java.security.cert.X509Certificate[] certs) { return true; } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } @Override public boolean verify(String urlHostName, SSLSession session) { //允许所有主机 return true; } /** * 客户端使用 */ public static HttpURLConnection connectTrustAllServer(String strUrl) throws Exception { return connectTrustAllServer(strUrl, null); } /** * 客户端使用 * * @param strUrl 要访问的地址 * @param proxy 需要经过的代理 * @return * @throws Exception */ public static HttpURLConnection connectTrustAllServer(String strUrl, Proxy proxy) throws Exception { javax.net.ssl.TrustManager[] trustCertsmanager = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new SSLTrustManager(); trustCertsmanager[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext .getInstance("TLS"); sc.init(null, trustCertsmanager, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc .getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((HostnameVerifier) tm); URL url = new URL(strUrl); HttpURLConnection urlConn = null; if (proxy == null) { urlConn = (HttpURLConnection) url.openConnection(); } else { urlConn = (HttpURLConnection) url.openConnection(proxy); } urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"); return urlConn; } /** * 用于双向认证,客户端使用 * * @param strUrl * @param proxy * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public static HttpURLConnection connectProxyTrustCA(String strUrl, Proxy proxy) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslsession) { return true; } }); String clientKeyStoreFile = "D:/JDK8Home/tianwt/sslClientKeys"; String clientKeyStorePwd = "123456"; String catServerKeyPwd = "123456"; String serverTrustKeyStoreFile = "D:/JDK8Home/tianwt/sslClientTrust"; String serverTrustKeyStorePwd = "123456"; KeyStore serverKeyStore = KeyStore.getInstance("JKS"); serverKeyStore.load(new FileInputStream(clientKeyStoreFile), clientKeyStorePwd.toCharArray()); KeyStore serverTrustKeyStore = KeyStore.getInstance("JKS"); serverTrustKeyStore.load(new FileInputStream(serverTrustKeyStoreFile), serverTrustKeyStorePwd.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(serverKeyStore, catServerKeyPwd.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(serverTrustKeyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); URL url = new URL(strUrl); HttpURLConnection httpURLConnection = null; if (proxy == null) { httpURLConnection = (HttpURLConnection) url.openConnection(); } else { httpURLConnection = (HttpURLConnection) url.openConnection(proxy); } httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"); return httpURLConnection; } /** * 用于单向认证,客户端使用 * <p> * server侧只需要自己的keystore文件,不需要truststore文件 * client侧不需要自己的keystore文件,只需要truststore文件(其中包含server的公钥)。 * 此外server侧需要在创建SSLServerSocket之后设定不需要客户端证书:setNeedClientAuth(false) * * @param strUrl * @param proxy * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public static HttpURLConnection connectProxyTrustCA2(String strUrl, Proxy proxy) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslsession) { return true; } }); String serverTrustKeyStoreFile = "D:/JDK8Home/tianwt/sslClientTrust"; String serverTrustKeyStorePwd = "123456"; KeyStore serverTrustKeyStore = KeyStore.getInstance("JKS"); serverTrustKeyStore.load(new FileInputStream(serverTrustKeyStoreFile), serverTrustKeyStorePwd.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(serverTrustKeyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); URL url = new URL(strUrl); HttpURLConnection httpURLConnection = null; if (proxy == null) { httpURLConnection = (HttpURLConnection) url.openConnection(); } else { httpURLConnection = (HttpURLConnection) url.openConnection(proxy); } httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"); return httpURLConnection; } /** * 用于双向认证 * * @param socketClient 是否产生socket * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public SSLSocket createTlsConnect(Socket socketClient) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { String protocol = "TLS"; String serverKey = "D:/JDK8Home/tianwt/sslServerKeys"; String serverTrust = "D:/JDK8Home/tianwt/sslServerTrust"; String serverKeyPwd = "123456"; //私钥密码 String serverTrustPwd = "123456"; //信任证书密码 String serverKeyStorePwd = "123456"; // keystore存储密码 KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(serverKey), serverKeyPwd.toCharArray()); KeyStore tks = KeyStore.getInstance("JKS"); tks.load(new FileInputStream(serverTrust), serverTrustPwd.toCharArray()); KeyManagerFactory km = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); km.init(keyStore, serverKeyStorePwd.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(tks); SSLContext sslContext = SSLContext.getInstance(protocol); sslContext.init(km.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); //第一项是用来做服务器验证的 SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket clientSSLSocket = (SSLSocket) sslSocketFactory.createSocket(socketClient, socketClient.getInetAddress().getHostAddress(), socketClient.getPort(), true); clientSSLSocket.setNeedClientAuth(false); clientSSLSocket.setUseClientMode(false); return clientSSLSocket; } /** * 用于单向认证 * server侧只需要自己的keystore文件,不需要truststore文件 * client侧不需要自己的keystore文件,只需要truststore文件(其中包含server的公钥)。 * 此外server侧需要在创建SSLServerSocket之后设定不需要客户端证书:setNeedClientAuth(false) * * @param socketClient * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public static SSLSocket createTlsConnect2(Socket socketClient) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { String protocol = "TLS"; String serverKey = "D:/JDK8Home/tianwt/sslServerKeys"; String serverKeyPwd = "123456"; //私钥密码 String serverKeyStorePwd = "123456"; // keystore存储密码 KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(serverKey), serverKeyPwd.toCharArray()); KeyManagerFactory km = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); km.init(keyStore, serverKeyStorePwd.toCharArray()); SSLContext sslContext = SSLContext.getInstance(protocol); sslContext.init(km.getKeyManagers(), null, new SecureRandom()); //第一项是用来做服务器验证的 SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket clientSSLSocket = (SSLSocket) sslSocketFactory.createSocket(socketClient, socketClient.getInetAddress().getHostAddress(), socketClient.getPort(), true); clientSSLSocket.setNeedClientAuth(false); clientSSLSocket.setUseClientMode(false); return clientSSLSocket; } /** * 将普通的socket转为sslsocket,客户端和服务端均可使用 * <p> * 服务端使用的时候是把普通的socket转为sslsocket,并且作为服务器套接字(注意:指的不是ServerSocket,当然ServerSocket的本质也是普通socket) * * @param remoteHost * @param isClient * @return */ public static SSLSocket getTlsTrustAllSocket(Socket remoteHost, boolean isClient) { SSLSocket remoteSSLSocket = null; SSLContext context = SSLTrustManager.getTrustAllSSLContext(isClient); try { remoteSSLSocket = (SSLSocket) context.getSocketFactory().createSocket(remoteHost, remoteHost.getInetAddress().getHostName(), remoteHost.getPort(), true); remoteSSLSocket.setTcpNoDelay(true); remoteSSLSocket.setSoTimeout(5000); remoteSSLSocket.setNeedClientAuth(false); //这里设置为true时会强制握手 remoteSSLSocket.setUseClientMode(isClient); //注意服务器和客户的角色选择 } catch (IOException e) { e.printStackTrace(); } return remoteSSLSocket; } /** * 用于客户端,通过所有证书验证 * * @param isClient 是否生成客户端SSLContext,否则生成服务端SSLContext * @return */ public static SSLContext getTrustAllSSLContext(boolean isClient) { String protocol = "TLS"; javax.net.ssl.SSLContext sc = null; try { javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new SSLTrustManager(); trustAllCerts[0] = tm; sc = javax.net.ssl.SSLContext .getInstance(protocol); if (isClient) { sc.init(null, trustAllCerts, null); //作为客户端使用 } else { String serverKeyPath = "D:/JDK8Home/tianwt/sslServerKeys"; String serverKeyPwd = "123456"; //私钥密码 String serverKeyStorePwd = "123456"; // keystore存储密码 KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(serverKeyPath), serverKeyPwd.toCharArray()); KeyManagerFactory km = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); km.init(keyStore, serverKeyStorePwd.toCharArray()); KeyManager[] keyManagers = km.getKeyManagers(); keyManagers = Arrays.copyOf(keyManagers, keyManagers.length + 1); sc.init(keyManagers, null, new SecureRandom()); } } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sc; } }
39.396175
246
0.683265
377e9bbad7f5360326ad29b3969ed533b40510cc
5,435
package com.jack12324.eop.machine.equalizingSmelter; import com.jack12324.eop.ExtremeOreProcessing; import com.jack12324.eop.packet.PacketClientToServer; import com.jack12324.eop.packet.PacketHandler; import com.jack12324.eop.util.Coord4D; import com.jack12324.eop.util.GuiValues; import com.jack12324.eop.util.HelpfulMethods; import com.jack12324.eop.util.gui.GuiBase; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class GuiEqualizingSmelter extends GuiBase { private static final ResourceLocation BG_TEXTURE = new ResourceLocation(ExtremeOreProcessing.modID, "textures/gui/equalizing_smelter.png"); private static final GuiValues guiValues = GuiValues.EQUALIZINGSMELTER; private final TileEntityEqualizingSmelter tileEntity; public GuiEqualizingSmelter(Container inventorySlotsIn, InventoryPlayer playerInv, TileEntityEqualizingSmelter tileEntity) { super(inventorySlotsIn, playerInv, tileEntity, BG_TEXTURE, guiValues); this.tileEntity = tileEntity; } @Override protected void actionPerformed(GuiButton button, int mbutton) throws IOException { if (button.id == 53 || button.id == 57) { NBTTagCompound compound = new NBTTagCompound(); Coord4D pos = new Coord4D(tileEntity.getPos(), tileEntity.getWorld()); compound = pos.write(compound); compound.setInteger("buttonID", button.id); PacketHandler.NETWORK.sendToServer(new PacketClientToServer(compound, PacketHandler.GUI_TOGGLE_BUTTON)); } else { super.actionPerformed(button, mbutton); } } @Override protected void drawTitleText(FontRenderer fontRenderer, String name, String invName) { String[] parts = name.split(" ", 2); name = parts[0]; String name2 = parts[1]; fontRenderer.drawString(name, xSize / 8 - fontRenderer.getStringWidth(name) / 8, 6, 0x404040); fontRenderer.drawString(name2, xSize / 8 - fontRenderer.getStringWidth(name2) / 8, 16, 0x404040); fontRenderer.drawString(invName, 8, ySize - 76, 0x404040); } @Override protected void drawOther() { // extraFirestone slot double dustProgress = tileEntity.fractionOfDustProgress(); int yOffset = (int) ((1.0 - dustProgress) * guiValues.getOther()[5]); drawTexturedModalRect(guiLeft + guiValues.getOther()[0], guiTop + guiValues.getOther()[1] + yOffset, guiValues.getOther()[2], guiValues.getOther()[3] + yOffset, guiValues.getOther()[4], guiValues.getOther()[5] - yOffset); } @Override public void drawProgressBar() { for (int i = 0; i < GuiValues.EQUALIZINGSMELTER.getProgress().length; i += 6) { // get cook progress as a double between 0 and 1 double cookProgress = tileEntity.fractionOfProgressTimeComplete(i / 6); // draw the cook progress bar if (i == 0 || i == 12) drawTexturedModalRect(guiLeft + guiValues.getProgress()[i], guiTop + guiValues.getProgress()[i + 1], guiValues.getProgress()[i + 2], guiValues.getProgress()[i + 3], (int) (cookProgress * guiValues.getProgress()[i + 4]), guiValues.getProgress()[i + 5]); else { int xOffset = (int) ((1.0 - cookProgress) * guiValues.getProgress()[i + 4]); drawTexturedModalRect(guiLeft + guiValues.getProgress()[i] + xOffset, guiTop + guiValues.getProgress()[i + 1], guiValues.getProgress()[i + 2] + xOffset, guiValues.getProgress()[i + 3], guiValues.getProgress()[i + 4] - xOffset, guiValues.getProgress()[i + 5]); } } } @Override protected List<String> otherText(int mouseX, int mouseY) { List<String> hoveringText = new ArrayList<>(); // hovering text for buttons if (HelpfulMethods.isInRect(guiLeft - 40, guiTop + 30, 40, 20, mouseX, mouseY)) { hoveringText.add("Toggle Spread Mode"); hoveringText.add("Spread Mode: " + tileEntity.getSpreadMode()); } if (HelpfulMethods.isInRect(guiLeft - 30, guiTop + 5, 30, 20, mouseX, mouseY)) { hoveringText.add("Toggle Smelter Mode"); if (tileEntity.getMode()) hoveringText.add("Smelter Mode: Furnace"); else hoveringText.add("Smelter Mode: Equalizing"); } // hovering text for firestone slot if (HelpfulMethods.isInRect(guiLeft + guiValues.getOther()[0], guiTop + guiValues.getOther()[1], guiValues.getOther()[4], guiValues.getOther()[5], mouseX, mouseY)) { hoveringText.add("Progress:"); int dustPercentage = (int) (tileEntity.fractionOfDustProgress() * 100); hoveringText.add(dustPercentage + "%"); } return hoveringText; } @Override public void initGui() { super.initGui(); this.buttonList.add(new GuiButton(53, guiLeft - 30, guiTop, 30, 20, "Mode")); this.buttonList.add(new GuiButton(57, guiLeft - 40, guiTop + 20, 40, 20, "Spread")); } }
46.059322
173
0.656118
d002271495b4555e3ed3dce3413286a0a7a33ee8
516
package org.pac4j.oauth.profile.facebook; import java.io.Serializable; /** * This class represents a Facebook application. * * @author Jerome Leleu * @since 1.2.0 */ public final class FacebookApplication implements Serializable { private static final long serialVersionUID = 8888597071833762957L; private String namespace; public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } }
20.64
70
0.693798
2f726eebbec13ea2a5847a4cef6df98eef056a10
4,986
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.streamToLoop; import com.intellij.lang.java.lexer.JavaLexer; import com.intellij.openapi.project.Project; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import java.util.*; /** * Provides context that can be used during transformation of chained method calls (e.g. stream calls chain, optional calls chain). * <p> * Allows to: * 1. register newly allocated variables' names * 2. add before / after steps that can be added after transformation is complete * 3. create different elements using PsiElementFactory */ public class ChainContext { private final PsiElementFactory myFactory; private final List<String> myBeforeSteps = new ArrayList<>(); private final List<String> myAfterSteps = new ArrayList<>(); public PsiElement myChainExpression; final Set<String> myUsedNames; public ChainContext(@NotNull PsiElement chainExpression) { myChainExpression = chainExpression; myFactory = JavaPsiFacade.getElementFactory(chainExpression.getProject()); myUsedNames = new HashSet<>(); } /** * Constructs chain context using parent's context chain call, factory and registered names. */ public ChainContext(@NotNull ChainContext parentContext) { myChainExpression = parentContext.myChainExpression; myFactory = parentContext.myFactory; myUsedNames = parentContext.myUsedNames; } /** * Choose name from variants for newly allocated variable and register it in context. * If all names from variants are already used then variable is named variant$i for i from 1 to Integer.MAX_INTEGER. * If no variants are present then variable is named either val or val$i. * * @param variants possible variable names * @return chosen name */ public String registerVarName(@NotNull Collection<String> variants) { if (variants.isEmpty()) { return registerVarName(Collections.singleton("val")); } for (int idx = 0; ; idx++) { for (String variant : variants) { String name = idx == 0 ? variant : variant + idx; if (!isUsed(name)) { myUsedNames.add(name); return name; } } } } /** * Add variable declaration to beforeSteps. * * @param desiredName desired name that is registered in context * @param type variable type * @param initializer variable initializer * @return */ public String declare(String desiredName, String type, String initializer) { String name = registerVarName(Collections.singleton(desiredName)); myBeforeSteps.add(type + " " + name + " = " + initializer + ";"); return name; } /** * Add step that will be added before transformation result. * * @param beforeStatement statement to add */ public void addBeforeStep(String beforeStatement) { myBeforeSteps.add(beforeStatement); } /** * Get all before steps and remove them from context. * * @return before steps */ public String drainBeforeSteps() { String beforeSteps = String.join("", myBeforeSteps); myBeforeSteps.clear(); return beforeSteps; } /** * Add step that will be added after transformation result. * * @param afterStatement statement to add */ public void addAfterStep(String afterStatement) { myAfterSteps.add(0, afterStatement); } /** * Get all after steps and remove them from context. * * @return before steps */ public String drainAfterSteps() { String afterSteps = String.join("", myAfterSteps); myAfterSteps.clear(); return afterSteps; } /** * Create expression from text in context of chain call. */ public PsiExpression createExpression(String text) { return myFactory.createExpressionFromText(text, myChainExpression); } /** * Create statement from text in context of chain call. */ public PsiStatement createStatement(String text) { return myFactory.createStatementFromText(text, myChainExpression); } /** * Create type from text in context of chain call. */ public PsiType createType(String text) { return myFactory.createTypeFromText(text, myChainExpression); } private boolean isUsed(String varName) { return myUsedNames.contains(varName) || JavaLexer.isKeyword(varName, LanguageLevel.HIGHEST) || !varName.equals(JavaCodeStyleManager.getInstance(getProject()) .suggestUniqueVariableName(varName, myChainExpression, v -> PsiTreeUtil.isAncestor(myChainExpression, v, true))); } /** * Get chain call project. */ public Project getProject() { return myChainExpression.getProject(); } }
31.757962
140
0.697754
b2ad2564f7a71fb4ca261ef42ba8fa2e8b4c7362
418
package com.devyok.bluetooth.base; /** * * @author wei.deng * */ public class BluetoothException extends Exception{ /** * */ private static final long serialVersionUID = 1L; public BluetoothException(String message, Throwable cause) { super(message, cause); } public BluetoothException(String message) { super(message); } public BluetoothException(Throwable cause) { super(cause); } }
14.413793
61
0.698565
6a6d6dee4c96baf8f85cbad40638b42b873cd211
3,904
package dev.paddock.adp.mCubed.model; import android.test.AndroidTestCase; import dev.paddock.adp.mCubed.TestUtils; public class WhereClauseTest extends AndroidTestCase { public void testCreate() { WhereClause a = WhereClause.create("a"); assertEquals("a", a.getSelection()); } public void testOr() { WhereClause a = WhereClause.create("a"); WhereClause b = WhereClause.create("b"); WhereClause or = WhereClause.or(a, b); assertEquals("(a OR b)", or.getSelection()); } public void testAnd() { WhereClause a = WhereClause.create("a"); WhereClause b = WhereClause.create("b"); WhereClause and = WhereClause.and(a, b); assertEquals("(a AND b)", and.getSelection()); } public void testOrsAnded() { // Create first or WhereClause a = WhereClause.create("a"); WhereClause b = WhereClause.create("b"); WhereClause orA = WhereClause.or(a, b); // Create second or WhereClause c = WhereClause.create("c"); WhereClause d = WhereClause.create("d"); WhereClause orB = WhereClause.or(c, d); // And the ors WhereClause and = WhereClause.and(orA, orB); assertEquals("((a OR b) AND (c OR d))", and.getSelection()); } public void testAndsOred() { // Create first and WhereClause a = WhereClause.create("a"); WhereClause b = WhereClause.create("b"); WhereClause andA = WhereClause.and(a, b); // Create second and WhereClause c = WhereClause.create("c"); WhereClause d = WhereClause.create("d"); WhereClause andB = WhereClause.and(c, d); // Or the ands WhereClause or = WhereClause.or(andA, andB); assertEquals("((a AND b) OR (c AND d))", or.getSelection()); } public void testComplexClause() { // Create threesome clause WhereClause a = WhereClause.create("a").or("b").and("c"); assertEquals("((a OR b) AND c)", a.getSelection()); // Create foursome clause WhereClause b = WhereClause.create("d").and("e").or("f").and("g"); assertEquals("(((d AND e) OR f) AND g)", b.getSelection()); // Or them together WhereClause orResult = a.or(b); assertEquals("(((a OR b) AND c) OR (((d AND e) OR f) AND g))", orResult.getSelection()); // And them together WhereClause andResult = b.and(a); assertEquals("((((d AND e) OR f) AND g) AND ((a OR b) AND c))", andResult.getSelection()); } public void testNoSelectionArgs() { // Create threesome clause WhereClause a = WhereClause.create("a").and("b").and("c"); assertEquals("((a AND b) AND c)", a.getSelection()); // Assert the selection args come out right TestUtils.assertSequenceEmpty(a.getSelectionArgs()); } public void testSimpleSelectionArgs() { // Create threesome clause WhereClause a = WhereClause.create("a = ?", "aVal").or("b = ?", "bVal").and("c = ?", "cVal"); assertEquals("((a = ? OR b = ?) AND c = ?)", a.getSelection()); // Assert the selection args come out right TestUtils.assertSequenceEquals(new String[] { "aVal", "bVal", "cVal" }, a.getSelectionArgs()); } public void testComplexSelectionArgs() { // Create threesome clause WhereClause a = WhereClause.create("a = ?", "aVal").or("b = ?", "bVal").and("c = ?", "cVal"); assertEquals("((a = ? OR b = ?) AND c = ?)", a.getSelection()); // Create foursome clause WhereClause b = WhereClause.create("d = ?", "dVal").and("e = ?", "eVal").or("f = ?", "fVal").and("g = ?", "gVal"); assertEquals("(((d = ? AND e = ?) OR f = ?) AND g = ?)", b.getSelection()); // And them together WhereClause andResult = a.and(b); assertEquals("(((a = ? OR b = ?) AND c = ?) AND (((d = ? AND e = ?) OR f = ?) AND g = ?))", andResult.getSelection()); // Assert the selection args come out right TestUtils.assertSequenceEquals(new String[] { "aVal", "bVal", "cVal", "dVal", "eVal", "fVal", "gVal" }, andResult.getSelectionArgs()); } }
35.490909
137
0.622182
ccbe276657b46137aa61b6e90d0431a6af0180f7
808
package com.telecominfraproject.wlan.client.datastore.inmemory; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit4.SpringRunner; import com.telecominfraproject.wlan.client.datastore.BaseClientDatastoreTest; import com.telecominfraproject.wlan.client.datastore.inmemory.ClientDatastoreInMemory; /** * @author dtoptygin * */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE, classes = ClientDatastoreInMemoryTests.class) @Import(value = { ClientDatastoreInMemory.class }) public class ClientDatastoreInMemoryTests extends BaseClientDatastoreTest { }
36.727273
99
0.846535
e495c0cb7b7fcefe6b0b4aac74c3a0793ef2b6ec
4,268
/* * Adito * * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package com.adito.extensions.actions; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.adito.core.actions.AuthenticatedDispatchAction; import com.adito.extensions.ExtensionBundle; import com.adito.extensions.forms.ExtensionBundleInformationForm; import com.adito.extensions.store.ExtensionStore; import com.adito.security.Constants; import com.adito.security.SessionInfo; /** * Action that display details about a {@link ExtensionBundle}. */ public class ExtensionBundleInformationAction extends AuthenticatedDispatchAction { final static Log log = LogFactory.getLog(ExtensionBundleInformationAction.class); /** * Constructor */ public ExtensionBundleInformationAction() { super(); } /* * (non-Javadoc) * * @see org.apache.struts.actions.DispatchAction#unspecified(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { String bundleId = request.getParameter("bundleId"); ExtensionBundle bundle; try { bundle = ExtensionStore.getInstance().getExtensionBundle(bundleId); } catch(Exception e) { bundle = ExtensionStore.getInstance().getDownloadableExtensionStoreDescriptor(true).getApplicationBundle(bundleId); } request.setAttribute(Constants.REQ_ATTR_INFO_RESOURCE, bundle); return extensionBundleInformation(mapping, form, request, response); } catch (Exception e) { log.error("Failed to get extension information. ", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return null; } } /** * Display information about an extension bundle * * @param mapping mapping * @param form form * @param request request * @param response response * @return forward * @throws Exception on any error */ public ActionForward extensionBundleInformation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ((ExtensionBundleInformationForm) form).initialise((ExtensionBundle) request.getAttribute(Constants.REQ_ATTR_INFO_RESOURCE)); return mapping.findForward("display"); } /* * (non-Javadoc) * * @see com.adito.core.actions.CoreAction#getNavigationContext(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ public int getNavigationContext(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { return SessionInfo.MANAGEMENT_CONSOLE_CONTEXT; } }
39.518519
135
0.699859
ba887dcd23c23e735e56bf4af5a21c516ad6ed34
4,279
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.institutionalproposal.home; import org.kuali.kra.institutionalproposal.document.InstitutionalProposalDocument; import org.kuali.kra.institutionalproposal.rules.InstitutionalProposalAddUnrecoveredFandARuleEvent; import org.kuali.kra.institutionalproposal.rules.InstitutionalProposalUnrecoveredFandARuleImpl; import org.kuali.kra.institutionalproposal.web.struts.form.InstitutionalProposalForm; import java.io.Serializable; public class InstitutionalProposalUnrecoveredFandABean implements Serializable { private static final long serialVersionUID = -4162806132355841770L; private InstitutionalProposalForm parent; private InstitutionalProposalUnrecoveredFandA newInstitutionalProposalUnrecoveredFandA; /** * Constructs a InstitutionalProposalUnrecoveredFandABean * @param parent */ public InstitutionalProposalUnrecoveredFandABean() { super(); newInstitutionalProposalUnrecoveredFandA = new InstitutionalProposalUnrecoveredFandA(); } /** * Constructs a InstitutionalProposalUnrecoveredFandABean * @param parent */ public InstitutionalProposalUnrecoveredFandABean(InstitutionalProposalForm parent) { this.parent = parent; newInstitutionalProposalUnrecoveredFandA = new InstitutionalProposalUnrecoveredFandA(); } /** * Initialize subform */ public void init() { newInstitutionalProposalUnrecoveredFandA = new InstitutionalProposalUnrecoveredFandA(); } /** * Gets the newInstitutionalProposalUnrecoveredFandA attribute. * @return Returns the newInstitutionalProposalUnrecoveredFandA. */ public InstitutionalProposalUnrecoveredFandA getNewInstitutionalProposalUnrecoveredFandA() { return newInstitutionalProposalUnrecoveredFandA; } /** * Sets the newInstitutionalProposalUnrecoveredFandA attribute value. * @param newInstitutionalProposalUnrecoveredFandA The newInstitutionalProposalUnrecoveredFandA to set. */ public void setnewInstitutionalProposalUnrecoveredFandA(InstitutionalProposalUnrecoveredFandA thisInstitutionalProposalUnrecoveredFandA) { this.newInstitutionalProposalUnrecoveredFandA = thisInstitutionalProposalUnrecoveredFandA; } public InstitutionalProposalDocument getInstitutionalProposalDocument() { return parent.getInstitutionalProposalDocument(); } public Object getData() { return getNewInstitutionalProposalUnrecoveredFandA(); } /** * This method is called when adding a new AwardCostShare * @param formHelper * @return * @throws Exception */ public boolean addUnrecoveredFandA(InstitutionalProposalUnrecoveredFandABean formBean) throws Exception { InstitutionalProposalAddUnrecoveredFandARuleEvent event = new InstitutionalProposalAddUnrecoveredFandARuleEvent( "newInstitutionalProposalUnrecoveredFandA", formBean.getInstitutionalProposalDocument(), formBean.getNewInstitutionalProposalUnrecoveredFandA()); boolean success = new InstitutionalProposalUnrecoveredFandARuleImpl().processAddInstitutionalProposalUnrecoveredFandABusinessRules(event); if(success){ formBean.getInstitutionalProposalDocument().getInstitutionalProposal().add(formBean.getNewInstitutionalProposalUnrecoveredFandA()); formBean.init(); } return success; } }
40.752381
147
0.73592
d7ed5ea0036d0a6b855c50e0662ab9f2a8062949
1,281
package roundone; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Solution78 { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int cases = Integer.parseInt(scanner.nextLine()); while (cases-- > 0) { int size = scanner.nextInt(); int[] power = new int[size]; for (int i = 0; i < size; i++) { power[i] = scanner.nextInt(); } Solution solution = new Solution(); List<List<Integer>> ans = solution.subsets(power); System.out.println(ans); } } static class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> lists = new ArrayList<>(); int size = 1 << nums.length; for (int i = 0; i < size; i++) { lists.add(new ArrayList<>()); } for (int i = 0; i < size; i++) { for (int j = 0; j < nums.length; j++) { if ((i & (1 << j)) > 0) { lists.get(i).add(nums[j]); } } } return lists; } } }
22.473684
62
0.446526
6cacf762d14e794402cc944e210c0d887dfc256c
784
package com.datang.modules.oss.service.impl; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.datang.common.utils.Query; import com.datang.common.utils.PageUtils; import com.datang.modules.oss.dao.SysOssDao; import com.datang.modules.oss.entity.SysOssEntity; import com.datang.modules.oss.service.SysOssService; import org.springframework.stereotype.Service; import java.util.Map; @Service("sysOssService") public class SysOssServiceImpl extends ServiceImpl<SysOssDao, SysOssEntity> implements SysOssService { @Override public PageUtils queryPage(Map<String, Object> params) { Page<SysOssEntity> page = this.selectPage( new Query<SysOssEntity>(params).getPage() ); return new PageUtils(page); } }
28
102
0.799745
a55c8fe8fec31797297d44071ed10f50aa5f6545
1,079
package com.example.gouadadopavogui.myshoppingapp.controller; import com.example.gouadadopavogui.myshoppingapp.helpers.Constants; import com.example.gouadadopavogui.myshoppingapp.interfaces.ShoppingGroupRestService; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Locale; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by GouadaDopavogui on 19.11.2016. */ public class ShoppingGroupRetrofitClient { public ShoppingGroupRestService getIGrouP() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd") .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constants.BASEURL) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); ShoppingGroupRestService shoppingGroupRestService = retrofit.create(ShoppingGroupRestService.class); return shoppingGroupRestService; } }
33.71875
109
0.675626
52aa4ebda841b283a0643727141213718e7c1acb
1,920
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String infix) { /* To find out the precedence, we take the index of the token in the ops string and divide by 2 (rounding down). This will give us: 0, 0, 1, 1, 2 */ final String ops = "-+/*^"; StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); for (String token : infix.split("\\s")) { if (token.isEmpty()) continue; char c = token.charAt(0); int idx = ops.indexOf(c); // check for operator if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 > prec1 || (prec2 == prec1 && c != '^')) sb.append(ops.charAt(s.pop())).append(' '); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); // -2 stands for '(' } else if (c == ')') { // until '(' on stack, pop operators. while (s.peek() != -2) sb.append(ops.charAt(s.pop())).append(' '); s.pop(); } else { sb.append(token).append(' '); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())).append(' '); return sb.toString(); } }
32
74
0.402083
2b9794f2803896c3b986b49a292dec546756d6fb
1,863
package com.peralex.utilities.ui.graphs.axisscale; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.SimpleBeanInfo; import javax.swing.JComponent; /** * BeanInfo class for AbstractDefaultAxisScale. Makes GUI editing of this component easier. * * @author Noel Grandin */ public class AbstractDefaultAxisScaleBeanInfo extends SimpleBeanInfo { @Override public PropertyDescriptor[] getPropertyDescriptors() { try { // use the introspector to get a list of JComponent's properties final PropertyDescriptor [] superclassResults = Introspector.getBeanInfo(JComponent.class).getPropertyDescriptors(); final PropertyDescriptor[] result = new PropertyDescriptor[superclassResults.length+5]; System.arraycopy(superclassResults, 0, result, 0, superclassResults.length); int idx = superclassResults.length; PropertyDescriptor orientationDescriptor = new PropertyDescriptor("orientation", AbstractDefaultAxisScale.class, "getOrientation", "setOrientation"); orientationDescriptor.setValue("enumerationValues", new Object[] { "X_AXIS", Integer.valueOf(AbstractDefaultAxisScale.X_AXIS), "com.peralex.utilities.ui.graphs.graphBase.cAxis.X_AXIS", "Y_AXIS", Integer.valueOf(AbstractDefaultAxisScale.Y_AXIS), "com.peralex.utilities.ui.graphs.graphBase.cAxis.Y_AXIS", }); result[idx++] = orientationDescriptor; result[idx++] = new PropertyDescriptor("offsetFirstLabel", AbstractDefaultAxisScale.class, "isOffsetFirstLabel", "setOffsetFirstLabel"); result[idx++] = new PropertyDescriptor("drawLabels", AbstractDefaultAxisScale.class, "isDrawLabels", "setDrawLabels"); return result; } catch (IntrospectionException exc) { exc.printStackTrace(); return null; } } }
38.020408
153
0.756307
ca2aeece657242376f90d8c7612bce4ed2d38ef0
174
package br.acme.exception; @SuppressWarnings("serial") public class NomeNullException extends Exception{ public NomeNullException(String msgErro){ super(msgErro); } }
17.4
49
0.781609
05aaf7fba46664e592de2e92bb18af3689cefbb2
6,365
package rocks.inspectit.agent.java.tracing.core.adapter.http.proxy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import java.lang.reflect.Field; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import rocks.inspectit.agent.java.eum.reflection.CachedMethod; import rocks.inspectit.agent.java.tracing.core.adapter.SpanStoreAdapter; import rocks.inspectit.agent.java.tracing.core.adapter.TagsProvidingAdapter; import rocks.inspectit.agent.java.tracing.core.adapter.http.HttpResponseAdapter; import rocks.inspectit.agent.java.tracing.core.adapter.http.proxy.FutureCallbackProxy.WFutureCallback; import rocks.inspectit.agent.java.tracing.core.async.SpanStore; import rocks.inspectit.shared.all.testbase.TestBase; /** * Tests the {@link FutureCallbackProxy} class. * * @author Isabel Vico Peinado * @author Marius Oehler * */ @SuppressWarnings("PMD") public class FutureCallbackProxyTest extends TestBase { @InjectMocks FutureCallbackProxy proxy; @Mock SpanStoreAdapter spanStoreAdapter; @Mock SpanStore spanStore; @Mock FutureCallback originalCallback; @BeforeMethod public void init() throws Exception { proxy = new FutureCallbackProxy(originalCallback, spanStoreAdapter); WFutureCallback.completed = new CachedMethod<Void>(FutureCallback.class.getName(), "completed", Object.class); WFutureCallback.failed = new CachedMethod<Void>(FutureCallback.class.getName(), "failed", Exception.class); WFutureCallback.cancelled = new CachedMethod<Void>(FutureCallback.class.getName(), "cancelled"); } public void removeOriginalCallback() throws Exception { Field fieldCallback = FutureCallbackProxy.class.getDeclaredField("originalCallback"); fieldCallback.setAccessible(true); fieldCallback.set(proxy, null); } /** * Tests the {@link FutureCallbackProxy#getProxyConstructorArguments()} method. */ public static class GetProxyConstructorArguments extends FutureCallbackProxyTest { @Test public void returnsAnEmptyCollection() { Object[] args = proxy.getProxyConstructorArguments(); assertThat("Number of args returned by the constructor must be zero.", args, is(new Object[] {})); } } /** * Tests the {@link FutureCallbackProxy#completed(Object)} method. */ public static class Completed extends FutureCallbackProxyTest { @Test public void successful() { Object response = new Object(); when(spanStoreAdapter.getSpanStore()).thenReturn(spanStore); proxy.completed(response); verify(spanStoreAdapter).getSpanStore(); verify(spanStore).finishSpan((HttpResponseAdapter) any()); verify(originalCallback).completed(response); verifyNoMoreInteractions(spanStore, spanStoreAdapter, originalCallback); } @Test public void withoutSpanStore() { Object response = new Object(); proxy.completed(response); verify(spanStoreAdapter).getSpanStore(); verify(originalCallback).completed(response); verifyNoMoreInteractions(spanStoreAdapter, originalCallback); verifyZeroInteractions(spanStore); } @Test public void withoutSpanStoreAndCallback() throws Exception { Object response = new Object(); removeOriginalCallback(); proxy.completed(response); verify(spanStoreAdapter).getSpanStore(); verifyNoMoreInteractions(spanStoreAdapter); verifyZeroInteractions(spanStore, originalCallback); } } /** * Tests the {@link FutureCallbackProxy#failed(Object)} method. */ public static class Failed extends FutureCallbackProxyTest { @Test public void successful() throws Exception { Exception exception = new Exception(); when(spanStoreAdapter.getSpanStore()).thenReturn(spanStore); proxy.failed(exception); verify(spanStoreAdapter).getSpanStore(); verify(spanStore).finishSpan((TagsProvidingAdapter) any()); verify(originalCallback).failed(exception); verifyNoMoreInteractions(spanStore, spanStoreAdapter, originalCallback); } @Test public void withoutSpanStore() throws Exception { Exception exception = new Exception(); proxy.failed(exception); verify(spanStoreAdapter).getSpanStore(); verify(originalCallback).failed(exception); verifyNoMoreInteractions(spanStoreAdapter, originalCallback); verifyZeroInteractions(spanStore); } @Test public void withoutSpanStoreAndCallback() throws Exception { Exception exception = new Exception(); removeOriginalCallback(); proxy.failed(exception); verify(spanStoreAdapter).getSpanStore(); verifyNoMoreInteractions(spanStoreAdapter); verifyZeroInteractions(spanStore, originalCallback); } } /** * Tests the {@link FutureCallbackProxy#cancelled()} method. */ public static class Cancelled extends FutureCallbackProxyTest { @Test public void successful() throws Exception { when(spanStoreAdapter.getSpanStore()).thenReturn(spanStore); proxy.cancelled(); ArgumentCaptor<TagsProvidingAdapter> captor = ArgumentCaptor.forClass(TagsProvidingAdapter.class); verify(spanStoreAdapter).getSpanStore(); verify(spanStore).finishSpan(captor.capture()); verify(originalCallback).cancelled(); verifyNoMoreInteractions(spanStore, spanStoreAdapter, originalCallback); assertThat(captor.getValue().getTags(), hasKey(SpanStoreAdapter.Constants.CANCEL)); } @Test public void withoutSpanStore() throws Exception { proxy.cancelled(); verify(spanStoreAdapter).getSpanStore(); verify(originalCallback).cancelled(); verifyNoMoreInteractions(spanStoreAdapter, originalCallback); verifyZeroInteractions(spanStore); } @Test public void withoutSpanStoreAndCallback() throws Exception { removeOriginalCallback(); proxy.cancelled(); verify(spanStoreAdapter).getSpanStore(); verifyNoMoreInteractions(spanStoreAdapter); verifyZeroInteractions(spanStore, originalCallback); } } public interface FutureCallback { void completed(Object object); void failed(Exception object); void cancelled(); } }
29.882629
112
0.77769
2c3278a90d0be2fc113b992ec69921f82ddc6ebc
832
package com.example.cms; import com.example.cms.bean.UserBean; import com.example.cms.service.UserService; import org.junit.jupiter.api.Test; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest @MapperScan("com.example.demo.mapper") class DemoApplicationTests { @Autowired UserService userService; @Test void contextLoads() { UserBean userBean = userService.loginIn("wegen","123456"); System.out.println("该用户ID为: "); System.out.println(userBean.getId()); System.out.println("该用户name为: "); System.out.println(userBean.getName()); System.out.println("该用户password为: "); System.out.println(userBean.getPassword()); } }
29.714286
66
0.721154
aaf59dff672b48f7496a5fdc3982d4c06da22ba5
651
package ca.ualberta.cmput301w16t18.gamexchange; import android.widget.TextView; import junit.framework.TestCase; import org.w3c.dom.Text; /** * Created by Adam on 2016-03-14. */ public class LoginActivityTest extends TestCase { public void testOnWrongPassword() throws Exception { LoginActivity activity = new LoginActivity(); activity.onWrongPassword(); assertEquals("Error was not set for password field", "This password is incorrect", ((TextView) activity.findViewById(R.id.password)).getError()); } public void testOnNewAccount() throws Exception { //To be completed on design decisions. } }
28.304348
153
0.72043
e72f9cf107c69878d9044dc4a37a77e06afac6f9
451
package com.bolyartech.forge.server.response.forge; public class ErrorResponse extends ForgeResponse { public ErrorResponse() { super(BasicResponseCodes.Errors.ERROR, ""); } public ErrorResponse(String string) { super(BasicResponseCodes.Errors.ERROR, string); } public ErrorResponse(String string, boolean enableGzipSupport) { super(BasicResponseCodes.Errors.ERROR, string, enableGzipSupport); } }
25.055556
74
0.718404
cfc2d0fbb3f566efba68569f93488361e3ff86e1
601
package com.ustudy.exam.service; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public interface TaskAllocationService { JSONArray getQuestions(Long egsId) throws Exception; JSONArray getQuestions(Long examId, Long gradeId, Long subjectId) throws Exception; JSONObject getSchool(String schoolId) throws Exception; JSONObject getGrade(Long gradeId) throws Exception; List<Map<String, Object>> getGradeNotaskTeachers(Long gradeId) throws Exception; JSONArray getSchoolTeachers() throws Exception; }
25.041667
85
0.768719
2ec1f0decb843bacd0e2d05a9da24617d4bc9131
3,177
package com.ichuk.coffee.adapter.mine; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.ichuk.coffee.R; import com.ichuk.coffee.activity.home.CoffeeDetailActivity; import com.ichuk.coffee.bean.PointBean; import java.util.List; /** * Created by xzh on 2017/12/5. */ public class PointAdapter extends RecyclerView.Adapter<PointAdapter.ViewHolder> { private final List<PointBean.CoffeeBean> mList; private final Context mContext; public PointAdapter(Context context, List<PointBean.CoffeeBean> mList) { this.mContext = context; this.mList = mList; } /** * Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent * an item. */ @Override public PointAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = View.inflate(mContext, R.layout.item_rv_my_point, null); return new ViewHolder(itemView); } /** * Called by RecyclerView to display the data at the specified position. This method should * update the contents of the {@link ViewHolder#itemView} to reflect the item at the given * position. */ @Override public void onBindViewHolder(PointAdapter.ViewHolder holder, int position) { PointBean.CoffeeBean coffeeBean = mList.get(position); Glide.with(mContext).load(coffeeBean.getImg()).into(holder.ivCoffeeImage); holder.tvCoffeeName.setText(coffeeBean.getName()); holder.tvCoffeeIngredient.setText("成分:" + coffeeBean.getIngredient()); holder.tvCoffeePrice.setText(coffeeBean.getPrice()); holder.tvToExchange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mContext, CoffeeDetailActivity.class); intent.putExtra("page", "MY_POINT_ACTIVITY"); mContext.startActivity(intent); } }); } /** * Returns the total number of items in the data set held by the adapter. * * @return The total number of items in this adapter. */ @Override public int getItemCount() { return mList.size(); } class ViewHolder extends RecyclerView.ViewHolder { ImageView ivCoffeeImage; TextView tvCoffeeName; TextView tvCoffeeIngredient; TextView tvCoffeePrice; TextView tvToExchange; View view; public ViewHolder(View itemView) { super(itemView); view = itemView; ivCoffeeImage = itemView.findViewById(R.id.iv_coffee_image); tvCoffeeName = itemView.findViewById(R.id.tv_coffee_name); tvCoffeeIngredient = itemView.findViewById(R.id.tv_coffee_ingredient); tvCoffeePrice = itemView.findViewById(R.id.tv_coffee_price); tvToExchange = itemView.findViewById(R.id.tv_to_exchange); } } }
33.442105
95
0.68146
642bfbf83a0c691d6ae6d9e39c6380b43a9b6004
6,149
package de.tuda.stg.consys.invariants.subset.model.types; import com.google.common.collect.Maps; import de.tuda.stg.consys.invariants.subset.Logger; import de.tuda.stg.consys.invariants.subset.model.ProgramModel; import de.tuda.stg.consys.invariants.subset.utils.JDTUtils; import de.tuda.stg.consys.invariants.subset.utils.Lazy; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.lookup.*; import java.util.HashMap; public class TypeModelFactory { private final ProgramModel model; private final Lazy<IntModel> intModel; private final Lazy<BoolModel> boolModel; private final Lazy<RealModel> realModel; private final Lazy<VoidModel> voidModel; private final Lazy<StringModel> stringModel; private final HashMap<ReferenceBinding, ObjectModel> refModels; public TypeModelFactory(ProgramModel model) { this.model = model; this.intModel = Lazy.make(() -> new IntModel(model)); this.boolModel = Lazy.make(() -> new BoolModel(model)); this.realModel = Lazy.make(() -> new RealModel(model)); this.voidModel = Lazy.make(() -> new VoidModel(model)); this.refModels = Maps.newHashMap(); this.stringModel = Lazy.make(() -> new StringModel(model)); } private ObjectModel modelForRef(ReferenceBinding refBinding) { var erased = JDTUtils.erase(refBinding); if (refModels.containsKey(erased)) { return refModels.get(erased); } else { var refModel = new ObjectModel(model, erased); refModels.put(erased, refModel); return refModel; } } public TypeModel<?> typeFor(TypeBinding typeBinding) { if (typeBinding instanceof BaseTypeBinding) { BaseTypeBinding binding = (BaseTypeBinding) typeBinding; switch (binding.id) { case 2: // char case 3: // byte case 4: // short case 7: // long case 10: // int return intModel.get(); case 8: // double case 9: // float return realModel.get(); case 5: // boolean return boolModel.get(); case 6: // void return voidModel.get(); default: //throw new IllegalArgumentException("incompatible base type " + typeBinding); return new EmptyModel(model, "incompatible base type " + typeBinding); } } else if (typeBinding instanceof ArrayBinding) { ArrayBinding arrayBinding = (ArrayBinding) typeBinding; // translate element type TypeModel elementType = typeFor(arrayBinding.leafComponentType); if (elementType.hasSort()) { // build array sort from index and element type return new ArrayModel(model, elementType);// } else { return new EmptyModel(model, "incompatible array element type in " + typeBinding); } } else if (typeBinding instanceof TypeVariableBinding) { return typeFor(((TypeVariableBinding) typeBinding).superclass); } else if (typeBinding instanceof WildcardBinding) { return typeFor(((WildcardBinding) typeBinding).typeVariable().superclass); } else if (typeBinding instanceof ReferenceBinding) { ReferenceBinding refBinding = (ReferenceBinding) typeBinding; // Lookup if class is in the data model var mbClassModel = model.getClassModel(refBinding); if (mbClassModel.isPresent()) { return modelForRef(refBinding); } //... else handle some special cases if (JDTUtils.typeIsSubtypeOfName(refBinding, "java.lang.String")) { return stringModel.get(); } else if (JDTUtils.typeIsSubtypeOfName(refBinding, "java.util.Set")) { if (refBinding instanceof ParameterizedTypeBinding) { ParameterizedTypeBinding parBinding = (ParameterizedTypeBinding) refBinding; return new SetModel(model, typeFor(parBinding.arguments[0])); } else { var objectModel = modelForRef(model.bindingForJavaLangObject()); return new SetModel(model, objectModel); } } else if (JDTUtils.typeIsSubtypeOfName(refBinding, "com.google.common.collect.Multimap")) { if (refBinding instanceof ParameterizedTypeBinding) { ParameterizedTypeBinding parBinding = (ParameterizedTypeBinding) refBinding; return new MultimapModel(model, typeFor(parBinding.arguments[0]), typeFor(parBinding.arguments[1])); } else { var objectModel = modelForRef(model.bindingForJavaLangObject()); return new MultimapModel(model, objectModel, objectModel); } } else if (JDTUtils.typeIsSubtypeOfName(refBinding, "java.util.Map")) { // Map<String, BigInteger> if (refBinding instanceof ParameterizedTypeBinding) { //Map has type parameters -> use them ParameterizedTypeBinding parBinding = (ParameterizedTypeBinding) refBinding; return new MapModel(model, typeFor(parBinding.arguments[0]), typeFor(parBinding.arguments[1])); } else { //not type parameters -> Map<Object, Object> var objectModel = modelForRef(model.bindingForJavaLangObject()); return new MapModel(model, objectModel, objectModel); } } /* generic collections */ else if (JDTUtils.typeIsSubtypeOfName(refBinding, "java.util.Collection")) { if (refBinding instanceof ParameterizedTypeBinding) { ParameterizedTypeBinding parBinding = (ParameterizedTypeBinding) refBinding; return new CollectionModel(model, typeFor(parBinding.arguments[0])); } else { var objectModel = modelForRef(model.bindingForJavaLangObject()); return new CollectionModel(model, objectModel); } } /* other integer types */ else if (JDTUtils.typeIsSubtypeOfName(refBinding, "java.lang.Integer")) { return intModel.get(); } else if (JDTUtils.typeIsSubtypeOfName(refBinding, "java.math.BigInteger")) { return intModel.get(); } /* other void types */ else if (JDTUtils.typeIsSubtypeOfName(refBinding, "java.lang.Void")) { return voidModel.get(); } /* rest */ else if (typeBinding instanceof MissingTypeBinding) { Logger.warn("missing type binding: " + typeBinding.debugName()); return new MissingModel(model, (MissingTypeBinding) typeBinding); } return modelForRef(refBinding); } else { return new EmptyModel(model, "incompatible type " + typeBinding); } } public TypeModel<?> typeFor(TypeReference typeReference) { return typeFor(typeReference.resolvedType); } }
37.042169
105
0.725646
b14d75ddd87a8a5fd5a66e2b1bd0e371198fe30c
301
package com.cs360.lydiasmith.localcoffeeshop.Gallery2; import android.widget.ImageView; /* Click interface for gallery images. Listens for click events. */ public interface GalleryItemClickListener { void onGalleryItemClickListener(int position, ImageModel imageModel, ImageView imageView); }
25.083333
94
0.813953
c6d6d6f7e768467b5b88837b59d00221826f2b46
1,608
import org.junit.Test; import org.junit.Before; import org.junit.After; import org.junit.Rule; import org.junit.rules.ExpectedException; import static org.junit.Assert.*; public class MemoryTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testStore() { Memory.store("A", 9.0); Memory.store("B", new Vector("", 1.0, 2.0, 3.0)); Memory.store("C", new Matrix("", 5, 5)); } @Test public void testRetrieveType() { Memory.store("D", 9.0); Memory.store("E", new Vector("", 1.0, 2.0, 3.0)); Memory.store("F", new Matrix("", 5, 5)); assertEquals("CONSTANT", Memory.retrieveType("D").toString()); assertEquals("VECTOR", Memory.retrieveType("E").toString()); assertEquals("MATRIX", Memory.retrieveType("F").toString()); assertEquals("NULL", Memory.retrieveType("K").toString()); Memory.free("D"); Memory.free("E"); Memory.free("F"); } @Test public void testFree() { Memory.free("A"); Memory.free("B"); Memory.free("C"); Memory.store("A", 9.0); Memory.store("B", new Vector("", 1.0, 2.0, 3.0)); Memory.store("C", new Matrix("", 5, 5)); } @Test public void testRetrieve() { double a = Memory.retrieveConstant("A"); Vector b = Memory.retrieveVector("B"); Matrix c = Memory.retrieveMatrix("C"); assertEquals(9.0, a, 1e-4); assertEquals(new Vector("", 1.0, 2.0, 3.0), b); assertEquals(new Matrix("", 5, 5), c); } }
27.254237
70
0.564055
8847861c0e875ae29511a389bb815aff2d5e0eba
2,640
package com.huawei.l00379880.algs4.chapter3search; import java.util.NoSuchElementException; import java.util.TreeMap; /*********************************************************** * @Description : 泛型有序符号表 ST(Symbol Table),键必须是Comparable对象 * 默认都改是升序排列 * @author : 梁山广 * @date : 2018/1/5 15:20 * @email : liangshanguang2@gmail.com ***********************************************************/ public class P230ST<Key extends Comparable<Key>, Value> { private TreeMap<Key, Value> st; public P230ST() { st = new TreeMap<>(); } /** * 获取键key对应的值,不存在的话就返回Null */ public Value get(Key key) { if (key == null) { throw new IllegalArgumentException("传入的键key不能为null"); } return st.get(key); } /** * 将键值对存入表中(若value为空) */ public void put(Key key, Value value) { if (key == null || value == null) { // 书中实现是如果value为空那么就把这个键值对从符号表中删除 throw new IllegalArgumentException("键key或值value不能为null"); } st.put(key, value); } /** * 从表中删除key对应的键值对 */ public void delete(Key key) { if (key == null) { throw new IllegalArgumentException("传入的键key不能为null"); } st.remove(key); } /** * 键是否已经存在 */ public boolean contains(Key key) { if (key == null) { throw new IllegalArgumentException("传入的键key不能为null"); } return st.containsKey(key); } /** * 符号表长度 */ public int size() { return st.size(); } /** * 符号表是否为空 */ public boolean isEmpty() { return size() == 0; } /** * 表中所有键的集合,已排序 */ public Iterable<Key> keys() { return st.keySet(); } /** * 最小的键 */ public Key min() { return st.firstKey(); } /** * 最大的键 */ public Key max() { return st.lastKey(); } /** * 小于等于key的最大键 */ public Key floor(Key key) { if (key == null) { throw new IllegalArgumentException("传入的键key不能为null"); } Key k = st.floorKey(key); if (k == null) { throw new NoSuchElementException("找不到小于等于key的键!"); } return k; } /** * 大于等于key的最小键 */ public Key ceiling(Key key) { if (key == null) { throw new IllegalArgumentException("传入的键key不能为null"); } Key k = st.ceilingKey(key); if (k == null) { throw new NoSuchElementException("找不到小于等于key的键!"); } return k; } }
20.625
69
0.484848
cb2ed0c666bb14343f405992cf2008d514f64c14
1,137
package bl.salesbl; import java.time.LocalDate; import java.util.ArrayList; import java.util.Date; import po.GoodsItemPO; import po.SalesPO; import util.BillState; import util.BillType; import vo.GoodsItemVO; import vo.SalesVO; public class MockSalesList { ArrayList<SalesVO> salesBill=new ArrayList<SalesVO>(); ArrayList<GoodsItemVO> goodsItemList=new ArrayList<GoodsItemVO>(); GoodsItemVO gi1=new GoodsItemVO( "01","霓虹灯",null, 20, 35.0, "耐用"); GoodsItemVO gi2=new GoodsItemVO("02", "挂灯",null, 10, 35.0, "好看"); { goodsItemList.add(gi1); goodsItemList.add(gi2); SalesVO s1=new SalesVO(BillType.SALES, BillState.DRAFT, "XSD-20171022-00001", "销售商1", "业务员1", "阿强","00000003", "默认仓库",goodsItemList , 100,500, "满足客户需求", LocalDate.now().toString(),"PC-1"); SalesVO s2=new SalesVO(BillType.SALES, BillState.FAILED, "XSTHD-20171022-00002", "销售商2", "业务员2", "阿奇","00000004" ,"默认仓库",goodsItemList , 100,500, "满足客户需求", LocalDate.now().toString(),"PB-1"); salesBill.add(s1); salesBill.add(s2); } public ArrayList<SalesVO> showSales(){ return salesBill; } }
29.921053
102
0.681618
9c9b2b2eba641746b29c45ee2e2b4593c4ab692c
654
package com.twu.biblioteca; import com.twu.biblioteca.domainObjects.Movie; import java.util.ArrayList; import java.util.List; /** * Created by jyotsna on 02/03/15. */ public class MovieList { List<Movie> movies = new ArrayList<Movie>(); MovieList(){ this.movies = moviesList; } List<Movie> moviesList = new ArrayList<Movie>(){ { add(new Movie("1","movie1","director1","4/5","2011")); add(new Movie("2","movie2","director2","2/5","2003")); add(new Movie("3","movie3","director3","3/5","2001")); add(new Movie("4","movie4","director4","1/5","2000")); } }; }
25.153846
66
0.576453
6c0104cabc699b4be28881b144dcac50ce115575
1,567
package keksdose.fwkib.modules.commands.security; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.List; import keksdose.fwkib.modules.Command; public class SecureChoice implements Command { @Override public String apply(String message) { try { List<String> list = List.of(message.split(",")); SecureRandom secureRandom = SecureRandom.getInstanceStrong(); return list.size() == 0 ? "das war leer" : randomEnum(Phrases.class).insert(list.get(secureRandom.nextInt(list.size()))); } catch (NoSuchAlgorithmException e) { return "Es gab keinen guten Zufall"; } } @Override public String help(String message) { return "Endlich kannst du sicher dein Mensaessen auswählen ohne kaputte Crypto."; } private enum Phrases { WIE_WÄRE_ES("Wie wäre es mit ", "?"), MACH_DOCH("Mach doch ", "?"), ICH_WÜRDE("Ich würde ", " machen"), PROBIERS_MAL_MIT("Probiers mal mit ", "."); private String beforePhrase; private String afterPhrases; private Phrases(String beforePhrase, String afterPhrases) { this.beforePhrase = beforePhrase; this.afterPhrases = afterPhrases; } public String insert(String insertString) { return this.beforePhrase + insertString.trim() + this.afterPhrases; } } private static <T extends Enum<?>> T randomEnum(Class<T> clazz) { SecureRandom random = new SecureRandom(); int x = random.nextInt(clazz.getEnumConstants().length); return clazz.getEnumConstants()[x]; } }
29.566038
95
0.695597
393feb153185c0f2a076caee6fc7712519cce68e
1,462
// Generated by Haxe 4.0.5 package connect.util; import haxe.root.*; @SuppressWarnings(value={"rawtypes", "unchecked"}) public class Diff_parse_209__Fun extends haxe.lang.Function { public Diff_parse_209__Fun(java.lang.Object obj, haxe.ds.StringMap deletions) { //line 209 "/home/travis/build/JaviCerveraIngram/connect-haxe-sdk/connect/util/Diff.hx" super(1, 0); //line 209 "/home/travis/build/JaviCerveraIngram/connect-haxe-sdk/connect/util/Diff.hx" this.obj = obj; //line 209 "/home/travis/build/JaviCerveraIngram/connect-haxe-sdk/connect/util/Diff.hx" this.deletions = deletions; } @Override public java.lang.Object __hx_invoke1_o(double __fn_float1, java.lang.Object __fn_dyn1) { //line 209 "/home/travis/build/JaviCerveraIngram/connect-haxe-sdk/connect/util/Diff.hx" java.lang.String f1 = ( (( __fn_dyn1 == haxe.lang.Runtime.undefined )) ? (haxe.lang.Runtime.toString(__fn_float1)) : (haxe.lang.Runtime.toString(__fn_dyn1)) ); //line 209 "/home/travis/build/JaviCerveraIngram/connect-haxe-sdk/connect/util/Diff.hx" java.lang.Object tmp1 = haxe.root.Reflect.field(haxe.lang.Runtime.getField(this.obj, "d", true), f1); //line 209 "/home/travis/build/JaviCerveraIngram/connect-haxe-sdk/connect/util/Diff.hx" this.deletions.set(f1, tmp1); //line 209 "/home/travis/build/JaviCerveraIngram/connect-haxe-sdk/connect/util/Diff.hx" return null; } public java.lang.Object obj; public haxe.ds.StringMap deletions; }
36.55
161
0.747606
c2ca4a614c554fc654b3343deb0fa5665ea22b5f
336
package me.xenodevs.xeno.module.modules.player; import me.xenodevs.xeno.module.Category; import me.xenodevs.xeno.module.Module; public class FastPlace extends Module { public FastPlace() { super("FastPlace", "removes place delay lel", Category.PLAYER); } @Override public void onUpdate() { mc.rightClickDelayTimer = 0; } }
19.764706
65
0.747024
b61b745f65619c553d9d85443f3cebc2d8bb565d
12,217
package com.zwf3lbs.zwf3lbsapp; import android.app.Application; import android.content.Context; import android.content.pm.ApplicationInfo; import android.graphics.Bitmap; import android.util.Log; import android.widget.Toast; import androidx.multidex.MultiDex; import com.baidu.lbsapi.BMapManager; import com.baidu.lbsapi.MKGeneralListener; import com.baidu.mapapi.SDKInitializer; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import com.tencent.bugly.Bugly; import com.umeng.commonsdk.UMConfigure; import com.umeng.socialize.PlatformConfig; import com.zwf3lbs.map.BaiduMapViewPackage; import com.zwf3lbs.marqueeLabel.RCTMarqueeLabelPackage; import com.zwf3lbs.ocr.util.FileUtils; import com.zwf3lbs.ocr.util.LogcatHelper; import com.zwf3lbs.ocr.util.RudenessScreenHelper; import com.zwf3lbs.share.DplusReactPackage; import com.zwf3lbs.share.RNUMConfigure; import com.zwf3lbs.stream.StreamPlayerPackage; import java.lang.reflect.InvocationTargetException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; //import com.tencent.bugly.crashreport.CrashReport; public class MainApplication extends Application implements ReactApplication { private static final String TAG = "MainApplication"; private static MainApplication mInstance = null; public BMapManager mBMapManager = null; private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); // packages.add(new BaiduMapViewPackage()); packages.add(new RCTMarqueeLabelPackage()); packages.add(new StreamPlayerPackage()); // 音视频 packages.add(new DplusReactPackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); mInstance = this; //安卓屏幕自适应 new RudenessScreenHelper(this, 350, 820).activate(); //SoLoader.init(this, /* native exopackage */ false); if (!isDebug(this)) { // CrashReport.initCrashReport(getApplicationContext(), "b184ee4b59", true); Bugly.init(getApplicationContext(), "b184ee4b59", true); CrashHandler.getInstance().init(this); } FileUtils.deleteFileByTime(FileUtils.PATH_LOG, 2); LogcatHelper.getInstance().start(); SDKInitializer.initialize(getApplicationContext()); SoLoader.init(this, false); // initEngineManager(this); RNUMConfigure.init(this, "5d7f56dd3fc195a8e4000e16", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, ""); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } public void initEngineManager(Context context) { if (mBMapManager == null) { mBMapManager = new BMapManager(context); } if (!mBMapManager.init(new MyGeneralListener())) { Toast.makeText(getInstance().getApplicationContext(), "BMapManager 初始化错误!", Toast.LENGTH_LONG).show(); } Log.d("ljx", "initEngineManager"); } public static MainApplication getInstance() { return mInstance; } // 常用事件监听,用来处理通常的网络错误,授权验证错误等 public static class MyGeneralListener implements MKGeneralListener { @Override public void onGetPermissionState(int iError) { // 非零值表示key验证未通过 if (iError != 0) { // 授权Key错误: Log.i(TAG, "key认证失败"); /*Toast.makeText(MainApplication.getInstance().getApplicationContext(), "请在AndoridManifest.xml中输入正确的授权Key,并检查您的网络连接是否正常!error: " + iError, Toast.LENGTH_LONG).show();*/ } else { Log.i(TAG, "key认证成功"); /*Toast.makeText(MainApplication.getInstance().getApplicationContext(), "key认证成功", Toast.LENGTH_LONG) .show();*/ } } } /** * Loads Flipper in React Native templates. Call this in the onCreate method with something like * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); */ private static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { if (BuildConfig.DEBUG) { try { Class<?> aClass = Class.forName("com.zwf3lbs.zwf3lbsapp.ReactNativeFlipper"); aClass .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } // 配置平台 static { PlatformConfig.setWeixin("wx4f7d606dde72cc1d", "ec7c6e1c762314a596ee8606154db647"); PlatformConfig.setQQZone("1106561424", "ArH8OHXaNVU1hdB4"); } private static boolean isDebug(Context context) { try { ApplicationInfo info = context.getApplicationInfo(); return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; } catch (Exception e) { return false; } } //ocr private String serviceAddress; private String access_token;//token private String monitorId; //监控对象id private String monitorName; private String platform; private Class<?> picResultClass; private String version; //fastdfs地址 private String FASTDFS_ADDRESS; private String oldPhotoPath;//旧的人员身份证照片存储路径 private String oldDrivingLicenseFrontPhoto;//旧的行驶证正面照片地址 private String oldDrivingLicenseDuplicatePhoto;//旧的行驶证副面照片地址 private String oldDriverLicensePhoto;//旧的驾驶证照片地址 private String oldQualificationCertificatePhoto;//旧的从业资格证照片地址 //fe75ffc3-1689-4fb1-a4ec-121b2f4d47ec,64b0b86c-ce77-491a-8ad2-5a873789e23f,1ffe4d77-43a9-456a-a79b-86000a1dab96 private String professionalId; private String professionalName; //从也人员类型 private String professionalType; //ic卡岗位类型 private static String IcProfessionalType = "ed057aa7-64b8-4ec1-9b14-dbc62b4286d4"; //标记是否是新增从业人员 private boolean isAddProfessional = false; //姓名 private String idName; private String drivingLicenseNo; private String identity; private String cardNumber; private Map<String, String> professionalInfos = new LinkedHashMap<>(); private Bitmap bigPic; public ReactNativeHost getmReactNativeHost() { return mReactNativeHost; } public String getServiceAddress() { return serviceAddress; } public void setServiceAddress(String serviceAddress) { this.serviceAddress = serviceAddress; } public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getMonitorId() { return monitorId; } public void setMonitorId(String monitorId) { this.monitorId = monitorId; } public String getMonitorName() { return monitorName; } public void setMonitorName(String monitorName) { this.monitorName = monitorName; } public String getPlatform() { return platform; } public void setPlatform(String platform) { this.platform = platform; } public Class<?> getPicResultClass() { return picResultClass; } public void setPicResultClass(Class<?> picResultClass) { this.picResultClass = picResultClass; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getFASTDFS_ADDRESS() { return FASTDFS_ADDRESS; } public void setFASTDFS_ADDRESS(String FASTDFS_ADDRESS) { this.FASTDFS_ADDRESS = FASTDFS_ADDRESS; } public String getOldPhotoPath() { return oldPhotoPath; } public void setOldPhotoPath(String oldPhotoPath) { this.oldPhotoPath = oldPhotoPath; } public String getOldDrivingLicenseFrontPhoto() { return oldDrivingLicenseFrontPhoto; } public void setOldDrivingLicenseFrontPhoto(String oldDrivingLicenseFrontPhoto) { this.oldDrivingLicenseFrontPhoto = oldDrivingLicenseFrontPhoto; } public String getOldDrivingLicenseDuplicatePhoto() { return oldDrivingLicenseDuplicatePhoto; } public void setOldDrivingLicenseDuplicatePhoto(String oldDrivingLicenseDuplicatePhoto) { this.oldDrivingLicenseDuplicatePhoto = oldDrivingLicenseDuplicatePhoto; } public String getOldDriverLicensePhoto() { return oldDriverLicensePhoto; } public void setOldDriverLicensePhoto(String oldDriverLicensePhoto) { this.oldDriverLicensePhoto = oldDriverLicensePhoto; } public String getOldQualificationCertificatePhoto() { return oldQualificationCertificatePhoto; } public void setOldQualificationCertificatePhoto(String oldQualificationCertificatePhoto) { this.oldQualificationCertificatePhoto = oldQualificationCertificatePhoto; } public String getProfessionalId() { return professionalId; } public void setProfessionalId(String professionalId) { this.professionalId = professionalId; } public String getProfessionalName() { return professionalName; } public void setProfessionalName(String professionalName) { this.professionalName = professionalName; } public String getProfessionalType() { return professionalType; } public void setProfessionalType(String professionalType) { this.professionalType = professionalType; } public static String getIcProfessionalType() { return IcProfessionalType; } public static void setIcProfessionalType(String icProfessionalType) { IcProfessionalType = icProfessionalType; } public boolean isAddProfessional() { return isAddProfessional; } public void setAddProfessional(boolean addProfessional) { isAddProfessional = addProfessional; } public String getIdName() { return idName; } public void setIdName(String idName) { this.idName = idName; } public String getDrivingLicenseNo() { return drivingLicenseNo; } public void setDrivingLicenseNo(String drivingLicenseNo) { this.drivingLicenseNo = drivingLicenseNo; } public String getIdentity() { return identity; } public void setIdentity(String identity) { this.identity = identity; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public Map<String, String> getProfessionalInfos() { return professionalInfos; } public void setProfessionalInfos(Map<String, String> professionalInfos) { this.professionalInfos = professionalInfos; } public Bitmap getBigPic() { return bigPic; } public void setBigPic(Bitmap bigPic) { this.bigPic = bigPic; } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }
28.881797
125
0.678726
5b6dc983054e8fe304b4314ba0d5d3f6a6232fd6
1,288
package com.hyphenate.chat.adapter; import com.hyphenate.chat.adapter.message.EMAMessage; import java.util.List; public abstract class EMAChatManagerListener extends EMABase implements EMAChatManagerListenerInterface { public EMAChatManagerListener() { nativeInit(); } public void finalize() throws Throwable { nativeFinalize(); super.finalize(); } native void nativeFinalize(); native void nativeInit(); public void onMessageAttachmentsStatusChanged(EMAMessage paramEMAMessage, EMAError paramEMAError) {} public void onMessageStatusChanged(EMAMessage paramEMAMessage, EMAError paramEMAError) {} public void onReceiveCmdMessages(List<EMAMessage> paramList) {} public void onReceiveHasDeliveredAcks(List<EMAMessage> paramList) {} public void onReceiveHasReadAcks(List<EMAMessage> paramList) {} public void onReceiveMessages(List<EMAMessage> paramList) {} public void onReceiveRecallMessages(List<EMAMessage> paramList) {} public void onUpdateConversationList(List<EMAConversation> paramList) {} } /* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/hyphenate/chat/adapter/EMAChatManagerListener.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
27.404255
132
0.753106
e885f438cfc78e6c10e0d3c53010838d9f5977a1
2,235
/** * Copyright Pravega Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pravega.common.io; import io.pravega.common.util.BufferView; import java.io.IOException; /** * Defines an object meant for serializing data (usually an {@link java.io.OutputStream}) that can write various inputs * more efficiently than otherwise (i.e., byte-by-byte copy). */ public interface DirectDataOutput { /** * Includes the given {@link BufferView}. * * @param buffer The {@link BufferView} to include. * @throws IOException If an IO Exception occurred. */ void writeBuffer(BufferView buffer) throws IOException; /** * Writes the given value as a 16 bit Short. Every effort will be made to write this using efficient techniques * (such as making use of intrinsic instructions). * * @param shortValue The Short value to write. * @throws IOException If an IO Exception occurred. */ void writeShort(int shortValue) throws IOException; /** * Writes the given value as a 32 bit Integer. Every effort will be made to write this using efficient techniques * (such as making use of intrinsic instructions). * * @param intValue The Integer value to write. * @throws IOException If an IO Exception occurred. */ void writeInt(int intValue) throws IOException; /** * Writes the given value as a 64 bit Long. Every effort will be made to write this using efficient techniques * (such as making use of intrinsic instructions). * * @param longValue The Long value to write. * @throws IOException If an IO Exception occurred. */ void writeLong(long longValue) throws IOException; }
36.639344
119
0.704251
3a4170b56f012226c0cf7e704ed1a766ff375725
16,572
package com.vcd.immersive.omafplayer; import android.Manifest; import android.Manifest.permission; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.google.vr.ndk.base.DaydreamApi; import com.vcd.immersive.omafplayer.Rendering.Mesh; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; /** * Basic Activity to hold {@link MonoscopicView} and render a 360 video in 2D. * * Most of this Activity's code is related to Android & VR permission handling. The real work is in * MonoscopicView. * * The default intent for this Activity will load a 360 placeholder panorama. For more options on * how to load other media using a custom Intent, see {@link MediaLoader}. */ public class VideoActivity extends Activity { private static final String TAG = "VideoActivity"; private static final int READ_EXTERNAL_STORAGE_PERMISSION_ID = 1; private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_ID = 2; private MonoscopicView videoView; private TextView urlText; private TextView sourceTypeText; private TextView extractorText; private TextView cachePathText; private TextView maxWidthText; private TextView maxHeightText; private TextView hasPredictText; private TextView predictNameText; private TextView predictPathText; private TextView hasCatchUpText; private TextView catchupTimesText; private TextView catchupMaxWidthText; private TextView catchupMaxHeightText; private boolean isInputConfigFinished = false; private boolean isPermissionRequired = false; /** * Checks that the appropriate permissions have been granted. Otherwise, the sample will wait * for the user to grant the permission. * * @param savedInstanceState unused in this sample but it could be used to track video position */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getApplicationContext().getExternalFilesDir(""); setContentView(R.layout.video_activity); // Configure the MonoscopicView which will render the video and UI. videoView = (MonoscopicView) findViewById(R.id.video_view); VideoUiView videoUi = (VideoUiView) findViewById(R.id.video_ui_view); videoUi.setVrIconClickListener( new OnClickListener() { @Override public void onClick(View v) { // Convert the Intent used to launch the 2D Activity into one that can launch the VR // Activity. This flow preserves the extras and data in the Intent. DaydreamApi api = DaydreamApi.create(VideoActivity.this); if (api != null){ // Launch the VR Activity with the proper intent. Intent intent = DaydreamApi.createVrIntent( new ComponentName(VideoActivity.this, VrVideoActivity.class)); intent.setData(getIntent().getData()); intent.putExtra( MediaLoader.MEDIA_FORMAT_KEY, getIntent().getIntExtra(MediaLoader.MEDIA_FORMAT_KEY, Mesh.MEDIA_MONOSCOPIC)); api.launchInVr(intent); api.close(); } else { // Fall back for devices that don't have Google VR Services. This flow should only // be used for older Cardboard devices. Intent intent = new Intent(getIntent()).setClass(VideoActivity.this, VrVideoActivity.class); intent.removeCategory(Intent.CATEGORY_LAUNCHER); intent.setFlags(0); // Clear any flags from the previous intent. startActivity(intent); } // See VrVideoActivity's launch2dActivity() for more info about why this finish() call // may be required. finish(); } }); videoView.initialize(videoUi); // Boilerplate for checking runtime permissions in Android. if (ContextCompat.checkSelfPermission(this, permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { View button = findViewById(R.id.permission_button); button.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { ActivityCompat.requestPermissions( VideoActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_PERMISSION_ID); } }); // The user can click the button to request permission but we will also click on their behalf // when the Activity is created. button.callOnClick(); } else { // Permission has already been granted. isPermissionRequired = true; if (isInputConfigFinished) { initializeActivity(); } } QueryInputParams(); } /** Handles the user accepting the permission. */ @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) { if (requestCode == READ_EXTERNAL_STORAGE_PERMISSION_ID) { if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) { isPermissionRequired = true; if (isInputConfigFinished) { initializeActivity(); } } } if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_ID) { if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) { isPermissionRequired = true; if (isInputConfigFinished) { initializeActivity(); } } } } /** * Normal apps don't need this. However, since we use adb to interact with this sample, we * want any new adb Intents to be routed to the existing Activity rather than launching a new * Activity. */ @Override protected void onNewIntent(Intent intent) { // Save the new Intent which may contain a new Uri. Then tear down & recreate this Activity to // load that Uri. setIntent(intent); recreate(); } /** Initializes the Activity only if the permission has been granted and input parameters configured. */ private void initializeActivity() { ViewGroup root = (ViewGroup) findViewById(R.id.activity_root); for (int i = 0; i < root.getChildCount(); ++i) { root.getChildAt(i).setVisibility(View.VISIBLE); } findViewById(R.id.permission_button).setVisibility(View.GONE); findViewById(R.id.topTitle).setVisibility(View.GONE); findViewById(R.id.relativeLayout1).setVisibility(View.GONE); findViewById(R.id.relativeLayout2).setVisibility(View.GONE); findViewById(R.id.relativeLayout3).setVisibility(View.GONE); findViewById(R.id.relativeLayout4).setVisibility(View.GONE); findViewById(R.id.relativeLayout5).setVisibility(View.GONE); findViewById(R.id.relativeLayout6).setVisibility(View.GONE); findViewById(R.id.relativeLayout7).setVisibility(View.GONE); findViewById(R.id.relativeLayout8).setVisibility(View.GONE); findViewById(R.id.relativeLayout9).setVisibility(View.GONE); findViewById(R.id.relativeLayout10).setVisibility(View.GONE); findViewById(R.id.relativeLayout11).setVisibility(View.GONE); findViewById(R.id.relativeLayout12).setVisibility(View.GONE); findViewById(R.id.relativeLayout13).setVisibility(View.GONE); findViewById(R.id.loginButton).setVisibility(View.GONE); videoView.loadMedia(getIntent()); } private void QueryInputParams() { urlText = findViewById(R.id.text_url); sourceTypeText = findViewById(R.id.text_sourceType); extractorText = findViewById(R.id.text_extractor); cachePathText = findViewById(R.id.text_cachePath); maxWidthText = findViewById(R.id.text_maxWidth); maxHeightText = findViewById(R.id.text_maxHeight); hasPredictText = findViewById(R.id.text_hasPredict); predictNameText= findViewById(R.id.text_predictName); predictPathText= findViewById(R.id.text_predictPath); hasCatchUpText = findViewById(R.id.text_hasCatchup); catchupTimesText = findViewById(R.id.text_catchupTimes); catchupMaxWidthText = findViewById(R.id.text_maxCatchupWidth); catchupMaxHeightText = findViewById(R.id.text_maxCatchupHeight); Button btn = findViewById(R.id.loginButton); SetDefaultValueFromCfgFile(); btn.setOnClickListener(new InputOnClickListener()); } private void SetDaultValues() { // default value for the first time urlText.setText("http://x.x.x.x:x/xxx/Test.mpd"); sourceTypeText.setText("0"); extractorText.setText("false"); cachePathText.setText("sdcard/Android/data/tmp/"); maxWidthText.setText("4096"); maxHeightText.setText("3200"); hasPredictText.setText("false"); predictNameText.setText(""); predictPathText.setText(""); hasCatchUpText.setText("false"); catchupTimesText.setText("1"); catchupMaxWidthText.setText("3200"); catchupMaxHeightText.setText("3200"); } //read from cfg file on create private void SetDefaultValueFromCfgFile() { StringBuilder stringBuilder = new StringBuilder(); try { //1. load cfg file String path = getApplicationContext().getExternalFilesDir("").getPath(); File inputfile = new File(path + "/cfg.json"); if (!inputfile.exists()) { Log.i(TAG, "First time to run the activity! Use default values!"); SetDaultValues(); return; } FileInputStream inputStream = new FileInputStream(inputfile); InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(isr); String jsonLines; while ((jsonLines = bufferedReader.readLine()) != null) { stringBuilder.append(jsonLines); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //2. set text according to json file String cfgJsonStr = stringBuilder.toString(); JSONObject cfgJsonObject = null; try { cfgJsonObject = new JSONObject(cfgJsonStr); } catch (JSONException e) { e.printStackTrace(); } try { urlText.setText(cfgJsonObject.getString("url")); sourceTypeText.setText(cfgJsonObject.getInt("sourceType") + ""); extractorText.setText(cfgJsonObject.getBoolean("enableExtractor") + ""); cachePathText.setText(cfgJsonObject.getString("cachePath")); maxWidthText.setText(cfgJsonObject.getInt("maxVideoDecodeWidth") + ""); maxHeightText.setText(cfgJsonObject.getInt("maxVideoDecodeHeight") + ""); hasPredictText.setText(cfgJsonObject.getBoolean("hasPredict") + ""); predictNameText.setText(cfgJsonObject.getString("predictName")); predictPathText.setText(cfgJsonObject.getString("predictPath")); hasCatchUpText.setText(cfgJsonObject.getBoolean("hasCatchup") + ""); catchupTimesText.setText(cfgJsonObject.getInt("catchupTimes") + ""); catchupMaxWidthText.setText(cfgJsonObject.getInt("maxCatchupWidth") + ""); catchupMaxHeightText.setText(cfgJsonObject.getInt("maxCatchupHeight") + ""); } catch (JSONException e) { e.printStackTrace(); } } // write to cfg file when on click private void SetCfgInFileFromInputParams() { try { //1. open/create cfg file String path = getApplicationContext().getExternalFilesDir("").getPath(); File inputfile = new File(path + "/cfg.json"); if (!inputfile.exists()) { Log.i(TAG, "The first time to use activity! create a cfg file to store history settings!"); inputfile.createNewFile(); } FileOutputStream outputStream = new FileOutputStream(inputfile); OutputStreamWriter osw = new OutputStreamWriter(outputStream, "UTF-8"); //2. fill input params to file JSONObject inputObj = new JSONObject(); inputObj.put("url", urlText.getText().toString()); inputObj.put("sourceType", sourceTypeText.getText().toString()); inputObj.put("enableExtractor", extractorText.getText().toString()); inputObj.put("cachePath", cachePathText.getText().toString()); inputObj.put("maxVideoDecodeWidth", maxWidthText.getText().toString()); inputObj.put("maxVideoDecodeHeight", maxHeightText.getText().toString()); inputObj.put("hasPredict", hasPredictText.getText().toString()); inputObj.put("predictName", predictNameText.getText().toString()); inputObj.put("predictPath", predictPathText.getText().toString()); inputObj.put("hasCatchup", hasCatchUpText.getText().toString()); inputObj.put("catchupTimes", catchupTimesText.getText().toString()); inputObj.put("maxCatchupWidth", catchupMaxWidthText.getText().toString()); inputObj.put("maxCatchupHeight", catchupMaxHeightText.getText().toString()); // fill in default values at the first time if (!inputObj.has("windowWidth")) inputObj.put("windowWidth", 960); if (!inputObj.has("windowHeight")) inputObj.put("windowHeight", 960); if (!inputObj.has("viewportHFOV")) inputObj.put("viewportHFOV", 80); if (!inputObj.has("viewportVFOV")) inputObj.put("viewportVFOV", 80); if (!inputObj.has("viewportWidth")) inputObj.put("viewportWidth", 960); if (!inputObj.has("viewportHeight")) inputObj.put("viewportHeight", 960); System.out.println("input " + inputObj.toString()); osw.write(inputObj.toString()); osw.flush(); osw.close(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } @Override protected void onResume() { super.onResume(); videoView.onResume(); } @Override protected void onPause() { // MonoscopicView is a GLSurfaceView so it needs to pause & resume rendering. It's also // important to pause MonoscopicView's sensors & the video player. videoView.onPause(); super.onPause(); } @Override protected void onDestroy() { videoView.destroy(); super.onDestroy(); } private class InputOnClickListener implements OnClickListener { @Override public void onClick(View v) { SetCfgInFileFromInputParams(); isInputConfigFinished = true; if (isPermissionRequired) { initializeActivity(); } } } }
44.668464
114
0.626961
54ef578def0d3e2c233c66da61203ebf7acd28b2
870
package model; import view.Sprite; /** * An object should implement IDrawable if it has a sprite associated with it. */ public interface IDrawable { /** * Returns sprite associated with an game object. * @return sprite associated with the game object. */ Sprite getSprite(); /** * Should return true if the object is visible. * @return true if the object is visible. */ boolean getVisible(); /** * @param v true if object should be drawn */ void setVisible(boolean v); /** * @return current X cord */ double getX(); /** * @return current X cord */ double getY(); /** * @return current angle */ double getAngle(); /** * @param newX new X cord */ void setX( double newX ); /** * @param newY new Y cord */ void setY( double newY ); /** * @param newAngle new angle */ void setAngle( double newAngle ); }
15.263158
78
0.629885
8e96fddd069728d6628a97683fc011125e836579
1,573
/* * 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 brooklyn.entity.proxying; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import brooklyn.entity.Entity; /** * A pointer to the default implementation of an entity. * * A common naming convention is for the implementation class to have the suffix "Impl", * but this is not required. * * See {@link EntityTypeRegistry} for how to override the implementation to be used, if * the class referenced by this annotation is not desired. * * @author aled */ @Retention(RUNTIME) @Target(TYPE) public @interface ImplementedBy { /** * The implementation type. */ Class<? extends Entity> value(); }
32.102041
88
0.748252
f49477a9728612c5c77eb07850565f95e3a7c896
1,924
package rti.meta.openvcall.ui.layout; import android.app.Activity; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import rti.meta.openvcall.R; import rti.meta.openvcall.model.Message; public class InChannelMessageListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private ArrayList<Message> mMsgList; private final LayoutInflater mInflater; public InChannelMessageListAdapter(Activity activity, ArrayList<Message> list) { mInflater = activity.getLayoutInflater(); mMsgList = list; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = mInflater.inflate(R.layout.in_channel_message, parent, false); return new MessageHolder(v); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { Message msg = mMsgList.get(position); MessageHolder myHolder = (MessageHolder) holder; String sender = msg.getSender().name; if (TextUtils.isEmpty(sender)) { myHolder.itemView.setBackgroundResource(R.drawable.rounded_bg_blue); } else { myHolder.itemView.setBackgroundResource(R.drawable.rounded_bg); } myHolder.mMsgContent.setText(msg.getContent()); } @Override public int getItemCount() { return mMsgList.size(); } @Override public long getItemId(int position) { return mMsgList.get(position).hashCode(); } public class MessageHolder extends RecyclerView.ViewHolder { TextView mMsgContent; MessageHolder(View v) { super(v); mMsgContent = (TextView) v.findViewById(R.id.msg_content); } } }
28.716418
96
0.702183
d59cb49eb709f8b15318d05c07f35ac266c37749
380
package io.egen.movieflix.repository; import java.util.List; import io.egen.movieflix.entity.Users; public interface UserRepository { public Users create(Users user); public List<Users> findAll(); public Users findById(String id); public Users update(Users user); public void delete(Users user); public Users login(String username, String password); }
22.352941
55
0.739474
474cdbe76c10948b4c727a99aeea3be8719c8adc
32,095
package com.scriptsbundle.nokri.activities; import java.io.IOException; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; import com.google.gson.JsonObject; import com.scriptsbundle.nokri.R; import com.scriptsbundle.nokri.candidate.dashboard.Nokri_CandidateDashboardActivity; import com.scriptsbundle.nokri.employeer.dashboard.Nokri_EmployeerDashboardActivity; import com.scriptsbundle.nokri.employeer.jobs.fragments.Nokri_JobDetailFragment; import com.scriptsbundle.nokri.manager.Nokri_DialogManager; import com.scriptsbundle.nokri.manager.Nokri_FontManager; import com.scriptsbundle.nokri.manager.Nokri_RequestHeaderManager; import com.scriptsbundle.nokri.manager.Nokri_SharedPrefManager; import com.scriptsbundle.nokri.manager.Nokri_ToastManager; import com.scriptsbundle.nokri.network.Nokri_ServiceGenerator; import com.scriptsbundle.nokri.rest.RestService; import com.scriptsbundle.nokri.utils.Nokri_Config; import com.scriptsbundle.nokri.utils.Nokri_Utils; import belka.us.androidtoggleswitch.widgets.BaseToggleSwitch; import belka.us.androidtoggleswitch.widgets.ToggleSwitch; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Nokri_LinkedinProfileActivity extends Activity { private Nokri_DialogManager dialogManager; private static final String PROFILE_URL = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,public-profile-url,picture-url,email-address,picture-urls::(original))"; private static final String OAUTH_ACCESS_TOKEN_PARAM ="oauth2_access_token"; private static final String QUESTION_MARK = "?"; private static final String EQUALS = "="; private String selectedOption = ""; private String[] accountTypes = new String[2]; private ProgressDialog pd; public static boolean IS_SOURCE_LOGIN = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //Request basic profile of the user SharedPreferences preferences = this.getSharedPreferences("user_info", 0); String accessToken = preferences.getString("accessToken", null); if(accessToken!=null){ String profileUrl = getProfileUrl(accessToken); new GetProfileRequestAsyncTask().execute(profileUrl); } } private static final String getProfileUrl(String accessToken){ return PROFILE_URL +QUESTION_MARK +OAUTH_ACCESS_TOKEN_PARAM+EQUALS+accessToken; } private class GetProfileRequestAsyncTask extends AsyncTask<String, Void, JSONObject>{ @Override protected void onPreExecute(){ pd = ProgressDialog.show(Nokri_LinkedinProfileActivity.this, "", Nokri_LinkedinProfileActivity.this.getString(R.string.loading),true); } @Override protected JSONObject doInBackground(String... urls) { if(urls.length>0){ String url = urls[0]; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); httpget.setHeader("x-li-format", "json"); try{ HttpResponse response = httpClient.execute(httpget); if(response!=null){ //If status is OK 200 if(response.getStatusLine().getStatusCode()==200){ String result = EntityUtils.toString(response.getEntity()); //Convert the string result to a JSON Object return new JSONObject(result); } } }catch(IOException e){ Log.e("Authorize","Error Http response "+e.getLocalizedMessage()); } catch (JSONException e) { Log.e("Authorize","Error Http response "+e.getLocalizedMessage()); } } return null; } @Override protected void onPostExecute(JSONObject data){ if(pd!=null && pd.isShowing()){ pd.dismiss(); } if(data!=null){ try { // String welcomeTextString = String.format(data.getString("firstName"),data.getString("lastName"),data.getString("headline")); if(IS_SOURCE_LOGIN) { Nokri_SharedPrefManager.saveEmail(data.getString("emailAddress"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveName(data.getString("firstName") + " " + data.getString("lastName"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveHeadline(data.getString("headline"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveLinkedinPublicProfile(data.getString("publicProfileUrl"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveProfileImage(data.getString("pictureUrls"), Nokri_LinkedinProfileActivity.this); nokri_postSocialSignin(data.getString("emailAddress"), "social"); } else { if(Nokri_SharedPrefManager.isAccountPublic(Nokri_LinkedinProfileActivity.this)) { Nokri_SharedPrefManager.saveEmail(data.getString("emailAddress"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveName(data.getString("firstName") + " " + data.getString("lastName"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveHeadline(data.getString("headline"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveProfileImage(data.getString("pictureUrls"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveLinkedinPublicProfile(data.getString("publicProfileUrl"), Nokri_LinkedinProfileActivity.this); nokri_postSocialSigninFromApplyJob(data.getString("emailAddress"),"social"); } else { Nokri_SharedPrefManager.saveLinkedinPublicProfile(data.getString("publicProfileUrl"), Nokri_LinkedinProfileActivity.this); nokri_applyjobLinkedIn(); } } } catch (JSONException e) { Log.e("Authorize","Error Parsing json "+e.getLocalizedMessage()); } } } }; private void nokri_postSocialSigninFromApplyJob(String email, final String type) { Log.d("socail", email + type); dialogManager = new Nokri_DialogManager(); dialogManager.showAlertDialog(this); JsonObject params = new JsonObject(); params.addProperty("type", type); params.addProperty("email", email); RestService restService = Nokri_ServiceGenerator.createService(RestService.class, email, email, this); // RestService restService = Nokri_ServiceGenerator.createService(RestService.class); Call<ResponseBody> myCall = restService.postSocialLogin(params, Nokri_RequestHeaderManager.addSocialHeaders()); myCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, @NonNull Response<ResponseBody> responseObject) { if (responseObject.isSuccessful()) { try { JSONObject respone = new JSONObject(responseObject.body().string()); Log.d("socail", respone.toString()); if (respone.getBoolean("success")) { JSONObject data = respone.getJSONObject("data"); Log.d("chussss",data.getString("acount_type")); if (data.getString("acount_type").trim().equals("1")) { Log.d("chussss","inside"); Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,"Employeers cannot apply for job"); dialogManager.hideAlertDialog(); Nokri_SharedPrefManager.saveLoginType(type, Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.savePassword("pass", Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveId(data.getString("id"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.savePhone(data.getString("phone"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveAccountType("employeer", Nokri_LinkedinProfileActivity.this); dialogManager.hideAlertDialog(); Intent intent = new Intent(Nokri_LinkedinProfileActivity.this, Nokri_EmployeerDashboardActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return; } else{ Nokri_SharedPrefManager.saveLoginType(type, Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.savePassword("pass", Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveId(data.getString("id"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.savePhone(data.getString("phone"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveAccountType("candidate", Nokri_LinkedinProfileActivity.this); nokri_postAccountType("0"); } } else { Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,respone.getString("message")); dialogManager.hideAlertDialog(); Nokri_LinkedinProfileActivity.super.onBackPressed(); } } catch (IOException e) { Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,e.getMessage()); dialogManager.hideAlertDialog(); e.printStackTrace(); } catch (JSONException e) { Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,e.getMessage()); dialogManager.hideAlertDialog(); e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { dialogManager.showCustom(t.getMessage()); dialogManager.hideAlertDialog(); Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,t.getMessage()); } }); } private void nokri_applyjobLinkedIn() { dialogManager = new Nokri_DialogManager(); JsonObject object = new JsonObject(); object.addProperty("job_id", Nokri_JobDetailFragment.JOB_ID); object.addProperty("url", Nokri_SharedPrefManager.getLinkedInPublicProfile(this)); RestService restService = Nokri_ServiceGenerator.createService(RestService.class, Nokri_SharedPrefManager.getEmail(this), Nokri_SharedPrefManager.getPassword(this),this); Call<ResponseBody> myCall; if(Nokri_SharedPrefManager.isSocialLogin(this)) { myCall = restService.applyJobLinkedin(object, Nokri_RequestHeaderManager.addSocialHeaders()); } else { myCall = restService.applyJobLinkedin(object, Nokri_RequestHeaderManager.addHeaders()); } // Call<ResponseBody> myCall = restService.postCandidateSkills(object, Nokri_RequestHeaderManager.addHeaders()); myCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObject) { if (responseObject.isSuccessful()) { try { JSONObject response = new JSONObject(responseObject.body().string()); Log.v("response", responseObject.message()); if (response.getBoolean("success")) { Nokri_SharedPrefManager.saveAccountType("candidate", Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveLoginType("social", Nokri_LinkedinProfileActivity.this); Intent intent = new Intent(Nokri_LinkedinProfileActivity.this, Nokri_CandidateDashboardActivity.class); intent.putExtra("linkedin",true); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); Nokri_ToastManager.showLongToast(Nokri_LinkedinProfileActivity.this,response.getString("message")); dialogManager.hideAlertDialog(); } else { /*Nokri_SharedPrefManager.saveAccountType("candidate", Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveLoginType("social", Nokri_LinkedinProfileActivity.this); Intent intent = new Intent(Nokri_LinkedinProfileActivity.this, Nokri_CandidateDashboardActivity.class); intent.putExtra("linkedin",true); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish();*/ Nokri_ToastManager.showLongToast(Nokri_LinkedinProfileActivity.this,response.getString("message")); dialogManager.hideAlertDialog(); Nokri_LinkedinProfileActivity.super.onBackPressed(); } } catch (JSONException e) { Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,e.getMessage()); dialogManager.hideAlertDialog(); e.printStackTrace(); } catch (IOException e) { Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,e.getMessage()); dialogManager.hideAlertDialog(); e.printStackTrace(); } } else { Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,responseObject.message()); dialogManager.hideAlertDialog(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,t.getMessage()); dialogManager.hideAlertDialog(); } }); } private void nokri_postSocialSignin(String email, final String type) { Log.d("socail", email + type); dialogManager = new Nokri_DialogManager(); dialogManager.showAlertDialog(this); JsonObject params = new JsonObject(); params.addProperty("type", type); params.addProperty("email", email); RestService restService = Nokri_ServiceGenerator.createService(RestService.class, email, email, Nokri_LinkedinProfileActivity.this); // RestService restService = Nokri_ServiceGenerator.createService(RestService.class); Call<ResponseBody> myCall = restService.postSocialLogin(params, Nokri_RequestHeaderManager.addSocialHeaders()); myCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, @NonNull Response<ResponseBody> responseObject) { if (responseObject.isSuccessful()) { try { JSONObject respone = new JSONObject(responseObject.body().string()); Log.d("socail", respone.toString()); if (respone.getBoolean("success")) { JSONObject data = respone.getJSONObject("data"); Nokri_SharedPrefManager.saveEmail(data.getString("user_email"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveLoginType(type, Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.savePassword("pass", Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveId(data.getString("id"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveName(data.getString("display_name"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.savePhone(data.getString("phone"), Nokri_LinkedinProfileActivity.this); Nokri_SharedPrefManager.saveProfileImage(data.getString("profile_img"), Nokri_LinkedinProfileActivity.this); // Default Sigin in type for testing // if(isCallbackFromLinkedin) //--------------------------------------------------------------------- if (data.getString("acount_type").equals("0")) { Nokri_SharedPrefManager.saveAccountType("candidate", Nokri_LinkedinProfileActivity.this); startActivity(new Intent(Nokri_LinkedinProfileActivity.this, Nokri_CandidateDashboardActivity.class)); finish(); } else if (data.getString("acount_type").equals("1")) { Nokri_SharedPrefManager.saveAccountType("employeer", Nokri_LinkedinProfileActivity.this); startActivity(new Intent(Nokri_LinkedinProfileActivity.this, Nokri_EmployeerDashboardActivity.class)); finish(); } else { nokri_showAccountTypePopup(); } Nokri_ToastManager.showLongToast(Nokri_LinkedinProfileActivity.this,respone.getString("message")); dialogManager.hideAlertDialog(); /*startActivity(new Intent(Nokri_SigninActivity.this, Nokri_CandidateDashboardActivity.class)); finish();*/ } else { Log.d("socail", responseObject.toString() + "error"); Nokri_ToastManager.showLongToast(Nokri_LinkedinProfileActivity.this,respone.getString("message")); dialogManager.hideAlertDialog(); Nokri_LinkedinProfileActivity.super.onBackPressed(); } } catch (IOException e) { dialogManager.showCustom(e.getMessage()); dialogManager.hideAfterDelay(); // Nokri_DialogManager.hideAlertDialog(); e.printStackTrace(); } catch (JSONException e) { dialogManager.showCustom(e.getMessage()); dialogManager.hideAfterDelay(); // Nokri_DialogManager.hideAlertDialog(); e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { dialogManager.showCustom(t.getMessage()); dialogManager.hideAlertDialog(); } }); } private void nokri_showAccountTypePopup() { dialogManager = new Nokri_DialogManager(); dialogManager.showAlertDialog(this); RestService restService = Nokri_ServiceGenerator.createService(RestService.class); Call<ResponseBody> myCall = restService.getAccoutTypeSelector(Nokri_RequestHeaderManager.addHeaders()); myCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObject) { if (responseObject.isSuccessful()) { try { Log.d("responce", responseObject.toString()); JSONObject respone = new JSONObject(responseObject.body().string()); if (respone.getBoolean("success")) { JSONObject data = respone.getJSONObject("data"); ArrayList<String> list = new ArrayList(); final Dialog dialog = new Dialog(Nokri_LinkedinProfileActivity.this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setContentView(R.layout.account_type_popup); final TextView titleTextView = dialog.findViewById(R.id.txt_title); TextView headingTextView = dialog.findViewById(R.id.txt_heading); final ToggleSwitch toggleSwitch = dialog.findViewById(R.id.toogle_switch); dialog.findViewById(R.id.title_text_container).setBackgroundColor(Color.parseColor(Nokri_Config.APP_COLOR)); list.add(data.getString("btn_cand")); list.add(data.getString("btn_emp")); headingTextView.setText(data.getString("desc")); toggleSwitch.setLabels(list); toggleSwitch.setActiveBgColor(Color.parseColor(Nokri_Config.APP_COLOR)); Button okButton = dialog.findViewById(R.id.btn_ok); Nokri_Utils.setRoundButtonColor(Nokri_LinkedinProfileActivity.this,okButton); okButton.setText(data.getString("continue")); accountTypes[0] = data.getString("btn_cand"); accountTypes[1] = data.getString("btn_emp"); titleTextView.setText( accountTypes[0]); Nokri_FontManager innerFontManager = new Nokri_FontManager(); innerFontManager.nokri_setMonesrratSemiBioldFont(titleTextView,getAssets()); innerFontManager.nokri_setOpenSenseFontTextView(headingTextView,getAssets()); innerFontManager.nokri_setOpenSenseFontButton(okButton,getAssets()); Nokri_Utils.setRoundButtonColor(Nokri_LinkedinProfileActivity.this,okButton); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { dialogManager.hideAlertDialog(); } }); okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedOption = toggleSwitch.getCheckedTogglePosition()+""; nokri_postAccountTypePopup(selectedOption); dialog.dismiss(); } }); toggleSwitch.setOnToggleSwitchChangeListener(new BaseToggleSwitch.OnToggleSwitchChangeListener() { @Override public void onToggleSwitchChangeListener(int position, boolean isChecked) { switch (position) { case 0: titleTextView.setText( accountTypes[position]); break; case 1: titleTextView.setText( accountTypes[position]); break; } } }); dialog.show(); } else { Nokri_ToastManager.showLongToast(Nokri_LinkedinProfileActivity.this,respone.getString("message")); } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } dialogManager.hideAlertDialog(); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { // dialog.showError(); dialogManager.showError(); new Handler().postDelayed(new Runnable() { @Override public void run() { onBackPressed(); } }, 2500); } }); } private void nokri_postAccountTypePopup(final String type) { dialogManager = new Nokri_DialogManager(); dialogManager.showAlertDialog(this); JsonObject params = new JsonObject(); params.addProperty("user_type", type); params.addProperty("user_id", Nokri_SharedPrefManager.getId(this)); RestService restService = Nokri_ServiceGenerator.createService(RestService.class, Nokri_SharedPrefManager.getEmail(this), "password", Nokri_LinkedinProfileActivity.this); Call<ResponseBody> myCall = restService.postAccountTypleSelector(params, Nokri_RequestHeaderManager.addHeaders()); myCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, @NonNull Response<ResponseBody> responseObject) { if (responseObject.isSuccessful()) { try { JSONObject respone = new JSONObject(responseObject.body().string()); Log.d("response", respone.toString()); if (respone.getBoolean("success")) { if (type.equals("0")) { Nokri_SharedPrefManager.saveAccountType("candidate", Nokri_LinkedinProfileActivity.this); startActivity(new Intent(Nokri_LinkedinProfileActivity.this, Nokri_CandidateDashboardActivity.class)); finish(); } else if (type.equals("1")) { Nokri_SharedPrefManager.saveAccountType("employeer", Nokri_LinkedinProfileActivity.this); startActivity(new Intent(Nokri_LinkedinProfileActivity.this, Nokri_EmployeerDashboardActivity.class)); finish(); } dialogManager.hideAfterDelay(); } else { Log.d("response", responseObject.toString() + "error"); Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,respone.getString("message")); dialogManager.hideAlertDialog(); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { dialogManager.showError(); dialogManager.hideAlertDialog(); } }); } private void nokri_postAccountType(final String type) { JsonObject params = new JsonObject(); params.addProperty("user_type", type); params.addProperty("user_id", Nokri_SharedPrefManager.getId(this)); RestService restService = Nokri_ServiceGenerator.createService(RestService.class, Nokri_SharedPrefManager.getEmail(this), "password", Nokri_LinkedinProfileActivity.this); Call<ResponseBody> myCall = restService.postAccountTypleSelector(params, Nokri_RequestHeaderManager.addHeaders()); myCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, @NonNull Response<ResponseBody> responseObject) { if (responseObject.isSuccessful()) { try { JSONObject respone = new JSONObject(responseObject.body().string()); Log.d("response", respone.toString()); if (respone.getBoolean("success")) { if (type.equals("0")) { dialogManager.hideAlertDialog(); nokri_applyjobLinkedIn(); } } else { Log.d("response", responseObject.toString() + "error"); Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,respone.getString("message")); dialogManager.hideAlertDialog(); Nokri_LinkedinProfileActivity.super.onBackPressed(); } } catch (IOException e) { Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,e.getMessage()); e.printStackTrace(); dialogManager.hideAlertDialog(); } catch (JSONException e) { e.printStackTrace(); Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,e.getMessage()); dialogManager.hideAlertDialog(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Nokri_ToastManager.showShortToast(Nokri_LinkedinProfileActivity.this,t.getMessage()); dialogManager.hideAlertDialog(); } }); } }
51.68277
190
0.573672
b5b709c74b678c5ab51cfbd88f9886bf9b2a414a
6,373
package com.anysoftkeyboard.quicktextkeys.ui; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import com.anysoftkeyboard.quicktextkeys.QuickTextKey; import com.anysoftkeyboard.quicktextkeys.QuickTextKeyFactory; import com.anysoftkeyboard.ui.settings.MainSettingsActivity; import com.anysoftkeyboard.utils.Log; import com.emtronics.dragsortrecycler.DragSortRecycler; import com.sevencupsoftea.ears.R; import java.util.ArrayList; import java.util.HashSet; import java.util.List; //import com.menny.android.anysoftkeyboard.R; public class QuickKeysOrderedListFragment extends Fragment { private static final String TAG = "QuickKeysOrderedListFragment"; private final HashSet<String> mEnabledAddOns = new HashSet<>(); private final CompoundButton.OnCheckedChangeListener mOnItemCheckedListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { QuickTextKey key = (QuickTextKey) buttonView.getTag(); if (isChecked) { mEnabledAddOns.add(key.getId()); } else { mEnabledAddOns.remove(key.getId()); } } }; private List<QuickTextKey> mAllQuickKeysAddOns; private RecyclerView mRecyclerView; private DragSortRecycler mDragSortRecycler; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.recycler_view_only_layout, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Context appContext = getActivity().getApplicationContext(); mAllQuickKeysAddOns = QuickTextKeyFactory.getOrderedEnabledQuickKeys(appContext); Log.d(TAG, "Got %d enabled quick-key addons", mAllQuickKeysAddOns.size()); for (QuickTextKey quickTextKey : mAllQuickKeysAddOns) { mEnabledAddOns.add(quickTextKey.getId()); Log.d(TAG, "Adding %s to enabled hash-set", quickTextKey.getId()); } for (QuickTextKey quickTextKey : QuickTextKeyFactory.getAllAvailableQuickKeys(appContext)) { Log.d(TAG, "Checking if %s is in enabled hash-set", quickTextKey.getId()); if (!mEnabledAddOns.contains(quickTextKey.getId())) { Log.d(TAG, "%s is not in the enabled list, adding it to the end of the list", quickTextKey.getId()); mAllQuickKeysAddOns.add(quickTextKey); } } mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(new LinearLayoutManager(appContext)); mRecyclerView.setAdapter(new Adapter()); mRecyclerView.setItemAnimator(null); mDragSortRecycler = new DragSortRecycler(); mDragSortRecycler.setViewHandleId(R.id.orderedListSlider); mDragSortRecycler.setOnItemMovedListener(new DragSortRecycler.OnItemMovedListener() { @Override public void onItemMoved(RecyclerView rv, int from, int to) { QuickTextKey temp = mAllQuickKeysAddOns.remove(from); mAllQuickKeysAddOns.add(to, temp); //a moved item MUST BE ENABLED mEnabledAddOns.add(temp.getId()); rv.getAdapter().notifyItemMoved(from, to); //making sure `to` is visible rv.scrollToPosition(to); } }); mRecyclerView.addItemDecoration(mDragSortRecycler); mRecyclerView.addOnItemTouchListener(mDragSortRecycler); mRecyclerView.addOnScrollListener(mDragSortRecycler.getScrollListener()); } @Override public void onStart() { super.onStart(); MainSettingsActivity.setActivityTitle(this, getString(R.string.quick_text_keys_order_dialog_title)); } @Override public void onStop() { super.onStop(); ArrayList<QuickTextKey> enabledAddons = new ArrayList<>(mEnabledAddOns.size()); for (QuickTextKey key : mAllQuickKeysAddOns) { if (mEnabledAddOns.contains(key.getId())) { enabledAddons.add(key); } } QuickTextKeyFactory.storeOrderedEnabledQuickKeys(getActivity(), enabledAddons); } @Override public void onDestroyView() { super.onDestroyView(); mRecyclerView.removeOnScrollListener(mDragSortRecycler.getScrollListener()); } private static class OrderedListViewHolder extends RecyclerView.ViewHolder { private final CheckBox title; public OrderedListViewHolder(View itemView, CompoundButton.OnCheckedChangeListener onItemCheckedListener) { super(itemView); title = (CheckBox) itemView.findViewById(R.id.orderedListTitle); title.setOnCheckedChangeListener(onItemCheckedListener); } } private class Adapter extends RecyclerView.Adapter<OrderedListViewHolder> { private final LayoutInflater mLayoutInflater; Adapter() { mLayoutInflater = LayoutInflater.from(getActivity()); } @Override public OrderedListViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { return new OrderedListViewHolder(mLayoutInflater.inflate(R.layout.ordered_list_item, viewGroup, false), mOnItemCheckedListener); } @Override public void onBindViewHolder(OrderedListViewHolder viewHolder, int position) { QuickTextKey value = mAllQuickKeysAddOns.get(position); viewHolder.title.setTag(value); viewHolder.title.setText(value.getName()); viewHolder.title.setChecked(mEnabledAddOns.contains(value.getId())); } @Override public int getItemCount() { return mAllQuickKeysAddOns.size(); } } }
40.592357
140
0.696846
31c7797486a437d5976afcbfd22e0bb74ffdbbb9
3,989
/** * Copyright 2022 Markus Bordihn * * 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 de.markusbordihn.lobby.datapack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.minecraft.server.level.ServerLevel; import de.markusbordihn.lobby.Constants; import de.markusbordihn.lobby.commands.CommandManager; import de.markusbordihn.lobby.data.FishingData; import de.markusbordihn.lobby.data.GamingData; import de.markusbordihn.lobby.data.LobbyData; import de.markusbordihn.lobby.data.MiningData; import de.markusbordihn.lobby.data.VoidData; import de.markusbordihn.lobby.dimension.DimensionManager; public class DataPackHandler { public static final Logger log = LogManager.getLogger(Constants.LOG_NAME); protected DataPackHandler() {} public static void prepareDataPackOnce(ServerLevel level) { if (level == DimensionManager.getLobbyDimension()) { if (LobbyData.get().getDimensionLoaded()) { log.info("Skip Data Pack for lobby dimension {} because it was already loaded!", level); } else { prepareDataPack(level); LobbyData.get().setDimensionLoaded(true); } } else if (level == DimensionManager.getMiningDimension()) { if (MiningData.get().getDimensionLoaded()) { log.info("Skip Data Pack for mining dimension {} because it was already loaded!", level); } else { prepareDataPack(level); MiningData.get().setDimensionLoaded(true); } } else if (level == DimensionManager.getFishingDimension()) { if (FishingData.get().getDimensionLoaded()) { log.info("Skip Data Pack for fishing dimension {} because it was already loaded!", level); } else { prepareDataPack(level); FishingData.get().setDimensionLoaded(true); } } else if (level == DimensionManager.getGamingDimension()) { if (GamingData.get().getDimensionLoaded()) { log.info("Skip Data Pack for gaming dimension {} because it was already loaded!", level); } else { prepareDataPack(level); GamingData.get().setDimensionLoaded(true); } } else if (level == DimensionManager.getVoidDimension()) { if (VoidData.get().getDimensionLoaded()) { log.info("Skip Data Pack for void dimension {} because it was already loaded!", level); } else { prepareDataPack(level); VoidData.get().setDimensionLoaded(true); } } else { log.warn("Unable to get status for level {} to confirm data pack load status!", level); } } public static void prepareDataPack(ServerLevel level) { String dimensionLocation = level.dimension().location().toString(); String dataPackFunction = dimensionLocation.split(":")[0] + ":" + dimensionLocation.split(":")[1] + "_load"; log.info("Loading data pack with {} for level {} ...", dataPackFunction, level); CommandManager.executeServerFunction(dataPackFunction, level); } }
43.835165
100
0.714966
9cc8db08318b04b261d85f3cf0e40426c4b5551e
429
package com.blackmorse.hattrick.model.enums; import com.fasterxml.jackson.annotation.JsonValue; public enum SearchType implements HattrickType { PLAYERS(0), ARENAS(1), MANAGERS(2), SERIES(3), TEAMS(4), REGIONS(5), MATCH(6); private int value; SearchType(int value) { this.value = value; } @JsonValue @Override public int getValue() { return value; } }
16.5
50
0.622378
53d29612e0e594a5d8f79b50d35193043cd795f4
1,663
package org.zackratos.weather.hewind; import android.os.Parcel; import android.os.Parcelable; /** * Created by Administrator on 2017/6/26. */ public class Wind implements Parcelable { /** * deg : 190 * dir : 南风 * sc : 3-4 * spd : 13 */ private String deg; private String dir; private String sc; private String spd; public String getDeg() { return deg; } public void setDeg(String deg) { this.deg = deg; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public String getSc() { return sc; } public void setSc(String sc) { this.sc = sc; } public String getSpd() { return spd; } public void setSpd(String spd) { this.spd = spd; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.deg); dest.writeString(this.dir); dest.writeString(this.sc); dest.writeString(this.spd); } protected Wind(Parcel in) { this.deg = in.readString(); this.dir = in.readString(); this.sc = in.readString(); this.spd = in.readString(); } public static final Parcelable.Creator<Wind> CREATOR = new Parcelable.Creator<Wind>() { @Override public Wind createFromParcel(Parcel source) { return new Wind(source); } @Override public Wind[] newArray(int size) { return new Wind[size]; } }; }
18.685393
91
0.556224
ba4c95b245333b03abb6ec3c0d1b187e43a211d6
1,578
import java.util.LinkedList; import java.lang.Math; public class SortedListToBST { public static Tree convertArrayToBST(Integer[] array, Tree result) { // A: find the middle of the whole array int mid = Math.floorDiv(0 + array.length - 1, 2); // B: set the root of the tree result.root = new BinaryTreeNode(array[mid]); // C: set the left and right children of the root result.root.left = convertArrayToBST(array, 0, mid - 1); result.root.right = convertArrayToBST(array, mid + 1, array.length - 1); // D: return the tree return result; } public static BinaryTreeNode convertArrayToBST(Integer[] array, int low, int high) { // A: find the middle of this range in the array int mid = Math.floorDiv(low + high, 2); // B: set the left and children of this node BinaryTreeNode node = new BinaryTreeNode(array[mid]); node.left = convertArrayToBST(array, low, mid - 1); node.right = convertArrayToBST(array, mid + 1, high); // C: return the node return node; } public static Tree solution(LinkedList<Integer> nums) { // A: init output Tree result = new Tree(); // B: validate input if (nums != null) { // C: convert linked list to array Integer[] numsArray = nums.toArray(new Integer[nums.size()]); // D: convert array to BST result = convertArrayToBST(numsArray, result); } // E: output the tree return result; } }
37.571429
88
0.60076
c77d1e57e2c8a6ae2c4da76ae7ae8564544d03b2
1,855
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.discovery.ec2; import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsResponse; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.discovery.DiscoveryModule; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import static org.hamcrest.CoreMatchers.is; /** * Just an empty Node Start test to check eveything if fine when * starting. * This test requires AWS to run. */ @ClusterScope(scope = Scope.TEST, numDataNodes = 0, numClientNodes = 0) public class Ec2DiscoveryUpdateSettingsTests extends AbstractAwsTestCase { public void testMinimumMasterNodesStart() { Settings nodeSettings = Settings.builder().put(DiscoveryModule.DISCOVERY_SEED_PROVIDERS_SETTING.getKey(), "ec2").build(); internalCluster().startNode(nodeSettings); // We try to update a setting now final String expectedValue = UUIDs.randomBase64UUID(random()); final String settingName = "cluster.routing.allocation.exclude.any_attribute"; final ClusterUpdateSettingsResponse response = client().admin() .cluster() .prepareUpdateSettings() .setPersistentSettings(Settings.builder().put(settingName, expectedValue)) .get(); final String value = response.getPersistentSettings().get(settingName); assertThat(value, is(expectedValue)); } }
42.159091
129
0.748248
22a954ae2c3db30a2ce3c8e3b84856112e005e53
1,556
import java.io.*; import java.util.*; public class FileRead { private static String lineOne; private static String lineTwo; public static ArrayList<String> readLines() { try { File fileName = new File("pol.txt"); FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader); lineOne = bufferedReader.readLine(); lineTwo = bufferedReader.readLine(); ArrayList<String> command = new ArrayList<String>(); String buffer; while((buffer = bufferedReader.readLine()) != null) { command.add(buffer); } return command; } catch (IOException e) { e.printStackTrace(); } return null; }//END readLines method public static void printLinesRead() { System.out.println("Polynomials read from file are : "); System.out.println(lineOne); System.out.println(lineTwo); } public static ArrayList<Integer> lineToIntArray(String line) { ArrayList<Integer> array = new ArrayList<Integer>(); int buf = 0; for (int i = 0;i<line.length();i++) { if(line.charAt(i)!=' ') { buf = buf*10 +((int)line.charAt(i) - 48); } if(line.charAt(i) == ' ') { array.add(buf); buf = 0; } } return array; } public static String getLineOne() { return lineOne; } public static String getLineTwo() { return lineTwo; } }//END class
17.885057
69
0.576478
f6d5705e2dd35494fadb72ee2a894831e26e64d3
11,482
/* * Copyright 2014 Institute fml (TU Munich) and Institute FLW (TU Dortmund). * * 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 kodemat.visu.editor.selection; import com.hazelcast.core.EntryEvent; import com.hazelcast.core.EntryListener; import com.hazelcast.core.IMap; import com.hazelcast.core.MapEvent; import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.SceneGraphVisitor; import com.jme3.scene.Spatial; import java.util.ArrayList; import java.util.List; import kodemat.visudata.VisuColor; import kodemat.visudata.visuComponents.VisuComponent; import kodemat.visudata.VisuHelper; import kodemat.visudata.VisuMarking; import kodemat.visudata.VisuRotation; import kodemat.visudata.VisuVector3f; /** * * @author Koshkabb, Kipouridis */ public class JMESelectionHandler implements IVisuSelectable { private VisuComponent selectedModel; private Spatial selectedSpatial; private static String username; public static String getUsername(){ return username; } public VisuComponent getSelectedModel() { return selectedModel; } public void setSelectedModel(VisuComponent selectedModel) { this.selectedModel = selectedModel; } public Spatial getSelectedSpatial() { return selectedSpatial; } public void setSelectedSpatial(Spatial selectedSpatial) { this.selectedSpatial = selectedSpatial; } private VisuHelper visuHelper; private SimpleApplication visuClient; private ArrayList<Long> selectedObjectIds; private boolean showSelection; private final IMap<String, ArrayList<Long>> allSelectedObjectsMap; public JMESelectionHandler(Application visuClient, VisuHelper visuHelper, boolean showSelection) { this.visuHelper = visuHelper; username = visuHelper.getUsername(); selectedObjectIds = new ArrayList<>(); this.visuClient = (SimpleApplication) visuClient; this.showSelection = showSelection; allSelectedObjectsMap = visuHelper.getSelectedComponents(); // add an entry listener to get the events when a user selects an object EntryListener listener = new UserSelectionEntryListener(); allSelectedObjectsMap.addEntryListener(listener, true); } public ArrayList<Long> getSelectedObjectIds() { return selectedObjectIds; } public void setSelectedObjectIds(ArrayList<Long> selectedObjectIds) { this.selectedObjectIds = selectedObjectIds; } // only for one component for the moment, should be extended to enable multiple object selection public void setSelectedModel(ArrayList<Long> selectedObjectIds) { long selectedModelId = this.getSelectedObjectIds().get(0); this.selectedModel = visuHelper.getComponent(selectedModelId); findSpatial(selectedModel.getName()); } public void findSpatial(final String name) { SceneGraphVisitor visitor = new SceneGraphVisitor() { @Override public void visit(Spatial spatial) { if (spatial.getName() != null) { if (spatial.getName().equals(name)) { selectedSpatial = spatial; } } } }; visuClient.getRootNode().breadthFirstTraversal(visitor); } //The method is a bit erroneous, should be replaced with a clear interface @Override public void setObjectSpatial(Spatial spatial) { this.selectedSpatial = spatial; } public void rotate() { // VisuComponent parent = getModelParent(); VisuComponent component = getSelectedModel(); float old = 0; if (component.getRotation() != null) { old = component.getRotation().y; } if (old < -360) { old = old + 360; } component.setRotation(new VisuRotation(0, old - 5, 0)); } @Override public void rotate(float deg) { VisuComponent component = getSelectedModel(); component.setRotation(new VisuRotation(0, deg, 0)); } @Override public void scale(float scale) { /* VisuVector3f originalScale = selectedModel.getOriginalScale(); if (originalScale != null) { selectedModel.setScale(new VisuVector3f(originalScale.x * scaleNum, originalScale.y * scaleNum, originalScale.z * scaleNum)); }else{*/ removeBoundingBox(); selectedModel.setScale(new VisuVector3f(scale, scale, scale)); createBoundingBox(); //} } @Override public void delete(){ ArrayList<String> toDelete = new ArrayList<String>(); toDelete.add(getSelectedModel().getName()); visuHelper.deleteComponents(toDelete); } @Override public void showOrHideNote() { Node selectedNode = (Node) selectedSpatial; List<Spatial> childrenList = selectedNode.getChildren(); for (Spatial child : childrenList) { if (child.getName().contains("Note")) { if (child.getCullHint() != Spatial.CullHint.Always) { child.setCullHint(Spatial.CullHint.Always); } else { child.setCullHint(Spatial.CullHint.Never); } } } } // public void removeLights() { // if (selectedSpatial != null) { // selectedSpatial.removeLight(lampLight); // selectedSpatial.removeControl(lightControl); // } // } @Override public void showBigNote() {//Attaches the billboard to the parent if (selectedSpatial != null) { Node n = (Node) selectedSpatial; n.detachChildNamed("Note"); n.attachChild(NoteBillboardCreator.createNote(visuClient.getAssetManager(), selectedModel.getLastNote())); } } @Override public void createBoundingBox() { if(selectedModel.getLabel() != null ){ if(!selectedModel.getLabel().isEmpty()){ selectedModel.setLabel(selectedModel.getLabel().concat(", "+visuHelper.getUsername())); //TODO: change this when usernames exist } } String labelText = "Edited by " + visuHelper.getUsername(); selectedModel.setLabel(labelText); //TODO: change this when usernames exist selectedModel.setMarking(new VisuMarking(new VisuColor(0f,0f,0f,0f),labelText,1)); } @Override public void removeBoundingBox() { if(this.getSelectedModel()!=null){ selectedModel.setLabel(""); selectedModel.setMarking(new VisuMarking(new VisuColor(0f,0f,0f,0f),"",0)); } } @Override public void move(Vector3f direction, float factor) { // VisuComponent parent = getModelParent(); VisuVector3f oldPos = this.selectedModel.getTranslation(); Vector3f currentTrans = new Vector3f(oldPos.x, oldPos.y, oldPos.z); Vector3f movingDirection = direction.mult(factor); currentTrans = currentTrans.add(movingDirection); oldPos = new VisuVector3f(currentTrans.x, oldPos.y, currentTrans.z); this.selectedModel.setTranslation(oldPos); } @Override public VisuComponent getModelParent() { if (selectedModel != null) { VisuComponent parent = visuHelper.getComponent(selectedModel.getParent()); if (parent != null) { return parent; } } return null; } @Override public Spatial getSpatial() { return selectedSpatial; } @Override public boolean isEmpty() { return (selectedModel == null); } @Override public boolean setVisuCompToSelected(VisuComponent selectedModel, Spatial selectedSpatial) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean setVisuCompToSelected(VisuComponent selectedModel) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void rotateRightGradual() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } //The first parameter should be generalized public class UserSelectionEntryListener implements EntryListener<String, ArrayList<Long>> { @Override public void entryAdded(EntryEvent<String, ArrayList<Long>> event) { // System.out.println("Selection map entry entryAdded "); } @Override public void entryRemoved(EntryEvent<String, ArrayList<Long>> event) { // System.out.println("Selection map entry entryRemoved "); } @Override public void entryUpdated(EntryEvent<String, ArrayList<Long>> event) { // System.out.println("Selection map entry entry Updated selected "); if(event.getKey().contains(username)){ setSelectedObjectIds(event.getValue()); if(event.getValue().size()>0){ //if there is at least one selected object if(getSelectedModel()!=null){ //check if there was already an object selected before removeBoundingBox(); //if there was remove its marking } setSelectedModel(event.getValue()); //update the marking of the currenct selection createBoundingBox(); }else { removeBoundingBox(); } } } @Override public void entryEvicted(EntryEvent<String, ArrayList<Long>> event) { System.out.println("Selection map entry evicted "); } @Override public void mapEvicted(MapEvent me) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mapCleared(MapEvent me) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } }
35.006098
152
0.61775
14773500f075dd364c83d4d788efa98f659065b4
2,769
/* * 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.spark.sql.execution.datasources.orc; import org.apache.orc.ColumnStatistics; import org.apache.orc.Reader; import org.apache.orc.TypeDescription; import org.apache.spark.sql.types.*; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; /** * `OrcFooterReader` is a util class which encapsulates the helper * methods of reading ORC file footer. */ public class OrcFooterReader { /** * Read the columns statistics from ORC file footer. * * @param orcReader the reader to read ORC file footer. * @return Statistics for all columns in the file. */ public static OrcColumnsStatistics readStatistics(Reader orcReader) { TypeDescription orcSchema = orcReader.getSchema(); ColumnStatistics[] orcStatistics = orcReader.getStatistics(); StructType dataType = OrcUtils.toCatalystSchema(orcSchema); return convertStatistics(dataType, new LinkedList<>(Arrays.asList(orcStatistics))); } /** * Convert a queue of ORC {@link ColumnStatistics}s into Spark {@link OrcColumnsStatistics}. * The queue of ORC {@link ColumnStatistics}s are assumed to be ordered as tree pre-order. */ private static OrcColumnsStatistics convertStatistics( DataType dataType, Queue<ColumnStatistics> orcStatistics) { OrcColumnsStatistics statistics = new OrcColumnsStatistics(orcStatistics.remove()); if (dataType instanceof StructType) { for (StructField field : ((StructType) dataType).fields()) { statistics.add(convertStatistics(field.dataType(), orcStatistics)); } } else if (dataType instanceof MapType) { statistics.add(convertStatistics(((MapType) dataType).keyType(), orcStatistics)); statistics.add(convertStatistics(((MapType) dataType).valueType(), orcStatistics)); } else if (dataType instanceof ArrayType) { statistics.add(convertStatistics(((ArrayType) dataType).elementType(), orcStatistics)); } return statistics; } }
40.720588
94
0.745395
aee6f0b67e9386524867473c3c68d08513d88a56
4,588
/* Copyright (c) 2013 James Ahlborn 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.healthmarketscience.jackcess.impl; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * Utility class for constructing {@code byte[]s} where the final size of the * data is not known beforehand. The API is similar to {@code ByteBuffer} but * the data is not actually written to a {@code byte[]} until {@link * #toBuffer} or {@link #toArray} is called. * * @author James Ahlborn */ public class ByteArrayBuilder { private int _pos; private final List<Data> _data = new ArrayList<Data>(); public ByteArrayBuilder() { } public int position() { return _pos; } public ByteArrayBuilder reserveInt() { return reserve(4); } public ByteArrayBuilder reserveShort() { return reserve(2); } public ByteArrayBuilder reserve(int bytes) { _pos += bytes; return this; } public ByteArrayBuilder put(byte val) { return put(new ByteData(_pos, val)); } public ByteArrayBuilder putInt(int val) { return putInt(_pos, val); } public ByteArrayBuilder putInt(int pos, int val) { return put(new IntData(pos, val)); } public ByteArrayBuilder putShort(short val) { return putShort(_pos, val); } public ByteArrayBuilder putShort(int pos, short val) { return put(new ShortData(pos, val)); } public ByteArrayBuilder put(byte[] val) { return put(new BytesData(_pos, val)); } public ByteArrayBuilder put(ByteBuffer val) { return put(new BufData(_pos, val)); } private ByteArrayBuilder put(Data data) { _data.add(data); int endPos = data.getEndPos(); if(endPos > _pos) { _pos = endPos; } return this; } public ByteBuffer toBuffer() { return toBuffer(PageChannel.wrap(new byte[_pos])); } public ByteBuffer toBuffer(ByteBuffer buf) { for(Data data : _data) { data.write(buf); } buf.rewind(); return buf; } public byte[] toArray() { return toBuffer().array(); } private static abstract class Data { private int _pos; protected Data(int pos) { _pos = pos; } public int getPos() { return _pos; } public int getEndPos() { return getPos() + size(); } public abstract int size(); public abstract void write(ByteBuffer buf); } private static final class IntData extends Data { private final int _val; private IntData(int pos, int val) { super(pos); _val = val; } @Override public int size() { return 4; } @Override public void write(ByteBuffer buf) { buf.putInt(getPos(), _val); } } private static final class ShortData extends Data { private final short _val; private ShortData(int pos, short val) { super(pos); _val = val; } @Override public int size() { return 2; } @Override public void write(ByteBuffer buf) { buf.putShort(getPos(), _val); } } private static final class ByteData extends Data { private final byte _val; private ByteData(int pos, byte val) { super(pos); _val = val; } @Override public int size() { return 1; } @Override public void write(ByteBuffer buf) { buf.put(getPos(), _val); } } private static final class BytesData extends Data { private final byte[] _val; private BytesData(int pos, byte[] val) { super(pos); _val = val; } @Override public int size() { return _val.length; } @Override public void write(ByteBuffer buf) { buf.position(getPos()); buf.put(_val); } } private static final class BufData extends Data { private final ByteBuffer _val; private BufData(int pos, ByteBuffer val) { super(pos); _val = val; } @Override public int size() { return _val.remaining(); } @Override public void write(ByteBuffer buf) { buf.position(getPos()); buf.put(_val); } } }
19.690987
78
0.637751
31ce12c73a9dd737da73fad6476afcac445d5c4d
4,964
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties; import java.util.List; import java.util.stream.Collectors; import org.eclipse.bpmn2.DataInput; import org.eclipse.bpmn2.DataInputAssociation; import org.eclipse.bpmn2.DataOutput; import org.eclipse.bpmn2.DataOutputAssociation; import org.eclipse.bpmn2.Property; import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.AssociationDeclaration; import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.AssociationDeclaration.Direction; import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.AssociationList; import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.CustomAttribute; import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.DeclarationList; import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.ParsedAssignmentsInfo; import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.VariableDeclaration; import org.kie.workbench.common.stunner.bpmn.definition.property.dataio.AssignmentsInfo; import static org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.AssociationDeclaration.Type; public class AssignmentsInfos { public static AssignmentsInfo of( final List<DataInput> datainput, final List<DataInputAssociation> inputAssociations, final List<DataOutput> dataoutput, final List<DataOutputAssociation> outputAssociations, boolean alternativeEncoding) { DeclarationList inputs = dataInputDeclarations(datainput); DeclarationList outputs = dataOutputDeclarations(dataoutput); AssociationList associations = new AssociationList( inAssociationDeclarations(inputAssociations), outAssociationDeclarations(outputAssociations)); return new AssignmentsInfo(new ParsedAssignmentsInfo( inputs, outputs, associations, alternativeEncoding).toString()); } private static DeclarationList dataInputDeclarations(List<DataInput> dataInputs) { return new DeclarationList( dataInputs.stream() .filter(o -> !o.getName().equals("TaskName")) .map(in -> new VariableDeclaration( in.getName(), CustomAttribute.dtype.of(in).get())) .collect(Collectors.toList())); } private static DeclarationList dataOutputDeclarations(List<DataOutput> dataInputs) { return new DeclarationList( dataInputs.stream() .filter(o -> !CustomAttribute.dtype.of(o).get().isEmpty()) .map(out -> new VariableDeclaration( out.getName(), CustomAttribute.dtype.of(out).get())) .collect(Collectors.toList())); } private static List<AssociationDeclaration> inAssociationDeclarations(List<DataInputAssociation> inputAssociations) { return inputAssociations.stream() .filter(association -> !association.getSourceRef().isEmpty()) .map(in -> new AssociationDeclaration( Direction.Input, Type.SourceTarget, getPropertyName((Property) in.getSourceRef().get(0)), ((DataInput) in.getTargetRef()).getName())) .collect(Collectors.toList()); } private static List<AssociationDeclaration> outAssociationDeclarations(List<DataOutputAssociation> outputAssociations) { return outputAssociations.stream() .map(out -> new AssociationDeclaration( Direction.Output, Type.SourceTarget, ((DataOutput) out.getSourceRef().get(0)).getName(), getPropertyName((Property) out.getTargetRef()))) .collect(Collectors.toList()); } // fallback to ID for https://issues.jboss.org/browse/JBPM-6708 private static String getPropertyName(Property prop) { return prop.getName() == null ? prop.getId() : prop.getName(); } }
47.730769
124
0.679291
0d22d1b6bf4ad417ea06194eba87971bb060c30f
2,663
/* * Selling Partner API for Shipping * Provides programmatic access to Amazon Shipping APIs. * * OpenAPI spec version: v1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.github.shuaidd.aspi.model.shipping; import com.google.gson.annotations.SerializedName; import java.util.Objects; /** * The promised delivery time and pickup time. */ public class ShippingPromiseSet { @SerializedName("deliveryWindow") private TimeRange deliveryWindow = null; @SerializedName("receiveWindow") private TimeRange receiveWindow = null; public ShippingPromiseSet deliveryWindow(TimeRange deliveryWindow) { this.deliveryWindow = deliveryWindow; return this; } /** * The time window in which the shipment will be delivered. * @return deliveryWindow **/ public TimeRange getDeliveryWindow() { return deliveryWindow; } public void setDeliveryWindow(TimeRange deliveryWindow) { this.deliveryWindow = deliveryWindow; } public ShippingPromiseSet receiveWindow(TimeRange receiveWindow) { this.receiveWindow = receiveWindow; return this; } /** * The time window in which Amazon Shipping will pick up the shipment. * @return receiveWindow **/ public TimeRange getReceiveWindow() { return receiveWindow; } public void setReceiveWindow(TimeRange receiveWindow) { this.receiveWindow = receiveWindow; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ShippingPromiseSet shippingPromiseSet = (ShippingPromiseSet) o; return Objects.equals(this.deliveryWindow, shippingPromiseSet.deliveryWindow) && Objects.equals(this.receiveWindow, shippingPromiseSet.receiveWindow); } @Override public int hashCode() { return Objects.hash(deliveryWindow, receiveWindow); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ShippingPromiseSet {\n"); sb.append(" deliveryWindow: ").append(toIndentedString(deliveryWindow)).append("\n"); sb.append(" receiveWindow: ").append(toIndentedString(receiveWindow)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
24.209091
92
0.695456
a69e1e5980cd94e409c3586283243ceef544d29b
488
package com.xuegao.gatewaytest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * <br/> @ClassName:GatewayTestApplication * <br/> @Description: * <br/> @author:xuegao * <br/> @date:2021/9/26 19:55 */ @SpringBootApplication @EnableDiscoveryClient public class GatewayTestApplication { public static void main(String[] args) { SpringApplication.run(GatewayTestApplication.class, args); } }
24.4
68
0.752049
44c8b102e01a417071ad490ba8f59905f50a18b7
1,424
/* * Copyright (C) 2018 The JackKnife Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lwh.jackknife.widget.animator; import android.view.View; public class ScaleAction implements Action<ScaleAction> { private float mScaleX; private float mScaleY; public ScaleAction(float scaleX, float scaleY) { this.mScaleX = scaleX; this.mScaleY = scaleY; } public float getScaleX() { return mScaleX; } public float getScaleY() { return mScaleY; } @Override public final Action add(ScaleAction action) { throw new UnsupportedOperationException("ScaleAction added leaf node does not support at present."); } @Override public final void startAnimation(View view, int duration) { throw new UnsupportedOperationException("ScaleAction does not hold the animation at present."); } }
29.061224
108
0.707163
efce07a3fac303aff5d6385222544d7da8d80405
1,266
/* * Copyright 2022 Tigris Data, 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.tigrisdata.db.client.auth; import org.junit.Assert; import org.junit.Test; public class TigrisAuthorizationTokenTest { @Test public void testInvalidToken() { try { new TigrisAuthorizationToken(""); Assert.fail("This must fail"); } catch (IllegalArgumentException illegalArgumentException) { Assert.assertEquals("Token is invalid", illegalArgumentException.getMessage()); } try { new TigrisAuthorizationToken(null); Assert.fail("This must fail"); } catch (IllegalArgumentException illegalArgumentException) { Assert.assertEquals("Token is invalid", illegalArgumentException.getMessage()); } } }
34.216216
99
0.732227
09ecf677f14b194c2e54ef8eb4ca0c3d199f1387
5,461
package fr.umlv.mjolnir.amber; import static java.lang.invoke.MethodType.methodType; import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS; import static org.objectweb.asm.Opcodes.ACC_FINAL; import static org.objectweb.asm.Opcodes.ACC_PRIVATE; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACC_STATIC; import static org.objectweb.asm.Opcodes.ACC_SUPER; import static org.objectweb.asm.Opcodes.ALOAD; import static org.objectweb.asm.Opcodes.ARETURN; import static org.objectweb.asm.Opcodes.DUP; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; import static org.objectweb.asm.Opcodes.LLOAD; import static org.objectweb.asm.Opcodes.NEW; import static org.objectweb.asm.Opcodes.PUTFIELD; import static org.objectweb.asm.Opcodes.RETURN; import static org.objectweb.asm.Opcodes.V1_9; import java.io.PrintWriter; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.util.ArrayList; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.util.CheckClassAdapter; //import sun.misc.Unsafe; import fr.umlv.mjolnir.amber.TupleHandle.Form; class TupleGenerator { private static final Lookup LOOKUP = MethodHandles.lookup(); private static final String CLASS_PREFIX = TupleHandle.class.getPackageName().replace('.', '/') + "/FORM"; private static MethodHandle constructor(Class<?> clazz, MethodType methodType) { MethodHandle constructor; try { constructor = LOOKUP.findStatic(clazz, "create", methodType.changeReturnType(clazz)); } catch (IllegalAccessException | NoSuchMethodException e) { throw (LinkageError)new LinkageError().initCause(e); } return constructor.asType(constructor.type().changeReturnType(Object.class)); } private static MethodHandle[] getters(Class<?> clazz, Form form) { ArrayList<MethodHandle> mhs = new ArrayList<>(); for(int i = 0; i < form.objects; i++) { mhs.add(getter(clazz, "objects$" + i, Object.class)); } for(int i = 0; i < form.prims; i++) { mhs.add(getter(clazz, "prims$" + i, long.class)); } return mhs.toArray(new MethodHandle[0]); } private static MethodHandle getter(Class<?> clazz, String name, Class<?> type) { MethodHandle getter; try { getter = LOOKUP.findGetter(clazz, name, type); } catch (IllegalAccessException | NoSuchFieldException e) { throw (LinkageError)new LinkageError().initCause(e); } return getter.asType(methodType(type, Object.class)); } public static TupleHandle generate(Form form) { MethodType methodType = form.asMethodType(); Class<?> clazz = generate(form, methodType); return new TupleHandle(methodType, constructor(clazz, methodType.changeReturnType(clazz)), getters(clazz, form)); } private static Class<?> generate(Form form, MethodType methodType) { String className = CLASS_PREFIX + form.objects + '_' + form.prims; ClassWriter writer = new ClassWriter(COMPUTE_MAXS); writer.visit(V1_9, ACC_PUBLIC| ACC_SUPER, className, null, "java/lang/Object", null); for(int i = 0; i < form.objects; i++) { FieldVisitor fv = writer.visitField(ACC_PUBLIC|ACC_FINAL, "objects$" + i, "Ljava/lang/Object;", null, null); fv.visitEnd(); } for(int i = 0; i < form.prims; i++) { FieldVisitor fv = writer.visitField(ACC_PUBLIC|ACC_FINAL, "prims$" + i, "J", null, null); fv.visitEnd(); } String desc = methodType.toMethodDescriptorString(); { MethodVisitor mv = writer.visitMethod(ACC_PRIVATE, "<init>", desc, null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); for(int i = 0; i < form.objects; i++) { mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, i + 1); mv.visitFieldInsn(PUTFIELD, className, "objects$" + i, "Ljava/lang/Object;"); } for(int i = 0; i < form.prims; i++) { mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(LLOAD, form.objects + 1 + i * 2); mv.visitFieldInsn(PUTFIELD, className, "prims$" + i, "J"); } mv.visitInsn(RETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); } String factoryDesc = desc.substring(0, desc.length() - 1) + 'L' + className + ';'; // replace V by className { MethodVisitor mv = writer.visitMethod(ACC_PUBLIC|ACC_STATIC, "create", factoryDesc, null, null); mv.visitCode(); mv.visitTypeInsn(NEW, className); mv.visitInsn(DUP); for(int i = 0; i < form.objects; i++) { mv.visitVarInsn(ALOAD, i); } for(int i = 0; i < form.prims; i++) { mv.visitVarInsn(LLOAD, form.objects + i * 2); } mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", desc, false); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); } writer.visitEnd(); byte[] code = writer.toByteArray(); // DEBUG CheckClassAdapter.verify(new ClassReader(code), false, new PrintWriter(System.out)); try { return LOOKUP.defineClass(code); } catch (IllegalAccessException e) { throw (LinkageError)new LinkageError().initCause(e); } } }
37.40411
117
0.680828
18c33e20d68c44aba12d3e60f8a60754d8f13107
2,659
/* * Copyright (C) 2015 Sebastian Daschner, sebastian-daschner.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE2.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.sebastian_daschner.jaxrs_analyzer.analysis.bytecode.collection; import com.sebastian_daschner.jaxrs_analyzer.model.instructions.DefaultInstruction; import com.sebastian_daschner.jaxrs_analyzer.model.instructions.Instruction; import javassist.bytecode.CodeIterator; import javassist.bytecode.Mnemonic; import javassist.bytecode.Opcode; /** * Creates instructions for WIDE opcodes. * * @author Sebastian Daschner */ class WideInstructionBuilder implements Opcode { private final CodeIterator codeIterator; private final LoadStoreInstructionBuilder loadStoreInstructionBuilder; WideInstructionBuilder(final CodeIterator codeIterator, final LoadStoreInstructionBuilder loadStoreInstructionBuilder) { this.codeIterator = codeIterator; this.loadStoreInstructionBuilder = loadStoreInstructionBuilder; } /** * Creates an LOAD, STORE, IINC or RET instruction for the given wide byte code position. * * @param position The byte code position * @return The contained instruction */ Instruction build(final int position) { if (codeIterator.byteAt(position) != WIDE) throw new IllegalArgumentException("WIDE instruction is not valid."); int containedOpcode = codeIterator.byteAt(position + 1); switch (containedOpcode) { case ILOAD: case LLOAD: case FLOAD: case DLOAD: case ALOAD: return loadStoreInstructionBuilder.buildLoad(codeIterator.u16bitAt(position + 2)); case ISTORE: case LSTORE: case FSTORE: case DSTORE: case ASTORE: return loadStoreInstructionBuilder.buildStore(codeIterator.u16bitAt(position + 2)); case IINC: case RET: return new DefaultInstruction(Mnemonic.OPCODE[containedOpcode]); default: throw new IllegalArgumentException("WIDE instruction is not valid."); } } }
35.932432
124
0.700263
2b8764afb231b159872318adf065f82c93428c75
1,672
import java.io.*; import java.util.*; public class Employees { int db,mb,yb; float sal; String name; public static void main(String args[]) { Employees emp = new Employees(); emp.showDetails(); } public void showDetails() { Scanner sc = new Scanner(System.in); int db,mb,yb; double sal,tax; String name; System.out.println("Enter your name : "); name = sc.next(); System.out.println("Enter your birth date : "); db = sc.nextInt(); System.out.println("Enter your birth month : "); mb = sc.nextInt(); System.out.println("Enter your birth year : "); yb = sc.nextInt(); System.out.println("Enter your monthly salary: "); sal = sc.nextDouble(); sal = sal*12; if(sal >= 500000) { tax = sal*0.20; System.out.println("name = " + name + " birth date = " + db + " birth month = " + mb + " birth year = " + yb + " salary = " + sal + " tax = " + tax); } else if(sal >=400000 && sal <=499999) { tax = sal *0.15; System.out.println("name = " + name + " birth date = " + db + " birth month = " + mb + " birth year = " + yb + " salary = " + sal + " tax = " + tax); } else if(sal >=300000 && sal <=399999) { tax = sal *0.10; System.out.println("name = " + name + " birth date = " + db + " birth month = " + mb + " birth year = " + yb + " salary = " + sal + " tax = " + tax); } else if(sal <= 200000) { tax = sal *0.05; System.out.println("name = " + name + " birth date = " + db + " birth month = " + mb + " birth year = " + yb + " salary = " + sal + " tax = " + tax); } } }
25.723077
158
0.513158
de741df5574edbf9a8beb6ca05c8fafb40e2701f
9,179
/** * Represents a single table in the database. * @author Kevin Filanowski * @version 09/21/18 */ public class Table<T extends AttributeInterface> { /** First record in the table */ private Node head; /** Last record in the table */ private Node tail; /** Label for the table */ private String title; /** Counter to keep size of the array */ private int size; /** * This temp node is only used to iterate through the table. It is declared * here so that we don't constantly declare it throughout the code. */ private Node temp; /** * Initializes an empty table with a label. * @param title The label for the table. */ public Table(String title) { this(null, title); } /** * Initializes a table with the first record and a label. * @param head The first record in the table. * @param title The label for the table. */ public Table(Node head, String title) { this.head = head; this.title = title; tail = head; size = 0; } /** * Checks the table to see if a row with the data specified exists. * NOTE: The data in the table should have a valid and appropriate * equals method to compare data. * @param data The data that will be used to check the table for. * @return True if there is a matching data piece to a row in the table, * false otherwise. */ public boolean contains(T data) { // Reset the temporary node back to the head to iterate the table. temp = head; for (int i = 0; i < size; i++) { // Compare the data if (temp.data.equals(data)) { return true; } temp = temp.next; } return false; } /** * Creates a new table comprised of nodes in this table, but not in the * table being passed in. * @param table The table used to compare with the original one. * @return A new table of type T, containing nodes contained in the * original table but not in the table passed in. */ Table<T> difference(Table<T> table) { // The new table comprised of differences. Table<T> differenceTable = new Table<T>(title + ", " + table.title); // Reset the temporary node back to the head to iterate the table. temp = head; // Iterate through the first table, only adding rows unique // to the first table. for (int i = 0; i < size; i++) { if (!table.contains(temp.data)) { differenceTable.insert(temp.data); } temp = temp.next; } return differenceTable; } /** * Adds a new record to the end of the table. * @param data The information that would be contained in a row of the table. */ void insert(T data) { // If this is the first element, set it to head. Otherwise, // add it to the end of the tail. if (head == null) { head = new Node(data); tail = head; } else { tail.next = new Node(data); tail = tail.next; } size++; } /** * Creates a new table comprised of nodes having a value for a specific * attribute, created from two tables. * @param attribute The attribute to restrict to. * @param value The value of that attribute to restrict to. * @param table The other table to compare with. * @return A new table composed of the same specified attributes and values * in both tables. */ Table<T> intersect(String attribute, String value, Table<T> table) { // The new table comprised of intersecting attributes and values. Table<T> intersectTable = new Table<T>(title + ", " + table.title); // First we select the attributes and values consisted in both tables Table<T> selectedOne = select(attribute, value); Table<T> selectedTwo = table.select(attribute, value); // Reset the temporary node back to the head to iterate the table. temp = selectedOne.head; // Then we add the first table into intersectTable. for (int i = 0; i < selectedOne.size; i++) { if (selectedTwo.contains(temp.data)) { // Create a copy to modify department without affecting // the original record. // We know the copy is of type T since we copied it from type T. @SuppressWarnings("unchecked") T copy = (T)temp.data.makeCopy(); copy.change("department", title + ", " + table.title); intersectTable.insert(copy); } else { intersectTable.insert(temp.data); } temp = temp.next; } // Then we ensure there are no duplicates by checking the second // table before we insert the row into intersectTable. temp = selectedTwo.head; for (int i = 0; i < selectedTwo.size; i++) { if (!intersectTable.contains(temp.data)) { intersectTable.insert(temp.data); } temp = temp.next; } return intersectTable; } /** * Getter method to retrieve the label of the table. * @return The title/label of the table. */ protected String getTitle() { return title; } /** * Removes the node/row with a matching ID from the table. * @param id The id of the node/row. */ void remove(String id) { // Checking the first record, then every other one afterwards. if (head != null) { if (head.data.check("id", id)) { head = head.next; size--; } else { Node prev = head; temp = head.next; // Walk the list and check for the record to remove. while(!temp.data.check("id", id) && temp.next != null) { temp = temp.next; prev = prev.next; } // Move the node previous to temp past temp. if (temp.data.check("id", id)) { prev.next = temp.next; size--; // Boundary checking. Update tail if tail is removed. if (prev.next == null) { tail = prev; } } } } } /** * Creates a new table comprised of nodes having a value for a specific * attribute. * @param attribute The attribute to select and restrict to. * @param value The value to select and restrict to. * @return A new table consisting of only the attributes and values * selected. */ Table<T> select(String attribute, String value) { // Create the new table Table<T> selectTable = new Table<T>(title); // Reset the temporary node back to the head to iterate the table. temp = head; // Iterate through the table to select the attribute value. for (int i = 0; i < size; i++) { if (temp.data.check(attribute, value)) { selectTable.insert(temp.data); } temp = temp.next; } return selectTable; } /** * Creates a new table comprised of nodes that occur in both tables. * @param table The other table to compare with. * @return A new table containing nodes that are contained in both tables. */ Table<T> union(Table<T> table) { // The new table consisting of elements of both tables. Table<T> unionTable = new Table<T>(title + ", " + table.title); // Reset the temporary node back to the head to iterate the table. temp = head; // Copy the original table into the unionTable. for (int i = 0; i < size; i++) { if (table.contains(temp.data)) { // Create a copy to modify department without affecting // the original record. // We know the copy is of type T since we copied it from type T. @SuppressWarnings("unchecked") T copy = (T)temp.data.makeCopy(); copy.change("department", title + ", " + table.title); unionTable.insert(copy); } else { unionTable.insert(temp.data); } temp = temp.next; } // Switch control to the table parameter. temp = table.head; // Copy the parameter table into unionTable and check for duplicates. for (int i = 0; i < table.size; i++) { if (!unionTable.contains(temp.data)) { unionTable.insert(temp.data); } temp = temp.next; } return unionTable; } /** * Prints the data in this entire table. * @return A string representation of the data in the table. */ public String toString() { // Creating a string buffer to concatenate strings to. StringBuffer string = new StringBuffer(); // Reset the temporary node back to the head to iterate the table. temp = head; string.append("\n=========================" + title + "=========================\n"); // Iterate through the entire table and append to the string. for (int i = 0; i < size; i++) { string.append(temp.toString()); string.append("\n-----------------------------" + "---------------------------------\n"); temp = temp.next; } string.append("=========================" + title + "=========================\n"); return string.toString(); } /** * Inner class node, each node is a row in the table. Each node also * contains the data and a pointer to the next row in the table. * @author Kevin Filanowski * @version 09/21/18 */ private class Node { /** * The data contained in this node. This contains the information * of one row in the table. */ private T data; /** The next row in the table.*/ private Node next; /** * Constructor initializes a new row in a table * @param data The data that will be contained in the node. **/ public Node(T data) { this.data = data; this.next = null; } /** * Prints the data in this node. * @return A string representation of the data in a row of the table. */ @Override public String toString() { return this.data.toString(); } } }
28.595016
78
0.636235
9913be60bda2d886c0c0a5ce5ebfb8c1c207001e
730
package allstructdati; /** * * @author Alessandro Mazzeo */ public class CodaOrdinata extends Coda { private Nodo first; @Override public void enqueue(Object ob) { Nodo appo = first; if (ob == null || !(ob instanceof Comparable)) { return; } if (isEmpty()) { Nodo n = new Nodo(ob, appo.next); appo = n; } else { Comparable i = (Comparable) appo.dato; while (appo.next != null && i.compareTo(ob) > 0) { appo = appo.next; i = (Comparable) appo.dato; } Nodo n = new Nodo(ob,null); appo.next = n; } } }
23.548387
63
0.453425
a17702771bb586f740eea0555472b4a9ca794237
277
package br.inatel.cdg.algebra.scene; public class Ponto { private double x, y; public Ponto(double a, double b) { this.x = a; this.y = b; } public double getX() { return x; } public double getY() { return y; } }
13.85
38
0.519856
3b3b3ac7d4ccc4a5088c5559e5781e4f503c0f38
2,891
/* * 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 xyz.joestr.postbox.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.InputStream; import java.util.Base64; /** * This class heavily abstracts the interaction between Base64 strings and * object. * * @param <T> Represents the type of the object * @author Joel */ public class Base64Objectifier<T> { // The object output stram Class<? extends ObjectOutputStream> objectOutputStream = null; // The object input stream Class<? extends ObjectInputStream> objectInputStream = null; /** * Create an instance. * * @param objectOutputStream The object output stream to use. * @param objectInputStream The object input stream to use. */ public Base64Objectifier(Class<? extends ObjectOutputStream> objectOutputStream, Class<? extends ObjectInputStream> objectInputStream) { // The object output stram this.objectOutputStream = objectOutputStream; // The object input stram this.objectInputStream = objectInputStream; } /** * Turns an object into a Base64 representation of it. (This method silences * exceptions and return null in case of an error.) * * @param object The object to turn into a Base64 string * @return The Base64 string. (In case of an error {@code null}) */ public String toBase64(T object) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream dataOutput = this.objectOutputStream.getConstructor(OutputStream.class).newInstance(outputStream); dataOutput.writeObject(object); dataOutput.close(); return Base64.getEncoder().encodeToString(outputStream.toByteArray()); } catch (Exception ex) { return null; } } /** * Turns a Base64 string into an object. (This method silences Exeptions and * returns null in case of an error.) * * @param data The Base64 string * @return The rebuilt object. (In case of an error {@code null}) */ public T fromBase64(String data) { try { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data)); ObjectInputStream dataInput = this.objectInputStream.getConstructor(InputStream.class).newInstance(inputStream); T object = (T) dataInput.readObject(); dataInput.close(); return object; } catch (Exception ex) { return null; } } }
31.423913
140
0.667589
3169cb5120ac15ebedba2457a27ea836a6004f15
3,964
package com.example.powellparstagram.fragments; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.example.powellparstagram.R; import com.example.powellparstagram.activities.LoginActivity; import com.parse.LogInCallback; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.SignUpCallback; public class LoginFragment extends Fragment { public static final String TAG = "LoginFragment"; private EditText etUsername; private EditText etPassword; private Button btnLogin; private Button btnRegister; public LoginFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_login, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (ParseUser.getCurrentUser() != null) { ((LoginActivity) getActivity()).goMainActivity(); } etUsername = view.findViewById(R.id.etUsernameRegister); etPassword = view.findViewById(R.id.etPasswordRegister); btnLogin = view.findViewById(R.id.btnLogin); btnRegister = view.findViewById(R.id.btnSignUp); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "Login button clicked"); String username = etUsername.getText().toString(); String password = etPassword.getText().toString(); loginUser(username, password); } }); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "Login button clicked"); String username = etUsername.getText().toString(); String password = etPassword.getText().toString(); registerUser(username, password); if (ParseUser.getCurrentUser() != null) { ((LoginActivity) getActivity()).goMainActivity(); } } }); } private void loginUser(String username, String password) { Log.i(TAG, "User logged in"); // If user has signed in, send user to MainActivity ParseUser.logInInBackground(username, password, new LogInCallback() { @Override public void done(ParseUser user, ParseException e) { if (e != null){ Log.e(TAG, "Issue with login", e); return; } ((LoginActivity)getActivity()).goMainActivity(); Toast.makeText(getActivity(), "Successful login", Toast.LENGTH_SHORT).show(); } }); } private void registerUser(String username, String password) { // Create the ParseUser ParseUser user = new ParseUser(); // Set core properties user.setUsername(username); user.setPassword(password); // Invoke signUpInBackground user.signUpInBackground(new SignUpCallback() { public void done(ParseException e) { if (e == null) { ((LoginActivity)getActivity()).goMainActivity(); } else { Log.e(TAG, "Issue with register", e); } } }); } }
33.880342
93
0.615035
011e9270418939e966a6fed60f6773d4a8838af3
1,574
package com.dazito.oauthexample.controller; import com.dazito.oauthexample.service.StorageService; import com.dazito.oauthexample.service.dto.request.StorageUpdateDto; import com.dazito.oauthexample.service.dto.response.GeneralResponseDto; import com.dazito.oauthexample.service.dto.response.StorageDto; import com.dazito.oauthexample.service.dto.response.StorageUpdatedDto; import com.dazito.oauthexample.utils.exception.AppException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.IOException; @RestController @RequestMapping(path = "/storage") public class StorageController { private final StorageService storageService; @Autowired public StorageController(StorageService storageService) { this.storageService = storageService; } @PatchMapping("/") public ResponseEntity<GeneralResponseDto<StorageUpdatedDto>> update(@RequestBody StorageUpdateDto storageUpdateDto) throws IOException, AppException { StorageUpdatedDto storageUpdatedDto = storageService.editData(storageUpdateDto); return ResponseEntity.ok(new GeneralResponseDto<>(null, storageUpdatedDto)); } @GetMapping("/hierarchy/{id:.+}") public ResponseEntity<GeneralResponseDto<StorageDto>> createHierarchy(@PathVariable Long id) throws IOException, AppException { StorageDto hierarchy = storageService.createHierarchy(id); return ResponseEntity.ok(new GeneralResponseDto<>(null, hierarchy)); } }
41.421053
154
0.798602
f146f0c029b30f7d6b5d6805f1ac6612e32ec798
1,031
import org.apache.edgent.function.Function; import java.util.ArrayList; public class EEGMapper implements Function<Double, Double> { double prevValue; double diff; int windowCounter; int recordsCount; int totalRecords; // ArrayList<Double> results; public EEGMapper(int cap) { // results = new ArrayList<>(cap); totalRecords = cap; } @Override public Double apply(Double value) { if(recordsCount > totalRecords) { return null; } diff += Math.pow(value - prevValue, 2); prevValue = value; windowCounter++; // a full one second has passed, perform the analytics if (windowCounter >= 178) { diff = Math.sqrt(diff); // results.add(diff); recordsCount++; windowCounter = 0; prevValue = 0.0; // System.out.println("apply: " + recordsCount); return diff; } else return null; } }
21.479167
62
0.552861
4df9075bba23e1d688403819b379e483aea9e416
936
package desafio02; import java.text.DecimalFormat; public class Desafio02 { private final String padrao = "##,###0.0#"; private DecimalFormat formato = new DecimalFormat(padrao); /** * Calcula a sequencia de números a partir de um {@code Double} número de entrada. * @param numero {@code Double} * @return {@code Double} o resultado do cálculo da sequência. */ private Double calcularSequencia(Double numero) { Double resultado = 0d; for (double i = 0; numero - i > 0; i++) { resultado += (numero - i)/(i + 1); } return resultado; } /** * Exibe no console a sequência de números a partir da entrada de um {@code Double} número. * @param numero {@code Double} */ public void exibirSequencia(Double numero) { formato.setMaximumFractionDigits(13); System.out.println( "Para N = " + formato.format(numero) + " A = " + formato.format(calcularSequencia(numero)) ); } }
22.829268
92
0.65812
b7ccd51ef2eaf79cb49821881b82450cdf7e27ce
2,403
package io.wollinger.hkmanager; import gnu.crypto.mode.IMode; import gnu.crypto.mode.ModeFactory; import gnu.crypto.pad.IPad; import gnu.crypto.pad.PadFactory; import org.json.JSONObject; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Arrays; import java.util.Base64; import java.util.HashMap; import java.util.Map; public class SaveLoader { private static final String CIPHER_MODE = "ECB"; private static final String CIPHER_ALGO = "Rijndael"; private static final String CIPHER_PAD = "PKCS7"; private static final byte[] RIJNDAEL_KEY = "UKu52ePUBwetZ9wNX88o54dnfKRu0T1l".getBytes(); private static final int BLOCK_SIZE = 16; private static byte[] crypt(byte[] input) throws Exception{ Map<String, Object> attributes = new HashMap<>(); attributes.put(IMode.KEY_MATERIAL, RIJNDAEL_KEY); attributes.put(IMode.CIPHER_BLOCK_SIZE, BLOCK_SIZE); attributes.put(IMode.STATE, IMode.DECRYPTION); IMode mode = ModeFactory.getInstance(CIPHER_MODE, CIPHER_ALGO, BLOCK_SIZE); mode.init(attributes); int bs = mode.currentBlockSize(); IPad padding = PadFactory.getInstance(CIPHER_PAD); padding.init(bs); byte[] pad = padding.pad(input, 0, input.length); byte[] pt = new byte[input.length + pad.length]; byte[] ct = new byte[pt.length]; System.arraycopy(input, 0, pt, 0, input.length); System.arraycopy(pad, 0, pt, input.length, pad.length); for (int i = 0; i + bs < pt.length; i += bs) mode.update(pt, i, ct, i); int unpad = padding.unpad(ct, 0, ct.length); byte[] output = new byte[ct.length - unpad]; System.arraycopy(ct, 0, output, 0, ct.length); return output; } private static byte[] decrypt(String input) throws Exception { byte[] message = input.getBytes(); byte[] tmp = Arrays.copyOfRange(message, 0, message.length-1); return crypt(Base64.getMimeDecoder().decode(new String(tmp))); } public static JSONObject loadSave(File dir) throws Exception { String str = new String(Files.readAllBytes(dir.toPath()), StandardCharsets.UTF_8); if(str.charAt(0) == '{') return new JSONObject(str.trim()); else return new JSONObject(new String(decrypt(str)).trim()); } }
35.865672
93
0.665418
5760584898e0a6bd3939cba086a3a9f270a16437
3,950
/** * Mule Development Kit * Copyright 2010-2011 (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mule.devkit.it.studio; import org.mule.api.annotations.Configurable; import org.mule.api.annotations.Module; import org.mule.api.annotations.Processor; import org.mule.api.annotations.Source; import org.mule.api.annotations.display.FriendlyName; import org.mule.api.annotations.display.Icons; import org.mule.api.annotations.display.Password; import org.mule.api.annotations.display.Placement; import org.mule.api.annotations.display.Summary; import org.mule.api.callback.SourceCallback; /** * Module to test annotations applied to parameters * * @author MuleSoft inc */ @Module(name = "metadata", description = "This description overrides class-level javadoc.") @Icons(connectorSmall = "../../../my-icons/my-cloud-connector-24x16.png", connectorLarge = "../../../my-icons/my-cloud-connector-48x32.png", endpointSmall = "../../../my-icons/my-endpoint-24x16.png", endpointLarge = "../../../my-icons/my-endpoint-48x32.png", transformerSmall = "../../../my-icons/my-transformer-24x16.png", transformerLarge = "../../../my-icons/my-transformer-48x32.png") public class MetadataModule { /** * Configurable field in group 1 */ @Configurable @Placement(group = "Group1", order = 1) @FriendlyName("non-default caption") private String configurable1; /** * Configurable field in group 2 */ @Configurable @Placement(group = "Group2", order = 2) @Summary("non-default description") private String configurable2; /** * Configurable field in group 1 */ @Configurable @Placement(group = "Group1", order = 3) @FriendlyName("non-default caption") @Summary("non-default description") private String configurable3; /** * A processor method with Studio metadata * * @param showFirst parameter with no input group * @param advanced1 parameter in Advanced input group * @param advanced2 parameter in Advanced input group * @param general parameter in General input group * @param password password parameter */ @Processor public void processor(@Placement(order = 1) @FriendlyName("non-default caption") @Summary("non-default description") String showFirst, @Placement(group = "Advanced", order = 2) @FriendlyName("non-default caption") String advanced1, @Placement(group = "Advanced", order = 1) @Summary("non-default description") String advanced2, String general, @Password String password) { } /** * A source method with Studio metadata * * @param sourceCallback the source callback * @param advanced1 parameter in Advanced input group * @param advanced2 parameter in Advanced input group * @param general parameter in General input group */ @Source public void source(SourceCallback sourceCallback, @Placement(group = "Advanced", order = 1) @FriendlyName("non-default caption") String advanced1, @Placement(group = "Advanced", order = 2) @Summary("non-default description") String advanced2, @Placement(order = 1) String general) { } }
41.578947
140
0.669873
be1e09abe699a7480305842e31f9088508c9dde5
768
package com.tangcheng.datasources.aop.business.db2; import com.tangcheng.datasources.aop.mapper.UserDetailMapper; import com.tangcheng.datasources.aop.model.UserDetail; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by tang.cheng on 2017/3/9. */ @Repository public class Test2Biz { @Autowired private UserDetailMapper userDetailMapper; public List<UserDetail> selectAll() { return userDetailMapper.selectAll(); } public void postNew(String name, String qq) { UserDetail userDetail = new UserDetail(); userDetail.setName(name); userDetail.setQq(qq); userDetailMapper.insert(userDetail); } }
23.272727
62
0.733073
e8aecc5ab233a7cc9c4ab1c24a8ec8869495f25e
414
package de.innovationhub.prox.projectservice.project; import io.micrometer.core.lang.Nullable; import java.util.List; import org.springframework.data.domain.Sort; public interface ProjectRepositoryCustom { List<Project> filterProjects( @Nullable ProjectStatus status, @Nullable String[] specializationKeys, @Nullable String[] moduleTypeKeys, @Nullable String text, Sort sort); }
25.875
53
0.756039
bee4bb73092d3c2d4e708fbe47d8b6a57212d9a3
2,913
/* * Copyright (C) 2020 xuexiangjys(xuexiangjys@163.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.xuexiang.xuidemo.fragment.components.pickerview; import android.widget.TextView; import com.xuexiang.xpage.annotation.Page; import com.xuexiang.xui.widget.picker.XRangeSlider; import com.xuexiang.xui.widget.picker.XSeekBar; import com.xuexiang.xuidemo.R; import com.xuexiang.xuidemo.base.BaseFragment; import butterknife.BindView; /** * @author xuexiang * @since 2020-01-04 23:51 */ @Page(name = "SeekBar\n滑块选择器,支持双向范围选择") public class SeekBarFragment extends BaseFragment { @BindView(R.id.xrs_normal) XRangeSlider xrsNormal; @BindView(R.id.tv_number) TextView tvNumber; @BindView(R.id.xrs_bubble) XRangeSlider xrsBubble; @BindView(R.id.tv_bubble) TextView tvBubble; @BindView(R.id.xsb) XSeekBar xsb; @BindView(R.id.tv_xsb) TextView tvXsb; @Override protected int getLayoutId() { return R.layout.fragment_seekbar; } @Override protected void initViews() { } @Override protected void initListeners() { xrsNormal.setOnRangeSliderListener(new XRangeSlider.OnRangeSliderListener() { @Override public void onMaxChanged(XRangeSlider slider, int maxValue) { tvNumber.setText(String.format("%d %d", slider.getSelectedMin(), slider.getSelectedMax())); } @Override public void onMinChanged(XRangeSlider slider, int minValue) { tvNumber.setText(String.format("%d %d", slider.getSelectedMin(), slider.getSelectedMax())); } }); xrsBubble.setStartingMinMax(60, 100); xrsBubble.setOnRangeSliderListener(new XRangeSlider.OnRangeSliderListener() { @Override public void onMaxChanged(XRangeSlider slider, int maxValue) { tvBubble.setText(String.format("%d %d", slider.getSelectedMin(), slider.getSelectedMax())); } @Override public void onMinChanged(XRangeSlider slider, int minValue) { tvBubble.setText(String.format("%d %d", slider.getSelectedMin(), slider.getSelectedMax())); } }); xsb.setDefaultValue(50); xsb.setOnSeekBarListener((seekBar, newValue) -> tvXsb.setText(String.valueOf(newValue))); } }
31.322581
111
0.672846
161c64b108aeb0259fd57722fc2413b608463dcc
2,260
/* * FirstAid * Copyright (C) 2017-2020 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ichttt.mods.firstaid.common.util; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.util.math.AxisAlignedBB; import javax.annotation.Nullable; public class ProjectileHelper { //PLAYER: 0, 0, 0, 0.6, 1.6, 0.6 private static final AxisAlignedBB HEAD_AABB = new AxisAlignedBB(0D, 1.5D, 0D, 1D, 2.0D, 1D); private static final AxisAlignedBB MAIN_AABB = new AxisAlignedBB(0D, 0.8D, 0D, 1D, 1.5D, 1D); private static final AxisAlignedBB LEG_AABB = new AxisAlignedBB(0D, 0.4D, 0D, 1D, 0.8D, 1D); private static final AxisAlignedBB FEET_AABB = new AxisAlignedBB(0D, 0.0D, 0D, 1D, 0.4D, 1D); @Nullable public static EntityEquipmentSlot getPartByPosition(Entity hittingObject, EntityPlayer toTrack) { if (testAABB(hittingObject, toTrack, HEAD_AABB)) return EntityEquipmentSlot.HEAD; if (testAABB(hittingObject, toTrack, MAIN_AABB)) return EntityEquipmentSlot.CHEST; if (testAABB(hittingObject, toTrack, LEG_AABB)) return EntityEquipmentSlot.LEGS; if (testAABB(hittingObject, toTrack, FEET_AABB)) return EntityEquipmentSlot.FEET; return null; } private static boolean testAABB(Entity hittingObject, EntityPlayer toTest, AxisAlignedBB aabb) { AxisAlignedBB toTestAABB = hittingObject.getEntityBoundingBox(); return (toTestAABB.minY - toTest.posY) < aabb.maxY && (toTestAABB.maxY - toTest.posY) > aabb.minY; } }
42.641509
106
0.724779
c7ef9692e36c254e163bf7a80afb8f09fae942c9
209
package com.woodplc.cora.refactoring; import java.util.Collection; import java.util.List; public interface Refactoring { List<String> refactor(); Collection<? extends String> getErrors(); }
16.076923
43
0.717703
0290e07b9481c4debb9f97dc83fc3dacffdcde5d
1,792
package com.lunchteam.lunchrestapi.api.dto.file; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import org.springframework.core.io.Resource; @Getter @AllArgsConstructor @NoArgsConstructor @Builder public class FileResponseDto { private Long id; // originalFileName private String fileName; // storedFileName private String fileKey; private String fileExtension; private String fileSize; // mime-type private String fileType; private Long targetId; private Long groupId; private int fileNo; private LocalDateTime insertDateTime; private LocalDateTime updateDateTime; // for download file. private Resource resource; private static FileResponseDto allOf(FileResult file) { return FileResponseDto.builder() .id(file.getId()) .fileName(file.getOriginalFileName()) .fileKey(file.getStoredFileName()) .fileExtension(file.getFileExtension()) .fileType(file.getFileType()) .targetId(file.getTargetId()) .groupId(file.getGroupId()) .fileNo(file.getFileNo()) .insertDateTime(file.getInsertDateTime()) .updateDateTime(file.getUpdateDateTime()) .build(); } public static List<FileResponseDto> listOf(List<FileResult> files) { if (!files.isEmpty()) { List<FileResponseDto> result = new ArrayList<>(); for (FileResult entity : files) { result.add(FileResponseDto.allOf(entity)); } return result; } else { return null; } } }
25.239437
72
0.651228
bbf8e3363b6b12e7b6a965815a89bbf067d49042
8,301
// Copyright 2019, California Institute of Technology ("Caltech"). // U.S. Government sponsorship acknowledged. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // * Neither the name of Caltech nor its operating division, the Jet Propulsion // Laboratory, nor the names of its contributors may be used to endorse or // promote products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 gov.nasa.pds.objectAccess; import gov.nasa.arc.pds.xml.generated.FileAreaObservational; import java.io.File; import java.net.URL; /** * Factory pattern class to create specific object exporters. * * @author dcberrio */ public class ExporterFactory { // Utility class - avoid instantiation. private ExporterFactory() { // never called } /** * Gets an instance of a Array2DImage exporter. * * @param label the PDS label file * @param fileAreaIndex the file area inside the label containing the data to export * @return an instance of a TwoDImageExporter * @throws Exception */ public static TwoDImageExporter get2DImageExporter(File label, int fileAreaIndex) throws Exception { return get2DImageExporter(label.toURI().toURL(), fileAreaIndex); } /** * Gets an instance of a Array2DImage exporter. * * @param label the PDS label file * @param fileAreaIndex the file area inside the label containing the data to export * @return an instance of a TwoDImageExporter * @throws Exception */ public static TwoDImageExporter get2DImageExporter(URL label, int fileAreaIndex) throws Exception { return new TwoDImageExporter(label, fileAreaIndex); } /** * Gets an instance of an Array3DImage exporter. * * @param label the PDS label file. * @param fileAreaIndex the file area inside the label containing the data to export. * @return an instance of a ThreeDImageExporter. * @throws Exception */ public static ThreeDImageExporter get3DImageExporter(File label, int fileAreaIndex) throws Exception { return get3DImageExporter(label.toURI().toURL(), fileAreaIndex); } /** * Gets an instance of an Array3DImage exporter. * * @param label the PDS label file. * @param fileAreaIndex the file area inside the label containing the data to export. * @return an instance of a ThreeDImageExporter. * @throws Exception */ public static ThreeDImageExporter get3DImageExporter(URL label, int fileAreaIndex) throws Exception { return new ThreeDImageExporter(label, fileAreaIndex); } /** * Gets an instance of an Array3DSpectrum exporter. * * @param label the PDS label file. * @param fileAreaIndex the file area inside the label containing the data to export. * @return an instance of a ThreeDSpectrumExporter. * @throws Exception */ public static ThreeDSpectrumExporter get3DSpectrumExporter(File label, int fileAreaIndex) throws Exception { return get3DSpectrumExporter(label.toURI().toURL(), fileAreaIndex); } /** * Gets an instance of an Array3DSpectrum exporter. * * @param label the PDS label file. * @param fileAreaIndex the file area inside the label containing the data to export. * @return an instance of a ThreeDSpectrumExporter. * @throws Exception */ public static ThreeDSpectrumExporter get3DSpectrumExporter(URL label, int fileAreaIndex) throws Exception { return new ThreeDSpectrumExporter(label, fileAreaIndex); } /** * Gets an instance of a Table exporter. * * @param label the PDS label file * @param fileAreaIndex the file area inside the label containing the data to export * @return an instance of a TableExporter * @throws Exception */ public static TableExporter getTableExporter(File label, int fileAreaIndex) throws Exception { return getTableExporter(label.toURI().toURL(), fileAreaIndex); } /** * Gets an instance of a Table exporter. * * @param label the PDS label file * @param fileAreaIndex the file area inside the label containing the data to export * @return an instance of a TableExporter * @throws Exception */ public static TableExporter getTableExporter(URL label, int fileAreaIndex) throws Exception { return new TableExporter(label, fileAreaIndex); } /** * Gets an instance of a Array2DImage exporter. * * @param fileArea the file area object containing the data to export * @param provider the object provider pointing to the PDS4 label * @return an instance of a TwoDImageExporter * @throws Exception */ public static TwoDImageExporter get2DImageExporter(FileAreaObservational fileArea, ObjectProvider provider) throws Exception { return new TwoDImageExporter(fileArea, provider); } /** * Gets an instance of an Array3DImage exporter. * * @param fileArea the file area object containing the data to export * @param provider the object provider pointing to the PDS4 label * @return an instance of a ThreeDImageExporter. * @throws Exception */ public static ThreeDImageExporter get3DImageExporter(FileAreaObservational fileArea, ObjectProvider provider) throws Exception { return new ThreeDImageExporter(fileArea, provider); } /** * Gets an instance of an Array3DSpectrum exporter. * * @param fileArea the file area object containing the data to export * @param provider the object provider pointing to the PDS4 label * @return an instance of a ThreeDSpectrumExporter. * @throws Exception */ public static ThreeDSpectrumExporter get3DSpectrumExporter(FileAreaObservational fileArea, ObjectProvider provider) throws Exception { return new ThreeDSpectrumExporter(fileArea, provider); } /** * Gets an instance of a Table exporter. * * @param fileArea the file area object containing the data to export * @param provider the object provider pointing to the PDS4 label * @return an instance of a TableExporter * @throws Exception */ public static TableExporter getTableExporter(FileAreaObservational fileArea, ObjectProvider provider) throws Exception { return new TableExporter(fileArea, provider); } /** * Gets a table reader object for a given table and data file. * * @param tableObject the table object, binary, character, or delimited * @param dataFile the data file containing the table * @return a table reader for the table * @throws Exception if there is an error reading the file */ public static TableReader getTableReader(Object tableObject, File dataFile) throws Exception { return getTableReader(tableObject, dataFile.toURI().toURL()); } /** * Gets a table reader object for a given table and data file. * * @param tableObject the table object, binary, character, or delimited * @param dataFile the data file containing the table * @return a table reader for the table * @throws Exception if there is an error reading the file */ public static TableReader getTableReader(Object tableObject, URL dataFile) throws Exception { return new TableReader(tableObject, dataFile, true); } }
37.391892
110
0.746657
0167b2e87124d45fc5eb686072a43ee64f7ae1b0
573
package top.hellholestudios.xgn.jmj.scoring.classic; import top.hellholestudios.xgn.jmj.RonWrapper; import top.hellholestudios.xgn.jmj.scoring.AgariInfo; import top.hellholestudios.xgn.jmj.scoring.Yaku; public class Haitei extends Yaku { public Haitei() { super("hdly", "海底撈月"); } @Override public boolean isNormalOnly() { return false; } @Override public int check(RonWrapper ron) { if(ron.agariInfo.source== AgariInfo.TileSource.Haitei){ return 1; }else{ return 0; } } }
22.038462
63
0.640489
24f11d96ac7800d4b724bf71fb93e5ff40691115
1,090
package com.example.weixin.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import com.example.weixin.controller.MessageReceiverController; import com.example.weixin.domain.InMessage; import com.example.weixin.domain.OUtMessage; import com.example.weixin.service.MessageService; @Service public class MessageServiceImpl implements MessageService{ private static final Logger LOG=LoggerFactory.getLogger(MessageReceiverController.class); @Autowired // 自动注入 @Qualifier("inMessageTemplate") // 根据名字自动注入 private RedisTemplate<String, ? extends InMessage> inMessageTemplate; @Override public OUtMessage onMessage(InMessage msg) { // TODO Auto-generated method stub LOG.trace("转换后消息对象:\n{}\n",msg); inMessageTemplate.convertAndSend("test_weixin"+msg.getMsgType(), msg); return null; } }
33.030303
91
0.790826
e97490f009fd137398d35af6d9d339351af1c7fa
2,026
package org.jesperancinha.jtd.jee.girl.bands.servlets; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.BLUE; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.BRIGHT_CYAN; import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.MAGENTA; import static org.jesperancinha.console.consolerizer.console.Consolerizer.printRainbowTitleLn; @WebServlet("/LogoutGirlBandRecordStoreServlet") public class LogoutGirlBandRecordStoreServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); final var cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { cookie.setMaxAge(0); response.addCookie(cookie); if (cookie.getName() .equals("JSESSIONID")) { printRainbowTitleLn("JSESSIONID=" + cookie.getValue()); } else { BRIGHT_CYAN.printGenericLn("Found cookie %s!. Invalidating...", cookie); BRIGHT_CYAN.printGenericLn("%s=%s", cookie.getName(), cookie.getValue()); } } } HttpSession httpSesssion = request.getSession(false); MAGENTA.printGenericLn("Username is=%s", httpSesssion.getAttribute("username")); if (httpSesssion != null) { httpSesssion.invalidate(); } BLUE.printGenericLn("Session %s is now invalidated", httpSesssion); response.sendRedirect("/jee-app-2-2-wildfly-1.0.0-SNAPSHOT"); } }
45.022222
104
0.692004
2dcf2c082f24094c731e8ce68b4051fd7e9ed0b0
634
/* * 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 export.model; import javax.xml.bind.annotation.XmlElement; /** * * @author kougi */ public class RoleWrapper { private RoleModel[] roles; public RoleWrapper() { } public RoleWrapper(RoleModel[] roles) { this.roles = roles; } @XmlElement(name="role") public RoleModel[] getRoles() { return roles; } public void setRoles(RoleModel[] roles) { this.roles = roles; } }
19.212121
79
0.641956
ff0cb715f5f4cd7b78f43c33bf8decb919683c52
1,485
public class S1415ThekthLexicographicalStringAllHappyStringsLengthN { public String getHappyString(int n, int k) { if (n == 1) { if (k == 1) { return "a"; } else if (k == 2) { return "b"; } else if (k == 3) { return "c"; } else { return ""; } } int total = 3*(0x1 << (n-1)); if (k > total) { return ""; } StringBuilder sb = new StringBuilder(); char last = '\0'; int cnt = 0; int remains = n; while (cnt < k && remains > 0) { int c = 0x1 << (remains-1); // a if (last != 'a') { if (cnt + c < k) { cnt += c; } else { sb.append('a'); last = 'a'; remains--; continue; } } if (last != 'b') { if (cnt + c < k) { cnt += c; } else { sb.append('b'); last = 'b'; remains--; continue; } } if (last != 'c') { assert cnt + c >= k; sb.append('c'); last = 'c'; remains--; } } return sb.toString(); } }
26.517857
69
0.289562
5d712edce1211ad4b78454bbae8f8c22815544c6
490
package com.jannchie.biliob.constant; /** * @author Jannchie */ public enum AgendaState { /** * WAITING: 等待被处理 * FINISHED: 已经处理完毕 * CLOSED: 不会处理此议题 * PENDING:正在处理此议题 * DUPLICATE:该议题重复 */ WAITING((byte) 0), FINISHED((byte) 1), CLOSED((byte) 2), PENDING((byte) 3), DUPLICATE((byte) 4); private final Byte value; AgendaState(Byte i) { this.value = i; } public Byte getValue() { return value; } }
15.806452
37
0.555102