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
|
---|---|---|---|---|---|
f5c6dd81dc8c64a687e3f1d641e9fff23b07e6df | 4,969 | /*MIT License
*
*Copyright (c) 2021 AlgoTeam
*
*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 com.algorithmlx.dimore.setup;
import com.algorithmlx.dimore.DimOre;
import com.algorithmlx.dimore.block.ModOreBase;
import com.algorithmlx.dimore.block.OreBase;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
public class DimOreReg {
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, DimOre.ModId);
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, DimOre.ModId);
public static void init() {
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());
}
public static final RegistryObject<OreBase> NETHER_COAL_ORE = BLOCKS.register("nether_coal_ore", OreBase::new);
public static final RegistryObject<OreBase> NETHER_IRON_ORE = BLOCKS.register("nether_iron_ore", OreBase::new);
public static final RegistryObject<OreBase> NETHER_LAPIS_LAZULI_ORE = BLOCKS.register("nether_lapis_lazuli_ore", OreBase::new);
public static final RegistryObject<OreBase> NETHER_REDSTONE_ORE = BLOCKS.register("nether_redstone_ore", OreBase::new);
public static final RegistryObject<OreBase> NETHER_DIAMOND_ORE = BLOCKS.register("nether_diamond_ore", OreBase::new);
public static final RegistryObject<OreBase> NETHER_EMERALD_ORE = BLOCKS.register("nether_emerald_ore", OreBase::new);
public static final RegistryObject<OreBase> END_QUARTZ_ORE = BLOCKS.register("end_quartz_ore", OreBase::new);
public static final RegistryObject<OreBase> END_COAL_ORE = BLOCKS.register("end_coal_ore", OreBase::new);
public static final RegistryObject<OreBase> END_IRON_ORE = BLOCKS.register("end_iron_ore", OreBase::new);
public static final RegistryObject<OreBase> END_GOLDEN_ORE = BLOCKS.register("end_golden_ore", OreBase::new);
public static final RegistryObject<OreBase> END_LAPIS_LAZULI_ORE = BLOCKS.register("end_lapis_lazuli_ore", OreBase::new);
public static final RegistryObject<OreBase> END_REDSTONE_ORE = BLOCKS.register("end_redstone_ore", OreBase::new);
public static final RegistryObject<OreBase> END_DIAMOND_ORE = BLOCKS.register("end_diamond_ore", OreBase::new);
public static final RegistryObject<OreBase> END_EMERALD_ORE = BLOCKS.register("end_emerald_ore", OreBase::new);
//integration
public static final RegistryObject<ModOreBase> NETHER_COPPER_ORE = DimOreConfig.allowIntegration.get().equals(true) /*&& ModList.get().isLoaded("thermal_foundation") || ModList.get().isLoaded("mekanism") || ModList.get().isLoaded("immersiveengineering")*/ ? BLOCKS.register("nether_copper_ore", ModOreBase::new) : null;
public static final RegistryObject<ModOreBase> NETHER_TIN_ORE = DimOreConfig.allowIntegration.get().equals(true) /*&& ModList.get().isLoaded("thermal_foundation") || ModList.get().isLoaded("mekanism") || ModList.get().isLoaded("immersiveengineering")*/ ? BLOCKS.register("nether_tin_ore", ModOreBase::new) : null;
public static final RegistryObject<ModOreBase> END_COPPER_ORE = DimOreConfig.allowIntegration.get().equals(true) /*&& ModList.get().isLoaded("thermal_foundation") || ModList.get().isLoaded("mekanism") || ModList.get().isLoaded("immersiveengineering")*/ ? BLOCKS.register("end_copper_ore", ModOreBase::new) : null;
public static final RegistryObject<ModOreBase> END_TIN_ORE = DimOreConfig.allowIntegration.get().equals(true) /*&& ModList.get().isLoaded("thermal_foundation") || ModList.get().isLoaded("mekanism") || ModList.get().isLoaded("immersiveengineering")*/ ? BLOCKS.register("end_tin_ore", ModOreBase::new) : null;
}
| 77.640625 | 323 | 0.782652 |
2e4e3141e862c180430f44ea193a85033898597b | 1,753 | package org.radargun.stages.test.legacy;
import org.radargun.Operation;
/**
* Implementations specify what operations should be executed during the stress test.
* Each stressor thread uses single instance of this class.
*
* @author Radim Vansa <[email protected]>
*/
public abstract class OperationLogic {
protected LegacyStressor stressor;
/**
* Initialize this logic. No {@link org.radargun.Operation operations}
* should be executed here.
*/
public void init(LegacyStressor stressor) {
this.stressor = stressor;
}
/**
* Release resources held by this logic. To be overriden in inheritors.
*/
public void destroy() {}
/**
* Execute operation on the stressor using its
* {@link LegacyStressor#makeRequest(Invocation)} makeRequest} method.
* This operation accounts to the statistics.
* Note: logic may actually execute more operations
*
* @return The method returns object in order to avoid JIT optimization by the compiler.
* @param operation
*/
public abstract void run(Operation operation) throws RequestException;
/**
* Handle started transaction - the logic should call {@link LegacyStressor#wrap(Object)} on all resources
* used in the further invocation
*/
public void transactionStarted() {
throw new UnsupportedOperationException("Transactions are not supported.");
}
/**
* Handle finished transaction - drop all wrapped resources
*/
public void transactionEnded() {
throw new UnsupportedOperationException("Transactions are not supported.");
}
public static class RequestException extends Exception {
public RequestException(Throwable cause) {
super(cause);
}
}
}
| 29.711864 | 109 | 0.702225 |
b5e7eebc1bd26b41a1bbcb3a87538e6f7f974c19 | 7,057 | package id.unify.gaitauth_sample_app.fragments;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.Locale;
import id.unify.gaitauth_sample_app.GaitAuthService;
import id.unify.gaitauth_sample_app.Preferences;
import id.unify.gaitauth_sample_app.R;
import id.unify.gaitauth_sample_app.databinding.FragmentSendFeaturesBinding;
public class SendFeaturesFragment extends Fragment {
private static final String TAG = "SendFeaturesFragment";
public static final String SCREEN_TITLE = "Send Features";
public static final String ARG_KEY_IS_TRAINING = "IS_TRAINING";
private SendFeaturesListener callback;
private boolean collecting = false;
private FragmentSendFeaturesBinding viewBinding;
public static SendFeaturesFragment build(boolean isTraining) {
Bundle arg = new Bundle();
arg.putBoolean(ARG_KEY_IS_TRAINING, isTraining);
SendFeaturesFragment ret = new SendFeaturesFragment();
ret.setArguments(arg);
return ret;
}
// Handle broadcasts from FeatureCollectionService to bump collectedCount
private BroadcastReceiver featureStatsUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getActivity() != null) {
int count = intent.getIntExtra(
GaitAuthService.BROADCAST_EXTRA_FEATURE_COUNT, 0);
updateCollectedCountUI(count);
}
}
};
private void updateCollectedCountUI(int count) {
runOnUiThread(() -> viewBinding.collectedCount.setText(String.format(Locale.US, "%d",
count)));
}
private void runOnUiThread(Runnable action) {
if (getActivity() != null) {
getActivity().runOnUiThread(action);
}
}
private void parseArgumentsAndUpdateCollectingState() {
Bundle arguments = getArguments();
if (arguments != null) {
collecting = arguments.getBoolean(ARG_KEY_IS_TRAINING, false);
}
}
// Setup broadcast receiver to get collectedCount from foreground service
private void setupBroadcastReceiver(Context context) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(GaitAuthService.ACTION_FEATURE_COLLECTED_COUNT_UPDATE);
LocalBroadcastManager.getInstance(context).registerReceiver(featureStatsUpdateReceiver,
intentFilter);
}
// refresh UI component based on current state
private void refreshUI() {
updateCollectedCountUI(Preferences.getInt(Preferences.FEATURE_COLLECTED_COUNT));
if (collecting) {
viewBinding.startPauseCollectionButton.setText(R.string.stop_collection_button);
} else {
viewBinding.startPauseCollectionButton.setText(R.string.start_collection_button);
}
}
private void setupStartOrStopBtnCallback() {
viewBinding.startPauseCollectionButton.setOnClickListener(v -> {
if (collecting) {
callback.onStopCollectionBtnPressed();
collecting = false;
} else {
callback.onStartCollectionBtnPressed();
collecting = true;
}
refreshUI();
});
}
private void setupSendFeaturesBtnCallback(Context context) {
viewBinding.sendHttpFeaturesButton.setOnClickListener(v -> {
if (collecting) {
Toast.makeText(context, "Need to stop collecting to add features.",
Toast.LENGTH_LONG).show();
return;
}
// this call can be blocking
AsyncTask.execute(() -> {
int totalUploaded = callback.onSendFeaturesPressed(viewBinding.editTextHttpServer.getText().toString());
if (totalUploaded == 0) {
return;
}
// update UI needs to be in main thread
runOnUiThread(() -> {
Preferences.put(Preferences.FEATURE_COLLECTED_COUNT, 0);
updateCollectedCountUI(0);
});
});
});
}
@SuppressLint("DefaultLocale")
private void setupCompareFeaturesBtnCallback(Context context) {
viewBinding.compareHttpFeaturesButton.setOnClickListener(v -> {
if (collecting) {
Toast.makeText(context, "Need to stop collecting to add features.",
Toast.LENGTH_LONG).show();
return;
}
// this call can be blocking
AsyncTask.execute(() -> {
double cosineSimilarity = callback.onCompareFeaturesPressed(viewBinding.editTextHttpServer.getText().toString());
// update UI needs to be in main thread
runOnUiThread(() -> {
Toast.makeText(context, String.format("Comparison result: %f", cosineSimilarity),
Toast.LENGTH_LONG).show();
// Updates count
Preferences.put(Preferences.FEATURE_COLLECTED_COUNT, 0);
updateCollectedCountUI(0);
});
});
});
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
viewBinding = FragmentSendFeaturesBinding.inflate(inflater, container,
false);
View view = viewBinding.getRoot();
Context context = getContext();
if (context == null) {
Log.i(TAG, "Context is null, early exit onCreateView");
return view;
}
parseArgumentsAndUpdateCollectingState();
setupBroadcastReceiver(context);
refreshUI();
setupStartOrStopBtnCallback();
setupSendFeaturesBtnCallback(context);
setupCompareFeaturesBtnCallback(context);
return view;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
callback = (SendFeaturesListener) context;
}
@Override
public void onResume() {
super.onResume();
refreshUI();
}
public interface SendFeaturesListener {
void onStartCollectionBtnPressed();
void onStopCollectionBtnPressed();
int onSendFeaturesPressed(String serverUrl);
double onCompareFeaturesPressed(String serverUrl);
}
} | 34.257282 | 129 | 0.64064 |
d371d29ec23146cd9e04c8935f1357ada632c2b7 | 4,401 | import java.io.*;
public class Test {
public static void main(String[] args) {
int[] array = {
8413, 9917, 5236, 1644, 4512, 7173, 3616, 2606, 8762, 2968, 595, 4903, 7077, 3509, 533, 5523, 1192, 7378, 8718, 2400,
1526, 9543, 7403, 5739, 7022, 4550, 1729, 8374, 8270, 5057, 7043, 9447, 2021, 6520, 8678, 318, 2911, 6552, 5918, 1261,
9798, 3218, 7419, 7224, 5974, 7891, 6016, 2067, 5388, 7616, 9049, 662, 4565, 152, 2879, 6512, 3339, 5830, 7233, 6079,
8902, 5612, 6074, 2702, 3413, 8211, 4000, 3944, 4572, 4153, 6029, 8199, 9909, 8906, 2366, 8938, 5137, 53, 5446, 8063,
6352, 7986, 771, 83, 2023, 5403, 3755, 4400, 4454, 6181, 5513, 8894, 6183, 5798, 4103, 3950, 4903, 7215, 2379, 5405,
4657, 4988, 9835, 8752, 1523, 6932, 7747, 1880, 7191, 1478, 6963, 3430, 4594, 5934, 6836, 6599, 8647, 2323, 8404, 8731,
8716, 4294, 8172, 4126, 4354, 5885, 9127, 3302, 6283, 5380, 9258, 4274, 112, 8930, 8840, 4960, 1645, 3395, 2501, 2400,
3475, 660, 2484, 1218, 3858, 7992, 1089, 1509, 2378, 8351, 949, 388, 550, 7582, 4680, 487, 8420, 2702, 944, 9178, 9288,
7572, 499, 8736, 7603, 938, 1798, 20, 448, 3984, 2175, 8067, 3220, 8862, 3777, 5629, 5134, 2563, 5471, 3895, 1527, 3672,
1002, 5993, 7381, 2963, 7321, 5227, 755, 6425, 6004, 7112, 8018, 7794, 652, 33, 8160, 8385, 1882, 5760, 9752, 5566, 6095,
8148, 606, 5243, 5008, 3658, 309, 9759, 9966, 5848, 1882, 3230, 3969, 3310, 5938, 5840, 7671, 632, 9229, 4237, 454, 7033,
4348, 8013, 4156, 5167, 5262, 1700, 6177, 6886, 2186, 701, 7755, 7647, 3416, 9660, 5470, 9443, 2629, 6728, 2486, 1078, 5786,
2140, 7477, 7932, 9249, 4498, 6145, 1990, 3294, 1618, 6381, 8131, 3060, 4537, 5030, 1631, 980, 7746, 989, 9808, 9187, 1048,
4675, 8106, 6760, 4693, 5785, 9294, 881, 2098, 3362, 1784, 5486, 5464, 8737, 7237, 4350, 1830, 2464, 8770, 5857, 6471, 5899,
6036, 3737, 3153, 7215, 3667, 4814, 45, 695, 2756, 6557, 8212, 9410, 1434, 288, 2804, 2244, 4000, 7196, 8310, 3621, 2662, 1238,
8881, 8225, 6104, 2880, 4577, 5548, 7018, 6420, 5404, 9500, 5341, 5863, 8986, 1861, 8923, 7836, 5469, 1022, 8633, 376, 2041,
9257, 9530, 1813, 9524, 3181, 8859, 6062, 5010, 4637, 9806, 4781, 6489, 7413, 9637, 3204, 1600, 607, 7845, 6083, 8971, 4281,
4079, 9053, 3705, 4948, 8917, 4068, 443, 3297, 9789, 9566, 4586, 9567, 9240, 802, 316, 7401, 8972, 6018, 7229, 8335, 1016, 7277,
9325, 9691, 8646, 7288, 3957, 2612, 6542, 5122, 5711, 6685, 5327, 6758, 2358, 8403, 6092, 5706, 2561, 443, 9632, 8179, 8266, 5677,
2082, 6921, 4006, 847, 91, 846, 6034, 6086, 1182, 2436, 958, 7505, 8135, 6602, 2927, 519, 5370, 8131, 9706, 4084, 5654, 3189, 8033,
2132, 709, 7869, 1218, 8602, 1535, 2300, 7941, 2788, 9162, 3360, 3578, 3739, 2482, 1243, 5748, 3136, 8289, 4663, 2925, 8968, 6163
};
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("time.txt"));
System.out.println("Unsorted array:");
SortArray.peek(array);
long start = System.nanoTime();
SortArray.insertionSort(array);
long end = System.nanoTime();
System.out.println("Sorted array:");
SortArray.peek(array);
System.out.println("Algorithm: Insertion Sort");
System.out.println("Elapsed time: " + (end - start) + "us");
bufferedWriter.write("n=" + array.length + "\nAlgorithm: Insertion Sort\n" + "Elapsed time: " + (end - start) + "us");
bufferedWriter.close();
} catch (IOException e) {
System.out.println(e.toString());
}
int[] array1 = { 5, 9, 2 }, array2 = { 1, 19, 3, 6 };
int[] array3 = new int[array1.length + array2.length];
System.out.println();
System.out.println("Unsorted first array:");
SortArray.print(array1);
System.out.println("Unsorted second array:");
SortArray.print(array2);
SortArray.twoWayMergeSort(array1, array2, array3);
System.out.println("Merged and sorted third array:");
SortArray.print(array3);
}
}
| 64.720588 | 148 | 0.569643 |
fe71e1d0ee303b6b56210a896431f3ec6221134c | 206 | package org.dotwebstack.framework.core.model;
import java.util.Map;
import javax.validation.Valid;
import lombok.Data;
@Data
public class Context {
@Valid
private Map<String, ContextField> fields;
}
| 15.846154 | 45 | 0.771845 |
31263abbd07dc600042cff88f5467994e12a6b37 | 1,226 | package com.road.crawler.meizitu.crawler;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.geccocrawler.gecco.pipeline.Pipeline;
import com.road.crawler.meizitu.exec.DownloadAction;
import com.road.crawler.meizitu.exec.Executors;
import com.road.crawler.meizitu.model.Picture;
import com.road.crawler.meizitu.service.PictureService;
@Service
public class BigPicPipeline implements Pipeline<BigPic> {
@Resource(name = "pictureServiceImpl")
private PictureService pictureService;
@Value("${local.path}")
private String fileSavePath;
private Executors executors = Executors.create();
@Override
public void process(BigPic bean) {
Picture pic = new Picture();
pic.setCreateDate(new Date());
pic.setUpdateDate(new Date());
pic.setPicinfoId(bean.getPicInfoId());
for (String url : bean.getPics()) {
pic.setUrl(url);
String localPath = fileSavePath + System.currentTimeMillis() + ".jpg";
pic.setPath(localPath);
pictureService.save(pic);
executors.getDefaultActionQueue().enqueue(
new DownloadAction(executors.getDefaultActionQueue(), url, localPath));
}
}
}
| 27.863636 | 76 | 0.769984 |
f916491970b178ef0025a4b88fb0974949e25858 | 6,302 | package io.opensphere.analysis.export;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.io.File;
import javafx.application.Platform;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import io.opensphere.analysis.export.controller.ExportCompleteListener;
import io.opensphere.analysis.export.controller.ExportExecutor;
import io.opensphere.analysis.export.model.ExportOptionsModel;
import io.opensphere.analysis.export.view.DataElementsExportDialog;
import io.opensphere.analysis.export.view.MimeTypeFileFilter;
import io.opensphere.analysis.listtool.model.ListToolTableModel;
import io.opensphere.analysis.table.model.MetaColumnsTableModel;
import io.opensphere.core.control.ui.UIRegistry;
import io.opensphere.core.event.EventManager;
import io.opensphere.core.export.Exporter;
import io.opensphere.core.preferences.PreferencesRegistry;
import io.opensphere.core.util.javafx.WebPanel;
import io.opensphere.core.util.lang.StringUtilities;
import io.opensphere.core.util.swing.AutohideMessageDialog;
import io.opensphere.core.util.swing.EventQueueUtilities;
import io.opensphere.core.util.taskactivity.TaskActivity;
import io.opensphere.mantle.data.cache.DataElementCache;
import io.opensphere.mantle.data.element.DataElement;
/**
* Given an exporter and a {@link MetaColumnsTableModel}, this class will ask
* the user a file to export the data to as well as some other various export
* options. Once the user initiates export this class will go ahead and pass in
* the correct data for the {@link Exporter} to export.
*/
public class DataElementExporter implements ExportCompleteListener
{
/**
* Used to get {@link DataElement} data.
*/
private final DataElementCache myCache;
/**
* Used to display toast messages if the export failed.
*/
private final EventManager myEventManager;
/**
* Used to get export dialog preferences.
*/
private final PreferencesRegistry myPrefsRegistry;
/**
* Used to show export {@link TaskActivity}.
*/
private final UIRegistry myUIRegistry;
/**
* Constructs a new {@link DataElementExporter}.
*
* @param prefsRegistry Used to get export dialog preferences.
* @param cache Used to get {@link DataElement} data.
* @param uiRegistry Used to show export {@link TaskActivity}.
* @param eventManager Used to display toast messages if the export failed.
*/
public DataElementExporter(PreferencesRegistry prefsRegistry, DataElementCache cache, UIRegistry uiRegistry,
EventManager eventManager)
{
myPrefsRegistry = prefsRegistry;
myCache = cache;
myUIRegistry = uiRegistry;
myEventManager = eventManager;
}
@Override
public boolean askUserForOverwrite(Component parent, File file)
{
boolean canOverwrite = false;
int choice = JOptionPane.showConfirmDialog(SwingUtilities.getWindowAncestor(parent), "Overwrite the file: " + file + "?",
"Export Data", JOptionPane.YES_NO_OPTION);
canOverwrite = choice == JOptionPane.YES_OPTION;
return canOverwrite;
}
/**
* Asks the user for the export file and other various export options. If
* user clicks save, the passed exporter will be executed in a background
* thread.
*
* @param parent The parent component to show the dialog.
* @param exporter The exporter to execute.
* @param tableModel The table model to export.
* @param table The table to export.
*/
public void export(Component parent, Exporter exporter, ListToolTableModel tableModel, JTable table)
{
ExportOptionsModel optionsModel = new ExportOptionsModel();
DataElementsExportDialog dialog = new DataElementsExportDialog(myPrefsRegistry,
new MimeTypeFileFilter(exporter.getMimeType()), optionsModel);
ExportExecutor exportExecutor = new ExportExecutor(myCache, myUIRegistry, myEventManager, myPrefsRegistry);
exportExecutor.executeExport(dialog, parent, exporter, tableModel, table, optionsModel, this);
}
/**
* Called when an export has completed.
*
* @param parent The parent component, used to properly place the completion
* dialog.
* @param file The exported file.
* @param count The number of records exported.
*/
@Override
public void exportComplete(Component parent, File file, int count)
{
EventQueueUtilities.runOnEDT(() -> showCompletionDialog(parent, file, count));
}
/**
* Show a dialog letting the user know that the export is complete.
*
* @param parent The parent component, used to properly place the completion
* dialog.
* @param file The destination file.
* @param exportedCount The number of rows exported.
*/
private void showCompletionDialog(Component parent, File file, int exportedCount)
{
assert EventQueue.isDispatchThread();
WebPanel fxPanel = new WebPanel();
AutohideMessageDialog dialog = new AutohideMessageDialog(parent, ModalityType.MODELESS);
dialog.setTitle("Done");
dialog.initialize(fxPanel, null, myPrefsRegistry.getPreferences(DataElementExporter.class), "hideDoneDialog");
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.setPreferredSize(new Dimension(700, 150));
dialog.setVisible(true);
dialog.setLocationRelativeTo(parent);
Platform.runLater(() ->
{
String content = StringUtilities.concat("<html><body bgcolor='#535366' style='color: white;'>", "Successfully saved ",
Integer.toString(exportedCount), " rows to <a style='color: white;' href='", file.toURI(), "'>", file,
"</a>.<p><a style='color: white;' href='", file.getParentFile().toURI(), "'>Parent directory</a>",
"</body></html>");
fxPanel.loadContent(content);
});
}
}
| 39.886076 | 131 | 0.690733 |
c37ce7547313f779d41931f6963ffbc8a4a7601b | 1,035 | package com.xuegao.im.manager.impl;
import com.xuegao.im.domain.doo.SysUser;
import com.xuegao.im.manager.interfaces.ISysUserManager;
import com.xuegao.im.mapper.ISysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <br/> @PackageName:com.xuegao.im.manager.impl
* <br/> @ClassName:SysUserManagerImpl
* <br/> @Description:
* <br/> @author:xuegao
* <br/> @date:2021/01/31 17:03
*/
@Service
public class SysUserManagerImpl implements ISysUserManager {
private static final Logger log = LoggerFactory.getLogger(SysUserManagerImpl.class);
private final ISysUserMapper sysUserMapper;
@Autowired
public SysUserManagerImpl(ISysUserMapper sysUserMapper) {
this.sysUserMapper = sysUserMapper;
}
@Override
public Long insert(SysUser sysUser) {
log.debug("sysUser {}", sysUser);
sysUserMapper.insert(sysUser);
return sysUser.getId();
}
} | 29.571429 | 88 | 0.740097 |
21e6a111ccc72fcfc9308bbac8f13dd89c3cd22e | 12,019 | package us.ihmc.robotics.math.frames;
import javax.vecmath.Point2d;
import javax.vecmath.Tuple2d;
import javax.vecmath.Tuple3d;
import javax.vecmath.Tuple3f;
import javax.vecmath.Vector2d;
import us.ihmc.robotics.dataStructures.listener.VariableChangedListener;
import us.ihmc.robotics.dataStructures.registry.YoVariableRegistry;
import us.ihmc.robotics.dataStructures.variable.DoubleYoVariable;
import us.ihmc.robotics.geometry.*;
import us.ihmc.robotics.referenceFrames.ReferenceFrame;
//Note: You should only make these once at the initialization of a controller. You shouldn't make any on the fly since they contain YoVariables.
public abstract class YoFrameTuple2d<S, T extends FrameTuple2d<?, ?>> extends AbstractReferenceFrameHolder
{
private final DoubleYoVariable x, y; // This is where the data is stored. All operations must act on these numbers.
private final T frameTuple2d; // This is only for assistance. The data is stored in the YoVariables, not in here!
private final ReferenceFrame referenceFrame; // Redundant but allows to make sure the frame isn't changed
public YoFrameTuple2d(DoubleYoVariable xVariable, DoubleYoVariable yVariable, ReferenceFrame referenceFrame)
{
this.x = xVariable;
this.y = yVariable;
this.referenceFrame = referenceFrame;
this.frameTuple2d = createEmptyFrameTuple2d();
putYoValuesIntoFrameTuple2d();
}
public YoFrameTuple2d(String namePrefix, String nameSuffix, ReferenceFrame referenceFrame, YoVariableRegistry registry)
{
this(namePrefix, nameSuffix, "", referenceFrame, registry);
}
public YoFrameTuple2d(String namePrefix, String nameSuffix, String description, ReferenceFrame referenceFrame, YoVariableRegistry registry)
{
x = new DoubleYoVariable(YoFrameVariableNameTools.createXName(namePrefix, nameSuffix), description, registry);
y = new DoubleYoVariable(YoFrameVariableNameTools.createYName(namePrefix, nameSuffix), description, registry);
this.referenceFrame = referenceFrame;
this.frameTuple2d = createEmptyFrameTuple2d();
putYoValuesIntoFrameTuple2d();
}
public final void get(Tuple2d tuple2dToPack)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.get(tuple2dToPack);
}
/**
* Pack this tuple2d in tuple3dToPack and tuple3dToPack.z = 0.0.
* @param tuple3dToPack {@code Tuple3d}
*/
public final void get(Tuple3d tuple3dToPack)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.get(tuple3dToPack);
}
/**
* Pack this tuple2d in tuple3fToPack and tuple3fToPack.z = 0.0.
* @param tuple3fToPack {@code Tuple3f}
*/
public final void get(Tuple3f tuple3fToPack)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.get(tuple3fToPack);
}
public final Vector2d getVector2dCopy()
{
Vector2d vector2d = new Vector2d();
get(vector2d);
return vector2d;
}
public final Point2d getPoint2dCopy()
{
Point2d point2d = new Point2d();
get(point2d);
return point2d;
}
public final void getFrameTuple2d(FrameTuple2d<?, ?> frameTuple2dToPack)
{
frameTuple2dToPack.set(getFrameTuple2d());
}
public final T getFrameTuple2d()
{
putYoValuesIntoFrameTuple2d();
return frameTuple2d;
}
public final FrameVector2d getFrameVector2dCopy()
{
return new FrameVector2d(getFrameTuple2d());
}
public final FramePoint2d getFramePoint2dCopy()
{
return new FramePoint2d(getFrameTuple2d());
}
public final void getFrameTuple2dIncludingFrame(FrameTuple2d<?, ?> frameTuple2dToPack)
{
frameTuple2dToPack.setIncludingFrame(getFrameTuple2d());
}
public final void getFrameTupleIncludingFrame(FrameTuple<?, ?> frameTupleToPack)
{
frameTupleToPack.setXYIncludingFrame(getFrameTuple2d());
}
public final double getX()
{
return x.getDoubleValue();
}
public final double getY()
{
return y.getDoubleValue();
}
public final DoubleYoVariable getYoX()
{
return x;
}
public final DoubleYoVariable getYoY()
{
return y;
}
public final void setX(double newX)
{
x.set(newX);
}
public final void setY(double newY)
{
y.set(newY);
}
public final void set(double newX, double newY)
{
x.set(newX);
y.set(newY);
}
/**
* Sets x and y with no checks for reference frame matches.
*/
public final void setWithoutChecks(FrameTuple2d<?, ?> frameTuple2d)
{
x.set(frameTuple2d.getX());
y.set(frameTuple2d.getY());
}
public final void setAndMatchFrame(FrameTuple2d<?, ?> frameTuple2d)
{
setAndMatchFrame(frameTuple2d, true);
}
public final void setAndMatchFrame(FrameTuple2d<?, ?> frameTuple2d, boolean notifyListeners)
{
this.frameTuple2d.setIncludingFrame(frameTuple2d);
this.frameTuple2d.changeFrame(getReferenceFrame());
getYoValuesFromFrameTuple2d(notifyListeners);
}
public final void set(ReferenceFrame referenceFrame, double x, double y)
{
checkReferenceFrameMatch(referenceFrame);
set(x, y);
}
public final void set(FrameTuple2d<?, ?> frameTuple2d)
{
set(frameTuple2d, true);
}
public final void set(FrameTuple2d<?, ?> frameTuple2d, boolean notifyListeners)
{
this.frameTuple2d.set(frameTuple2d);
getYoValuesFromFrameTuple2d(notifyListeners);
}
public final void set(YoFrameTuple2d<?, ?> yoFrameTuple2d)
{
set(yoFrameTuple2d.getFrameTuple2d());
}
public final void set(Tuple2d tuple2d)
{
this.frameTuple2d.set(tuple2d);
getYoValuesFromFrameTuple2d();
}
public final void setByProjectionOntoXYPlane(FrameTuple<?, ?> frameTuple)
{
setByProjectionOntoXYPlane(frameTuple, true);
}
public final void setByProjectionOntoXYPlane(FrameTuple<?, ?> frameTuple, boolean notifyListeners)
{
this.frameTuple2d.setByProjectionOntoXYPlane(frameTuple);
getYoValuesFromFrameTuple2d(notifyListeners);
}
public final void setByProjectionOntoXYPlane(YoFrameTuple<?, ?> yoFrameTuple)
{
setByProjectionOntoXYPlane(yoFrameTuple, true);
}
public final void setByProjectionOntoXYPlane(YoFrameTuple<?, ?> yoFrameTuple, boolean notifyListeners)
{
yoFrameTuple.getFrameTuple2d(frameTuple2d);
getYoValuesFromFrameTuple2d(notifyListeners);
}
public final void add(double dx, double dy)
{
x.set(x.getDoubleValue() + dx);
y.set(y.getDoubleValue() + dy);
}
public final void add(Tuple2d tuple2d)
{
putYoValuesIntoFrameTuple2d();
this.frameTuple2d.add(tuple2d);
getYoValuesFromFrameTuple2d();
}
public final void add(FrameTuple2d<?, ?> frameTuple2d)
{
putYoValuesIntoFrameTuple2d();
this.frameTuple2d.add(frameTuple2d);
getYoValuesFromFrameTuple2d();
}
public final void add(YoFrameTuple2d<?, ?> yoFrameTuple2d)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.add(yoFrameTuple2d.getFrameTuple2d());
getYoValuesFromFrameTuple2d();
}
public final void sub(Tuple2d tuple2d)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.sub(tuple2d);
getYoValuesFromFrameTuple2d();
}
public final void sub(FrameTuple2d<?, ?> frameTuple2d)
{
putYoValuesIntoFrameTuple2d();
this.frameTuple2d.sub(frameTuple2d);
getYoValuesFromFrameTuple2d();
}
public final void sub(YoFrameTuple2d<?, ?> yoFrameTuple2d)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.sub(yoFrameTuple2d.getFrameTuple2d());
getYoValuesFromFrameTuple2d();
}
public final void sub(FrameTuple2d<?, ?> frameTuple1, FrameTuple2d<?, ?> frameTuple2)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.sub(frameTuple1, frameTuple2);
getYoValuesFromFrameTuple2d();
}
public final void scale(double scaleFactor)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.scale(scaleFactor);
getYoValuesFromFrameTuple2d();
}
/**
* Sets the value of this tuple to the scalar multiplication of itself and then adds frameTuple1 (this = scaleFactor * this + frameTuple1).
* Checks if reference frames match.
*
* @param scaleFactor double
* @param frameTuple1 FrameTuple2d<?, ?>
* @throws ReferenceFrameMismatchException
*/
public final void scaleAdd(double scaleFactor, FrameTuple2d<?, ?> frameTuple2d)
{
putYoValuesIntoFrameTuple2d();
this.frameTuple2d.scaleAdd(scaleFactor, frameTuple2d);
getYoValuesFromFrameTuple2d();
}
public final void scaleAdd(double scaleFactor, YoFrameTuple2d<?, ?> yoFrameTuple2d)
{
scaleAdd(scaleFactor, yoFrameTuple2d.getFrameTuple2d());
}
public final void scaleAdd(double scaleFactor, YoFrameTuple2d<?, ?> yoFrameTuple1, YoFrameTuple2d<?, ?> yoFrameTuple2)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.scaleAdd(scaleFactor, yoFrameTuple1.getFrameTuple2d(), yoFrameTuple2.getFrameTuple2d());
getYoValuesFromFrameTuple2d();
}
public final void interpolate(Tuple2d tuple1, Tuple2d tuple2, double alpha)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.interpolate(tuple1, tuple2, alpha);
getYoValuesFromFrameTuple2d();
}
/**
* Linearly interpolates between tuples frameTuple1 and frameTuple2 and places the result into this tuple: this = (1-alpha) * frameTuple1 + alpha * frameTuple2.
* @param frameTuple1 the first tuple
* @param frameTuple2 the second tuple
* @param alpha the alpha interpolation parameter
* @throws ReferenceFrameMismatchException
*/
public final void interpolate(FrameTuple2d<?, ?> frameTuple1, FrameTuple2d<?, ?> frameTuple2, double alpha)
{
checkReferenceFrameMatch(frameTuple1);
checkReferenceFrameMatch(frameTuple2);
putYoValuesIntoFrameTuple2d();
frameTuple2d.interpolate(frameTuple1, frameTuple2, alpha);
getYoValuesFromFrameTuple2d();
}
public final boolean epsilonEquals(FrameTuple2d<?, ?> frameTuple2d, double threshold)
{
putYoValuesIntoFrameTuple2d();
return this.frameTuple2d.epsilonEquals(frameTuple2d, threshold);
}
public final void checkForNaN()
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.checkForNaN();
}
public final boolean containsNaN()
{
putYoValuesIntoFrameTuple2d();
return frameTuple2d.containsNaN();
}
public final void setToZero()
{
frameTuple2d.setToZero(referenceFrame);
getYoValuesFromFrameTuple2d();
}
public final void setToNaN()
{
frameTuple2d.setToNaN(referenceFrame);
getYoValuesFromFrameTuple2d();
}
public final void applyTransform(RigidBodyTransform transform)
{
putYoValuesIntoFrameTuple2d();
frameTuple2d.applyTransform(transform);
getYoValuesFromFrameTuple2d();
}
@Override
public ReferenceFrame getReferenceFrame()
{
return referenceFrame;
}
public final void attachVariableChangedListener(VariableChangedListener variableChangedListener)
{
x.addVariableChangedListener(variableChangedListener);
y.addVariableChangedListener(variableChangedListener);
}
protected abstract T createEmptyFrameTuple2d();
private final void putYoValuesIntoFrameTuple2d()
{
frameTuple2d.setIncludingFrame(referenceFrame, x.getDoubleValue(), y.getDoubleValue());
}
protected void getYoValuesFromFrameTuple2d()
{
getYoValuesFromFrameTuple2d(true);
}
private void getYoValuesFromFrameTuple2d(boolean notifyListeners)
{
x.set(frameTuple2d.getX(), notifyListeners);
y.set(frameTuple2d.getY(), notifyListeners);
}
/**
* toString
*
* String representation of a FrameVector (x,y)-reference frame name
*
* @return String
*/
@Override
public String toString()
{
putYoValuesIntoFrameTuple2d();
return frameTuple2d.toString();
}
}
| 28.822542 | 165 | 0.707879 |
5b0ef53f36367d8a69f05711f62b0f6cbdf4cba1 | 3,609 | package servlet;
import com.google.gson.Gson;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "EchoServlet", urlPatterns = {"/echo"})
public class EchoServlet extends HttpServlet{
@Override
protected void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
doGet(req, res);
/*
res.setContentType ("aplication/json");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST");
res.setHeader("Access-Control-Allow-Headers", "*");
PrintWriter out = res.getWriter();
Map<String, String[]> parameterMap = req.getParameterMap();
Map<String, String> data = new HashMap<String, String>();
for (String key: parameterMap.keySet()) {
String parameter = parameterMap.get(key)[0];
data.put(key, parameter);
}
out.print(new Gson().toJson(data));
out.flush();
out.close();
*/
}
@Override
protected void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
// req = request, and res = response
res.setContentType("text/html; charset=UTF-8");
PrintWriter out = res.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>SWE 432 Echo Servlet, Assignment 4</title></head>");
out.println("<h1>SWE 432 Echo Servlet, Assignment 4</h1>");
// Get all requests (name from html post) and display it as html
String sortedOrderString = req.getParameter("Sorted Order String");
// If the string is blank, print error msg
// Compare with the sortedOrderString since this list gets rid of whitespace, 'String input' does not
if (sortedOrderString.equals("")) {
out.println("<h2>String Input:</h2><p> No input was provided</p>");
}
// Else, print the string
else {
// Display the string input
String input = req.getParameter("String Input");
out.println("<h2>String Input:</h2><p> " + input + "</p>");
}
// Display the first random string
String randomString = req.getParameter("Random String");
out.println("<h2>Random String:</h2><p> " + randomString + "</p>");
// Display the second random string
String randomStringTwo = req.getParameter("Random String #2 Without Replacement");
out.println("<h2>Random String #2 Without Replacement:</h2><p> " + randomStringTwo + "</p>");
// Display the sorted order string
out.println("<h2>Sorted Order String:</h2><p> " + sortedOrderString + "</p>");
// Display the reversed order string
String reverseOrderString = req.getParameter("Reverse Order String");
out.println("<h2>Reverse Order String:</h2><p> " + reverseOrderString + "</p>");
/*
res.setContentType ("text/html");
PrintWriter out = res.getWriter ();
out.println ("<HTML>");
out.println ("<HEAD>");
out.println ("<TITLE>Invalid request</TITLE>");
out.println ("</HEAD>");
out.println ("<BODY>");
out.println ("<CENTER>");
out.println (
"<P>Invalid GET request: TEST This service only accepts POST requests</P>"
);
out.println ("</CENTER>");
out.println ("</BODY>");
out.println ("</HTML>");
out.flush();
out.close ();
*/
}
}
| 29.826446 | 114 | 0.683015 |
ccee7ed6da6038c41b8f56433353acd2c5b6b903 | 5,100 | /*
* MIT License
*
* Copyright (c) 2018 Udo Borkowski, ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.abego.rebsta.core.internal;
import org.abego.commons.javalang.ClassName;
import org.abego.commons.lang.ClassUtil;
import org.abego.rebsta.core.RebstaParameters.ClassVisibility;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.stream.Stream;
import static org.abego.commons.javalang.JavaLangUtil.toJavaIdentifier;
import static org.abego.commons.text.MessageFormatUtil.maxArgumentIndexInMessageFormatPattern;
class StaticTextAccessClassTemplate {
private static final String CLASS_PATTERN_RESOURCE_NAME = "classPattern.txt"; // NON-NLS
private static final String METHOD_BODY_PATTERN_RESOURCE_NAME = "methodBodyPattern.txt"; // NON-NLS
private static final String ACCESS_METHOD_PATTERN_RESOURCE_NAME = "accessMethodPattern.txt"; // NON-NLS
private static final String PARAMETER_NAME_PREFIX = "p"; // NON-NLS
private static final String PARAMETER_TYPENAME = "Object"; // NON-NLS
private final String resourceBundleName;
private final Properties resourceBundleContent;
StaticTextAccessClassTemplate(String resourceBundleName,
Properties resourceBundleContent) {
this.resourceBundleName = resourceBundleName;
this.resourceBundleContent = resourceBundleContent;
}
private static String textOfResource(String name) {
return ClassUtil.textOfResource(StaticTextAccessClassTemplate.class, name);
}
String javaClassText(ClassName className,
ClassVisibility testClassVisibility) {
String modifier = testClassVisibility.javaModifier();
if (!modifier.isEmpty()) {
//noinspection StringConcatenation
modifier = modifier + " ";
}
String messageBodyText = textOfResource(METHOD_BODY_PATTERN_RESOURCE_NAME);
String classTextMessagePattern =
textOfResource(CLASS_PATTERN_RESOURCE_NAME);
return MessageFormat.format(classTextMessagePattern,
className.packagePath(),
className.simpleName(),
modifier,
resourceBundleName,
classBody(modifier),
messageBodyText);
}
private String classBody(String access) {
StringBuilder result = new StringBuilder();
Stream<Object> sortedKeys =
resourceBundleContent.keySet().stream().sorted();
sortedKeys.forEachOrdered(key -> {
String keyString = key.toString();
appendAccessMethod(
result,
keyString,
resourceBundleContent.getProperty(keyString),
access);
});
return result.toString();
}
private void appendAccessMethod(StringBuilder text, String key,
String value, String access) {
int maxArgumentIndex = maxArgumentIndexInMessageFormatPattern(value);
StringBuilder parameterSignature = new StringBuilder();
StringBuilder arguments = new StringBuilder();
for (int i = 0; i <= maxArgumentIndex; i++) {
String paramName = MessageFormat.format(
"{0}{1}", PARAMETER_NAME_PREFIX, i);
if (parameterSignature.length() > 0) {
parameterSignature.append(", ");
}
parameterSignature.append(MessageFormat.format("{0} {1}",
PARAMETER_TYPENAME, paramName));
arguments.append(", ");
arguments.append(paramName);
}
String accessMethodPattern =
textOfResource(ACCESS_METHOD_PATTERN_RESOURCE_NAME);
String methodText = MessageFormat.format(accessMethodPattern,
access,
toJavaIdentifier(key),
parameterSignature.toString(),
key,
arguments);
text.append(methodText);
}
}
| 39.230769 | 107 | 0.671961 |
65c31bc2034a27e029ff9bddcc97c93306656216 | 273 | package org.activiti.engine.identity;
import org.activiti.engine.query.NativeQuery;
/**
* Allows querying of {@link org.activiti.engine.identity.Group}s via native (SQL) queries
*
*/
public interface NativeGroupQuery extends NativeQuery<NativeGroupQuery, Group> {
} | 22.75 | 90 | 0.772894 |
f5baa26e40b47fe77cc97834e1caaedf4fe2a949 | 471 | package com.leyou.order.pojo;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import tk.mybatis.mapper.annotation.KeySql;
@Data
@Table(name = "tb_order_detail")
public class OrderDetail {
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
private Long orderId;
private Long skuId;
private Integer num;
private String title;
private Long price;
private String ownSpec;
private String image;
}
| 20.478261 | 43 | 0.726115 |
8e277da8aebffb7f95fe171fa0e6d74f0dfdd737 | 3,093 | package com.hyperledger.export.propwindow;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.archimatetool.model.IArchimateModel;
import com.archimatetool.model.IProperty;
/**
* View окна экспорта
*/
public class ExportAsBNAPage extends WizardPage {
public enum Field {
BUSINESS_NETWORK_NAME("Business network name"),
DESCRIPTION("Description"),
AUTHOR_NAME("Author name"),
AUTHOR_EMAIL("Author email"),
LICENSE("License"),
NAMESPACE("Namespace");
private String caption;
private Text input;
Field(String caption) {
this.caption = caption;
}
@Override
public String toString() {
return caption;
}
public void setInput(Text input) {
this.input = input;
}
public void setText(String text) {
this.input.setText(text);
}
public String getValue() {
if (input != null)
return input.getText();
return "null";
}
};
//Archimate модель
private IArchimateModel model;
public ExportAsBNAPage(IArchimateModel model) {
this("ExportAsBNAWizard", model);
}
protected ExportAsBNAPage(String pageName, IArchimateModel model) {
super(pageName);
this.model = model;
}
/**
* Создание view окна
*/
@Override
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
container.setLayout(new GridLayout());
setControl(container);
GridData gd = new GridData();
gd.widthHint = 500;
for (Field field : Field.values()) {
addField(container, gd, field);
}
Field.BUSINESS_NETWORK_NAME.setText(model.getName());
Field.DESCRIPTION.setText(model.getPurpose());
for (IProperty prop : model.getProperties()) {
String key = prop.getKey().toLowerCase().trim();
String value = prop.getValue().replaceAll(" ", "");
if (key.equals("namespace")) {
Field.NAMESPACE.setText(value);
} else if (key.equals("author") || key.equals("author name") || key.equals("author_name")) {
Field.AUTHOR_NAME.setText(value);
} else if (key.equals("email") || key.equals("author email") || key.equals("author_email")) {
Field.AUTHOR_EMAIL.setText(value);
} else if (key.equals("license")) {
Field.LICENSE.setText(value);
}
}
setTitle("Export BNA");
}
/**
* Добавить поле для ввода
* @param container родительский контейнер
* @param gd данные для layout
* @param field поле
*/
private void addField(Composite container, GridData gd, Field field) {
Label label = new Label(container, SWT.READ_ONLY);
label.setText(field.toString());
Text input = new Text(container, SWT.BORDER | SWT.SINGLE);
input.setLayoutData(gd);
field.setInput(input);
}
}
| 25.775 | 102 | 0.648561 |
3dcafae2bc79bd504b72679723a6405a7c56ca41 | 667 | package org.charlie.chess.pieces;
import org.charlie.chess.Board;
import org.charlie.chess.Square;
import org.charlie.chess.moves.PossibleMoves;
import org.charlie.chess.moves.StraightLineMove;
import org.charlie.chess.players.Player;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
public class RookTest {
@Test
public void testPieceDoesntJump() throws Exception {
Rook rook = new Rook(mock(Player.class), new Square(0, 0), new StraightLineMove());
PossibleMoves possibleMoves = rook.getPossibleMoves(mock(Board.class));
assertEquals(possibleMoves.size(), 2);
}
} | 27.791667 | 91 | 0.752624 |
8b57d50bc33b0497d006d2cf7bc252a5c5112fed | 814 | package com.atguigu.gmall.sms.api;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.sms.vo.ItemSaleVo;
import com.atguigu.gmall.sms.vo.SkuSaleVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
public interface GmallSmsApi {
/**
* 添加营销信息
*/
@PostMapping("/sms/skubounds/skusale/save")
public ResponseVo<SkuSaleVo> skuSaleInfo(@RequestBody SkuSaleVo skuSaleVo);
/**
* 根据skuId查询营销信息
*/
@GetMapping("sms/skubounds/salesItem/{skuId}")
public ResponseVo<List<ItemSaleVo>> queryItemSalesBySkuId(@PathVariable("skuId")Long skuId);
}
| 31.307692 | 96 | 0.765356 |
28070a97e0dae9c7bfb1200350167352f8c24c2c | 1,556 | /*
* Copyright (c) 2012 M. M. Naseri <[email protected]>
*
* 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.
*/
package com.agileapes.powerpack.string.reader.impl;
import com.agileapes.powerpack.string.reader.TokenDescriptor;
import java.util.regex.Pattern;
/**
* @author Mohammad Milad Naseri ([email protected])
* @since 1.0 (2012/12/3, 18:44)
*/
public class NonWhitespaceTokenDesignator extends PatternTokenDesignator {
public NonWhitespaceTokenDesignator() {
super(Pattern.compile("\\S+"));
}
@Override
public TokenDescriptor getToken(String string) {
int whitespaces = 0;
while (string.length() > 0 && Character.isWhitespace(string.charAt(0))) {
string = string.substring(1);
whitespaces ++;
}
final TokenDescriptor token = super.getToken(string);
if (token != null) {
return new SimpleTokenDescriptor(token.getLength(), token.getOffset() + whitespaces);
}
return null;
}
}
| 33.826087 | 97 | 0.694087 |
ee60652b6ff8095a128716d33acc0db731e98140 | 7,146 | package kh.edu.npic.unitgrader.grade;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import kh.edu.npic.unitgrader.grade.filters.GradedStudentsFilter;
import kh.edu.npic.unitgrader.grade.filters.RecentlyGradedFilter;
import kh.edu.npic.unitgrader.grade.filters.StudentConditionFilter;
import kh.edu.npic.unitgrader.grade.manager.LMSAssignmentManager;
import kh.edu.npic.unitgrader.util.console.NumericalSelectionMenu;
import kh.edu.npic.unitgrader.util.console.Option;
import kh.edu.npic.unitgrader.util.preferences.DirectoryManager;
public class TailoredExportOption extends Option
{
private LMSAssignmentManager<?> manager;
public TailoredExportOption(LMSAssignmentManager<?> manager)
{
super("Write the results to a *.csv file designed for import to " + manager.getName() + ".");
this.manager = manager;
}
@Override
public boolean function()
{
/*
* Stage one: user must select a template CSV for the destination LMS. Ideally, a copy of the gradebook
* with an already-existing header entry for the autograder's results.
*/
int res;
JFileChooser chooseOriginalCSV = new JFileChooser();
chooseOriginalCSV.setDialogTitle("Select the base CSV (gradebook) file.");
chooseOriginalCSV.setCurrentDirectory(DirectoryManager.baseSubmissionSelectedDirectory);
chooseOriginalCSV.setFileFilter(new FileNameExtensionFilter("Comma-separated values file (*.csv)", "csv"));
res = chooseOriginalCSV.showOpenDialog(null);
switch(res)
{
case JFileChooser.CANCEL_OPTION:
return true;
case JFileChooser.APPROVE_OPTION:
break;
case JFileChooser.ERROR_OPTION:
System.err.println("Error detected in results from file selection.");
return true;
default:
System.err.println("Impossible result from file chooser dialog.");
return true;
}
File sourceCSVFile = chooseOriginalCSV.getSelectedFile();
/*
* Validate the selection - is the selected CSV appropriate?
*/
FileReader in = null;
CSVParser parser = null;
Map<String, Integer> reducedHeaderMap;
Map<String, Integer> originalHeaderMap;
try
{
in = new FileReader(sourceCSVFile);
parser = new CSVParser(in, CSVFormat.EXCEL.withHeader());
reducedHeaderMap = manager.getCSV_DefaultHeader();
originalHeaderMap = parser.getHeaderMap();
parser.close();
// Condition - if the CSV has a header that matches the standard style for its LMS.
if(!(originalHeaderMap.entrySet().containsAll(reducedHeaderMap.entrySet())))
{
System.out.println("CSV doesn't fit the recognized " + manager.getName() + " CSV format!");
return true;
}
}
catch(IOException e)
{
if(in != null)
{
try
{
in.close();
}
catch (IOException e1) { }
}
System.err.println("Error occurred when verifying the base template CSV.");
return true;
}
JFileChooser chooseExportCSV = new JFileChooser();
chooseExportCSV.setDialogTitle("Export to CSV file...");
chooseExportCSV.setCurrentDirectory(DirectoryManager.baseSubmissionSelectedDirectory);
chooseExportCSV.setFileFilter(new FileNameExtensionFilter("Comma-separated values file (*.csv)", "csv"));
res = chooseExportCSV.showSaveDialog(null);
switch(res)
{
case JFileChooser.CANCEL_OPTION:
return true;
case JFileChooser.APPROVE_OPTION:
break;
case JFileChooser.ERROR_OPTION:
System.err.println("Error detected in results from file selection.");
return true;
default:
System.err.println("Impossible result from file chooser dialog.");
return true;
}
File destinationFile = chooseExportCSV.getSelectedFile();
boolean fullExport = true; // False - use RecentlyGradedFilter. True - use GradedStudentsFilter.
// TODO: Triple option - export literally all, all graded, or newly graded.
if(manager.getLastExportTimestamp() > 0) // No reason to ask if we've never done ANY exports.
{
res = JOptionPane.showConfirmDialog(null, "Export data only for changes since prior export?", "Export Option", JOptionPane.YES_NO_OPTION);
if(res == JOptionPane.YES_OPTION)
fullExport = false;
}
StudentConditionFilter filter;
if(fullExport)
filter = new GradedStudentsFilter();
else filter = new RecentlyGradedFilter(manager.getLastExportTimestamp());
/////////////////
// What are the fields corresponding to gradebook entries?
List<String> fields = new ArrayList<String>(originalHeaderMap.keySet());
fields.removeAll(reducedHeaderMap.keySet());
// Trim any blanks.
for(int i=0; i < fields.size(); i++)
{
if(fields.get(i).trim().equals(""))
fields.remove(i--);
}
// Select the appropriate field, or define a new field. (options)
// Toward defining a menu for user selection of the field.
abstract class Resolver<T>
{
public abstract T evaluate();
public abstract String toString();
}
class StringRunner extends Resolver<String>
{
String title;
String value;
public StringRunner(String value)
{
this(value, value);
}
public StringRunner(String value, String title)
{
this.value = value;
this.title = title;
}
public String evaluate()
{
return value;
}
@Override
public String toString()
{
return title;
}
}
class NewFieldResolver extends Resolver<String>
{
@Override
public String evaluate()
{
try
{
while(System.in.available() > 0)
{
System.in.read();
}
}
catch (IOException e) { }
System.out.println("Enter a name for this assignment's field in the gradebook: ");
Scanner input = new Scanner(System.in);
return input.nextLine();
}
@Override
public String toString()
{
return "Enter a new field.";
}
}
NumericalSelectionMenu<Resolver<String>> menu = new NumericalSelectionMenu<Resolver<String>>();
for(String f:fields)
{
menu.add(new StringRunner(f));
}
menu.add(new NewFieldResolver());
menu.add(new StringRunner(null, "Cancel."));
String fieldName = menu.run().evaluate();
try
{
TailoredCSVExporter.exportToCSV(manager, sourceCSVFile, destinationFile, fieldName, filter);
System.out.println("Enter a name for the final exported archive file: ");
Scanner input = new Scanner(System.in);
String archiveFile = input.nextLine();
manager.exportUploadArchive(archiveFile, filter);
}
catch (FileNotFoundException e)
{
System.out.println("Could not write to that destination.");
}
return true;
}
}
| 27.590734 | 144 | 0.683599 |
f7d1f3d5233815590b72b98b1b2339a621d93e30 | 6,456 | /*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.elasticsearch.test.integration.gateway.local;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.gateway.Gateway;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.internal.InternalNode;
import org.elasticsearch.test.integration.AbstractNodesTests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import static org.elasticsearch.client.Requests.*;
import static org.elasticsearch.common.settings.ImmutableSettings.*;
import static org.elasticsearch.common.xcontent.XContentFactory.*;
import static org.elasticsearch.index.query.xcontent.QueryBuilders.*;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
/**
* @author kimchy (shay.banon)
*/
public class QuorumLocalGatewayTests extends AbstractNodesTests {
@AfterMethod public void cleanAndCloseNodes() throws Exception {
for (int i = 0; i < 10; i++) {
if (node("node" + i) != null) {
node("node" + i).stop();
// since we store (by default) the index snapshot under the gateway, resetting it will reset the index data as well
((InternalNode) node("node" + i)).injector().getInstance(Gateway.class).reset();
}
}
closeAllNodes();
}
@Test public void testQuorumRecovery() throws Exception {
// clean three nodes
logger.info("--> cleaning nodes");
buildNode("node1", settingsBuilder().put("gateway.type", "local").build());
buildNode("node2", settingsBuilder().put("gateway.type", "local").build());
buildNode("node3", settingsBuilder().put("gateway.type", "local").build());
cleanAndCloseNodes();
logger.info("--> starting 3 nodes");
Node node1 = startNode("node1", settingsBuilder().put("gateway.type", "local").put("index.number_of_shards", 2).put("index.number_of_replicas", 2).build());
Node node2 = startNode("node2", settingsBuilder().put("gateway.type", "local").put("index.number_of_shards", 2).put("index.number_of_replicas", 2).build());
Node node3 = startNode("node3", settingsBuilder().put("gateway.type", "local").put("index.number_of_shards", 2).put("index.number_of_replicas", 2).build());
logger.info("--> indexing...");
node1.client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().field("field", "value1").endObject()).execute().actionGet();
node1.client().admin().indices().prepareFlush().execute().actionGet();
node1.client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject().field("field", "value2").endObject()).execute().actionGet();
node1.client().admin().indices().prepareRefresh().execute().actionGet();
logger.info("--> running cluster_health (wait for the shards to startup)");
ClusterHealthResponse clusterHealth = client("node1").admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForActiveShards(6)).actionGet();
logger.info("--> done cluster_health, status " + clusterHealth.status());
assertThat(clusterHealth.timedOut(), equalTo(false));
assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN));
for (int i = 0; i < 10; i++) {
assertThat(node1.client().prepareCount().setQuery(matchAllQuery()).execute().actionGet().count(), equalTo(2l));
}
logger.info("--> closing first node, and indexing more data to the second node");
closeNode("node1");
logger.info("--> running cluster_health (wait for the shards to startup)");
clusterHealth = client("node2").admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForActiveShards(4)).actionGet();
logger.info("--> done cluster_health, status " + clusterHealth.status());
assertThat(clusterHealth.timedOut(), equalTo(false));
assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.YELLOW));
node2.client().prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject().field("field", "value3").endObject()).execute().actionGet();
node2.client().admin().indices().prepareRefresh().execute().actionGet();
for (int i = 0; i < 10; i++) {
assertThat(node2.client().prepareCount().setQuery(matchAllQuery()).execute().actionGet().count(), equalTo(3l));
}
logger.info("--> closing the second node and third node");
closeNode("node2");
closeNode("node3");
logger.info("--> starting the nodes back, verifying we got the latest version");
node1 = startNode("node1", settingsBuilder().put("gateway.type", "local").build());
node2 = startNode("node2", settingsBuilder().put("gateway.type", "local").build());
node2 = startNode("node3", settingsBuilder().put("gateway.type", "local").build());
logger.info("--> running cluster_health (wait for the shards to startup)");
clusterHealth = client("node1").admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForActiveShards(6)).actionGet();
logger.info("--> done cluster_health, status " + clusterHealth.status());
assertThat(clusterHealth.timedOut(), equalTo(false));
assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN));
for (int i = 0; i < 10; i++) {
assertThat(node1.client().prepareCount().setQuery(matchAllQuery()).execute().actionGet().count(), equalTo(3l));
}
}
}
| 53.8 | 167 | 0.68355 |
0ffb569263d5c95e99c94b91585a6006ba5183f5 | 1,207 | package cc.sylar.elasticsearch.proxy.beans.search.request.geo;
import java.io.Serializable;
/**
* @author sylar
* @Description:
* @date 2018/10/30 3:17 PM
*/
public class GeoPoint implements Serializable {
/**
* 经度
*/
private Double lon;
/**
* 纬度
*/
private Double lat;
private GeoPoint(Builder builder) {
this.lon = builder.lon;
this.lat = builder.lat;
}
public static Builder newBuilder() {
return new Builder();
}
public Double getLon() {
return lon;
}
public Double getLat() {
return lat;
}
public static final class Builder {
private Double lon;
private Double lat;
private Builder() {
}
public Builder lon(Double val) {
lon = val;
return this;
}
public Builder lat(Double val) {
lat = val;
return this;
}
public GeoPoint build() {
return new GeoPoint(this);
}
}
@Override
public String toString() {
return "GeoPoint{" +
"lon=" + lon +
", lat=" + lat +
'}';
}
}
| 18.014925 | 62 | 0.502071 |
368a91a44c3ec723837982fc99f296cff337b16d | 5,898 | /*
* The MIT License
*
* Copyright 2021 Vladi.
*
* 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 ru.VladTheMountain.oclide.ui.dialogs;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.LayoutStyle;
/**
*
* @author Vladi
*/
public class MachineChooserDialog extends javax.swing.JDialog {
final ResourceBundle localiztionResource = ResourceBundle.getBundle("ru.VladTheMountain.oclide.resources.dialog.Dialog", Locale.getDefault());
private static final long serialVersionUID = 1L;
private String[] fileSystemList;
private String selectedFS;
/**
* Creates new form MachineChooser
*
* @param parent
* @param modal
* @param fs Array of filesystem UUIDs
*/
public MachineChooserDialog(java.awt.Frame parent, boolean modal, String[] fs) {
super(parent, modal);
this.fileSystemList = new String[fs.length];
System.arraycopy(fs, 0, this.fileSystemList, 0, fs.length);
selectedFS = null;
initComponents();
this.setDefaultCloseOperation(javax.swing.JDialog.DISPOSE_ON_CLOSE);
this.setVisible(true);
}
/**
*
* @return target filesystem UUID
*/
public String getSelectedFS() {
return this.selectedFS;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new JLabel();
jComboBox1 = new JComboBox<String>(this.fileSystemList)
;
proceedButton = new JButton();
setTitle("Installing OpenOS...");
jLabel1.setFont(new Font("Segoe UI", 0, 12)); // NOI18N
jLabel1.setText("Choose a file system to install OpenOS to:");
jComboBox1.setToolTipText("");
jComboBox1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
proceedButton.setText("Proceed");
proceedButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
proceedButtonActionPerformed(evt);
}
});
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 160, Short.MAX_VALUE))
.addComponent(jComboBox1, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(proceedButton)))
.addContainerGap())
);
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(proceedButton)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jComboBox1ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
}//GEN-LAST:event_jComboBox1ActionPerformed
private void proceedButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_proceedButtonActionPerformed
this.selectedFS = String.valueOf(jComboBox1.getSelectedItem());
}//GEN-LAST:event_proceedButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private JComboBox<String> jComboBox1;
private JLabel jLabel1;
private JButton proceedButton;
// End of variables declaration//GEN-END:variables
}
| 39.059603 | 146 | 0.683452 |
8b01375e7970212cb7ecf243a18c8bfe39a4a3d9 | 9,335 | /*
* 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 br.org.gdt.beans;
import br.org.gdt.model.GchAlternativas;
import br.org.gdt.model.GchAlternativasperguntas;
import br.org.gdt.model.GchPerguntas;
import br.org.gdt.resources.Helper;
import br.org.gdt.service.GchCadastroAlternativaServiceCerto;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.behavior.AjaxBehavior;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import org.primefaces.event.SelectEvent;
/**
*
* @author Alisson Allebrandt
*/
@ManagedBean
@RequestScoped
public class GchAlternativaBean {
private boolean formAtivo = false;
private Map<GchAlternativas, Boolean> checked = new HashMap<GchAlternativas, Boolean>();
private List<GchAlternativas> alternativasVinculadas = new ArrayList<>();
private String codigo;
private List<GchAlternativasperguntas> altPerLista = new ArrayList<>();
public List<GchAlternativasperguntas> getAltPerLista() {
return altPerLista;
}
public void setAltPerLista(List<GchAlternativasperguntas> altPerLista) {
this.altPerLista = altPerLista;
}
private GchAlternativas gchAlternativas = new GchAlternativas();
private List<GchAlternativas> gchTodasAlternativas;
@ManagedProperty("#{gchAlternativaCertoService}")
private GchCadastroAlternativaServiceCerto gchAlternativasService;
public GchAlternativaBean() {
}
public List<String> completeText(String query) {
List<String> results = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
results.add(query + i);
}
return results;
}
public void onItemSelect(SelectEvent event) {
// FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Item Selecionado", event.getObject().toString()));
}
public String VincularAlternativa(FacesContext event) {
Map<String, String> parameterMap = (Map<String, String>) event.getExternalContext().getRequestParameterMap();
String param = parameterMap.get("valorPerguntas");
return "1";
}
public String VinculaPerguntaAlternativa() {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String param = params.get("valorPerguntas");
FacesContext context = FacesContext.getCurrentInstance();
String a = (String) UIComponent.getCurrentComponent(context).getAttributes().get("teste");
// String action = params.get("formFormulario:j_idt70:"+index+":alternativas_hinput");
GchAlternativasperguntas altPergunta = new GchAlternativasperguntas();
// altPergunta.setAltCodigo(alt.getAltCodigo());
GchPerguntas pergunta = new GchPerguntas();
// pergunta.setPerCodigo(perg.getPerCodigo());
// pergunta.setPerDescricao(perg.getPerDescricao());
// altPergunta.setPerCodigo(pergunta);
altPerLista.add(altPergunta);
return null;
}
public List<GchAlternativas> CompleteAlternativas(String query) {
String filterValue = (String) UIComponent.getCurrentComponent(FacesContext.getCurrentInstance()).getAttributes().get("teste");
List<GchAlternativas> TodasAlternativas = gchAlternativasService.findAll();
List<GchAlternativas> AlternativasFiltradas = new ArrayList<GchAlternativas>();
for (int i = 0; i < TodasAlternativas.size(); i++) {
GchAlternativas alternativa = TodasAlternativas.get(i);
if (alternativa.getAltDescricao().toLowerCase().startsWith(query)) {
AlternativasFiltradas.add(alternativa);
}
}
return AlternativasFiltradas;
}
public String cancel() {
this.formAtivo = false;
this.gchAlternativas = new GchAlternativas();
return "Alternativas";
}
public void add() {
this.formAtivo = true;
this.gchAlternativas = new GchAlternativas();
}
public boolean isFormAtivo() {
return formAtivo;
}
public void setFormAtivo(boolean formAtivo) {
this.formAtivo = formAtivo;
}
public void setGchAlternativas(GchAlternativas gchAlternativas) {
this.gchAlternativas = gchAlternativas;
}
public String save() {
String MsgNotificacao = "";
try {
if (gchAlternativas.getAltCodigo() > 0) {
gchAlternativasService.update(gchAlternativas);
MsgNotificacao = "A alternativa <b>" + gchAlternativas.getAltDescricao() + " </b>foi atualizada com sucesso!";
} else {
gchAlternativasService.save(gchAlternativas);
MsgNotificacao = "A alternativa <b>" + gchAlternativas.getAltDescricao() + " </b>foi cadastrada com sucesso!";
}
Helper.mostrarNotificacao("Sucesso", MsgNotificacao, "success");
} catch (Exception ex) {
MsgNotificacao = "Houve uma falha ao cadastrar a alternativa <b>" + gchAlternativas.getAltDescricao() + ex.getMessage() + " , </b>tente novamente mais tarde!";
Helper.mostrarNotificacao("Erro", MsgNotificacao, "error");
}
gchTodasAlternativas = null; //Limpa a variavel e garante que a lista de alternativas seja atualizada corretamente
return "Alternativas";
}
public String buscaPorId(int idAlternativa) {
if (idAlternativa != 0) {
gchAlternativas = gchAlternativasService.findById(idAlternativa);
return "CadastroAlternativas";
}
return null;
}
public String excluir(GchAlternativas gchAlternativas) {
String MsgNotificacao = "";
try {
if (gchAlternativas != null) {
gchAlternativasService.delete(gchAlternativas.getAltCodigo());
gchTodasAlternativas.remove(gchAlternativas);
MsgNotificacao = "A alternativa <b>" + gchAlternativas.getAltDescricao() + " </b>foi excluída com sucesso!";
Helper.mostrarNotificacao("Sucesso", MsgNotificacao, "success");
}
} catch (Exception ex) {
//Excessão de Fk Perguntas
if (ex.toString().indexOf("fk_rlxnrgqkge2ynq1dulrv80omv") > 0) {
MsgNotificacao = "Esta alternativa já está vinculada a <b>perguntas</b> de um formulário e não pode ser excluída!";
} else {
//Excessao de fk REspostas
if (ex.toString().indexOf("fk_6flos8clp2yfpo91p7pdarwgn") > 0) {
MsgNotificacao = "Esta alternativa já está vinculada a <b>respostas</b> de um formulário e não pode ser excluída!";
} else {
MsgNotificacao = "Uma Exceção não tratada impediu a exclusão da alternativa!" + ex.toString();
}
}
Helper.mostrarNotificacao("Erro", MsgNotificacao, "error");
}
return "Alternativas";
}
public GchAlternativas getGchAlternativa() {
return gchAlternativas;
}
public void setGchAlternativa(GchAlternativas gchAlternativas) {
this.gchAlternativas = gchAlternativas;
}
public List<GchAlternativas> getGchTodasAlternativas() {
if (gchTodasAlternativas == null) {
gchTodasAlternativas = gchAlternativasService.findAll();
}
return gchTodasAlternativas;
}
public void setGchTodasAlternativas(List<GchAlternativas> gchTodasAlternativas) {
this.gchTodasAlternativas = gchTodasAlternativas;
}
public GchCadastroAlternativaServiceCerto getGchAlternativasService() {
return gchAlternativasService;
}
public void setGchAlternativasService(GchCadastroAlternativaServiceCerto gchAlternativasService) {
this.gchAlternativasService = gchAlternativasService;
}
public Map<GchAlternativas, Boolean> getChecked() {
return checked;
}
public void setChecked(Map<GchAlternativas, Boolean> checked) {
this.checked = checked;
}
public List<GchAlternativas> getAlternativasVinculadas() {
return alternativasVinculadas;
}
public void setAlternativasVinculadas(List<GchAlternativas> alternativasVinculadas) {
this.alternativasVinculadas = alternativasVinculadas;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
}
| 31.537162 | 172 | 0.652598 |
ca1a5f595857aa28821b607cc9eb8fa51a3fecd6 | 1,135 | package team.univ.magic_conch.bundle;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import team.univ.magic_conch.team.Team;
import java.util.List;
import java.util.Optional;
public interface BundleRepository extends JpaRepository<Bundle, Long> {
@EntityGraph(attributePaths = {"tag"}, type = EntityGraph.EntityGraphType.LOAD)
List<Bundle> findAllByUserUsername(@Param("username") String username);
@EntityGraph(attributePaths = {"questions", "tag"}, type = EntityGraph.EntityGraphType.LOAD)
Optional<Bundle> findWithQuestionsAndTagById(Long id);
@EntityGraph(attributePaths = {"tag"}, type = EntityGraph.EntityGraphType.LOAD)
Page<Bundle> findAllByUserUsername(@Param("username") String username, Pageable pageable);
List<Bundle> findAllByNameContaining(String bundleName);
Optional<Bundle> findByName(String bundleName);
List<Bundle> findAllByTeam(Team team);
}
| 36.612903 | 96 | 0.787665 |
5c655aa6dc96ed72090a4cf0c2b1d0488fa8af1c | 2,946 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2011 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.soap.mail.message;
import com.google.common.base.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.zimbra.common.soap.MailConstants;
import com.zimbra.soap.mail.type.MailSearchParams;
import com.zimbra.soap.type.ZmBoolean;
/**
* @zm-api-command-auth-required true
* @zm-api-command-admin-auth-required false
* @zm-api-command-description Search a conversation
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name=MailConstants.E_SEARCH_CONV_REQUEST)
public class SearchConvRequest extends MailSearchParams {
/**
* @zm-api-field-tag conversation-id
* @zm-api-field-description The ID of the conversation to search within. <b>REQUIRED</b>.
*/
@XmlAttribute(name=MailConstants.A_CONV_ID /* cid */, required=true)
private final String conversationId;
/**
* @zm-api-field-tag nest-messages-inside-conv
* @zm-api-field-description If set then the response will contain a top level <b><c</b> element representing
* the conversation with child <b><m></b> elements representing messages in the conversation.
* <br />
* If unset, no <b><c></b> element is included - <b><m></b> elements will be top level elements.
*/
@XmlAttribute(name=MailConstants.A_NEST_MESSAGES /* nest */, required=false)
private ZmBoolean nestMessages;
/**
* no-argument constructor wanted by JAXB
*/
@SuppressWarnings("unused")
private SearchConvRequest() {
this((String) null);
}
public SearchConvRequest(String conversationId) {
this.conversationId = conversationId;
}
public void setNestMessages(Boolean nestMessages) { this.nestMessages = ZmBoolean.fromBool(nestMessages); }
public Boolean getNestMessages() { return ZmBoolean.toBool(nestMessages); }
public String getConversationId() { return conversationId; }
public Objects.ToStringHelper addToStringInfo(Objects.ToStringHelper helper) {
helper = super.addToStringInfo(helper);
return helper
.add("nestMessages", nestMessages)
.add("conversationId", conversationId);
}
@Override
public String toString() {
return addToStringInfo(Objects.toStringHelper(this)).toString();
}
}
| 35.926829 | 116 | 0.712492 |
04933c3c31a17432b76ed44eccdb8fedf5dfb086 | 757 | package apitrace.github.io.eglretrace;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import java.io.IOException;
public abstract class AbstractServer extends Thread {
public AbstractServer(String name) throws IOException {
m_localServer = new LocalServerSocket(name);
}
private LocalServerSocket m_localServer;
public void close() throws IOException {
m_localServer.close();
}
@Override
public void run() {
while(true) {
try {
accepted(m_localServer.accept());
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
protected abstract void accepted(LocalSocket socket);
}
| 23.65625 | 59 | 0.627477 |
42969a91428400c9fd4663fe45a284e17ac65b90 | 906 | package org.educama.common.exceptions;
/**
* Exception to throw if resource cannot be found.
*/
@SuppressWarnings("serial")
public class ResourceNotFoundException extends RuntimeException {
private final String messageKey;
/**
* Constructor to initialize exception with a message key to translate.
*
* @param messageKey the message key to translate
*/
public ResourceNotFoundException(String messageKey) {
this.messageKey = messageKey;
}
/**
* Constructor to initialize exception with a message key to translate and error cause.
*
* @param messageKey the message key to translate
* @param cause the cause
*/
public ResourceNotFoundException(String messageKey, Throwable cause) {
super(cause);
this.messageKey = messageKey;
}
public String getMessageKey() {
return messageKey;
}
}
| 25.166667 | 91 | 0.6766 |
06b8e6a9f74346688bdb457cff07b5daae351ee8 | 1,874 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.impl.tree;
import java.util.ArrayList;
import java.util.List;
import org.camunda.bpm.engine.impl.pvm.runtime.LegacyBehavior;
import org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl;
/**
* Collects executions that execute an activity instance that is a leaf in the activity instance tree.
* Typically, such executions are also leaves in the execution tree. The exception to this are compensation-throwing
* executions: Their activities are leaves but they have child executions responsible for compensation handling.
*
* @author Thorben Lindhauer
*
*/
public class LeafActivityInstanceExecutionCollector implements TreeVisitor<PvmExecutionImpl> {
protected List<PvmExecutionImpl> leaves = new ArrayList<PvmExecutionImpl>();
public void visit(PvmExecutionImpl obj) {
if (obj.getNonEventScopeExecutions().isEmpty() || (obj.getActivity() != null && !LegacyBehavior.hasInvalidIntermediaryActivityId(obj))) {
leaves.add(obj);
}
}
public List<PvmExecutionImpl> getLeaves() {
return leaves;
}
} | 40.73913 | 141 | 0.770544 |
a7b42a3c21263b70ece6cf14cbe887985428d51d | 7,867 | /*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' 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 com.jme3.scene.plugins.blender.file;
import com.jme3.scene.plugins.blender.BlenderContext;
import com.jme3.scene.plugins.blender.exceptions.BlenderFileException;
import java.util.ArrayList;
import java.util.List;
/**
* A class that represents a pointer of any level that can be stored in the file.
* @author Marcin Roguski
*/
public class Pointer {
/** The blender context. */
private BlenderContext blenderContext;
/** The level of the pointer. */
private int pointerLevel;
/** The address in file it points to. */
private long oldMemoryAddress;
/** This variable indicates if the field is a function pointer. */
public boolean function;
/**
* Constructr. Stores the basic data about the pointer.
* @param pointerLevel
* the level of the pointer
* @param function
* this variable indicates if the field is a function pointer
* @param blenderContext
* the repository f data; used in fetching the value that the pointer points
*/
public Pointer(int pointerLevel, boolean function, BlenderContext blenderContext) {
this.pointerLevel = pointerLevel;
this.function = function;
this.blenderContext = blenderContext;
}
/**
* This method fills the pointer with its address value (it doesn't get the actual data yet. Use the 'fetch' method
* for this.
* @param inputStream
* the stream we read the pointer value from
*/
public void fill(BlenderInputStream inputStream) {
oldMemoryAddress = inputStream.readPointer();
}
/**
* This method fetches the data stored under the given address.
* @param inputStream
* the stream we read data from
* @return the data read from the file
* @throws BlenderFileException
* this exception is thrown when the blend file structure is somehow invalid or corrupted
*/
public List<Structure> fetchData(BlenderInputStream inputStream) throws BlenderFileException {
if (oldMemoryAddress == 0) {
throw new NullPointerException("The pointer points to nothing!");
}
List<Structure> structures = null;
FileBlockHeader dataFileBlock = blenderContext.getFileBlock(oldMemoryAddress);
if (dataFileBlock == null) {
throw new BlenderFileException("No data stored for address: " + oldMemoryAddress + ". Rarely blender makes mistakes when storing data. Try resaving the model after making minor changes. This usually helps.");
}
if (pointerLevel > 1) {
int pointersAmount = dataFileBlock.getSize() / inputStream.getPointerSize() * dataFileBlock.getCount();
for (int i = 0; i < pointersAmount; ++i) {
inputStream.setPosition(dataFileBlock.getBlockPosition() + inputStream.getPointerSize() * i);
long oldMemoryAddress = inputStream.readPointer();
if (oldMemoryAddress != 0L) {
Pointer p = new Pointer(pointerLevel - 1, this.function, blenderContext);
p.oldMemoryAddress = oldMemoryAddress;
if (structures == null) {
structures = p.fetchData(inputStream);
} else {
structures.addAll(p.fetchData(inputStream));
}
} else {
// it is necessary to put null's if the pointer is null, ie. in materials array that is attached to the mesh, the index
// of the material is important, that is why we need null's to indicate that some materials' slots are empty
if (structures == null) {
structures = new ArrayList<Structure>();
}
structures.add(null);
}
}
} else {
inputStream.setPosition(dataFileBlock.getBlockPosition());
structures = new ArrayList<Structure>(dataFileBlock.getCount());
for (int i = 0; i < dataFileBlock.getCount(); ++i) {
Structure structure = blenderContext.getDnaBlockData().getStructure(dataFileBlock.getSdnaIndex());
structure.fill(inputStream);
structures.add(structure);
}
return structures;
}
return structures;
}
/**
* This method indicates if this pointer points to a function.
* @return <b>true</b> if this is a function pointer and <b>false</b> otherwise
*/
public boolean isFunction() {
return function;
}
/**
* This method indicates if this is a null-pointer or not.
* @return <b>true</b> if the pointer is null and <b>false</b> otherwise
*/
public boolean isNull() {
return oldMemoryAddress == 0;
}
/**
* This method indicates if this is a null-pointer or not.
* @return <b>true</b> if the pointer is not null and <b>false</b> otherwise
*/
public boolean isNotNull() {
return oldMemoryAddress != 0;
}
/**
* This method returns the old memory address of the structure pointed by the pointer.
* @return the old memory address of the structure pointed by the pointer
*/
public long getOldMemoryAddress() {
return oldMemoryAddress;
}
@Override
public String toString() {
return oldMemoryAddress == 0 ? "{$null$}" : "{$" + oldMemoryAddress + "$}";
}
@Override
public int hashCode() {
return 31 + (int) (oldMemoryAddress ^ oldMemoryAddress >>> 32);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Pointer other = (Pointer) obj;
if (oldMemoryAddress != other.oldMemoryAddress) {
return false;
}
return true;
}
}
| 41.188482 | 221 | 0.619169 |
70549bc5cd6578d5d1ba48bbd8b56f76b4084d7e | 485 | package com.cloudskol.apiman.base64;
import com.cloudskol.apiman.base.APIManException;
import org.junit.Test;
/**
* @author tham
*/
public class Base64ManagerTest {
@Test
public void testEncode() throws APIManException {
final String encoded = Base64Manager.getInstance().encode("Thamizharasu");
System.out.println(encoded);
final String decodedValue = Base64Manager.getInstance().decode(encoded);
System.out.printf(decodedValue);
}
}
| 24.25 | 82 | 0.71134 |
cae33708993baa08973768a802eac811e62aea65 | 1,294 | package sumofmultiples;
import java.util.ArrayList;
/** program to find all multiples of 3 or 5 below 1000 then find the result of adding them all together. **/
public class SumOfMultiples {
public static void main(String[] args) {
// Calculate sum of all multiples.
long sumOfMultiples = sumMultiples(getMultiplesOf(3, 5, 1000));
// Log result.
System.out.print("\nThe sum of multiples of 3 and 5 below 1000 is " + sumOfMultiples + ".\n\n");
}
/** method to return the multiples of x or y below the limit . **/
public static ArrayList<Integer> getMultiplesOf(int firstMultiple, int secondMultiple, int limit)
{
ArrayList<Integer> allMultiples = new ArrayList<>();
for (int i = 0; i < limit; i++)
{
if ((i % firstMultiple == 0) || (i % secondMultiple == 0)) allMultiples.add(i);
}
return allMultiples;
}
/** method to return sum of all values inside array-list passed in. **/
public static long sumMultiples(ArrayList<Integer> allMultiples)
{
long sum = 0;
for (int i = 0; i < allMultiples.size(); i++)
{
sum += allMultiples.get(i);
}
return sum;
}
}
| 30.093023 | 108 | 0.578825 |
6bec7b0e062f663b8cda71156ccca6427fc59c9e | 850 | package com.misty.jmm;
/**
* @ClassName VolatileDemoTest
* @Description TODO
* @Author HeTao
* @Date 2021/4/15 15:35
* @Version 1.0
**/
public class VolatileDemoTest {
private static int num = 0;
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int j=0 ;j< 1000 ;j++){
increase();
}
}
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println(num);
}
public static void increase() {
num++;
}
}
| 22.972973 | 72 | 0.476471 |
589dcb27d5f7e50d40107af028ac269f3ff12472 | 5,445 | package emissary.place.sample;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import emissary.core.IBaseDataObject;
import emissary.place.ServiceProviderPlace;
import emissary.server.mvc.DocumentAction;
/**
* Store payload objects that come from web submissions until they are retrieved by SUBMISSION_TOKEN value
*/
public class WebSubmissionPlace extends ServiceProviderPlace implements emissary.place.AgentsNotSupportedPlace {
/** The hash of stored documents */
protected final Map<String, List<IBaseDataObject>> map = new HashMap<String, List<IBaseDataObject>>();
/** Matching output types will have data available */
protected List<String> outputTypes;
/** Matchine view names will have view data available */
protected List<String> viewTypes;
/**
* Create and register with all defaults
*/
public WebSubmissionPlace() throws IOException {
super();
configure();
}
/**
* Create and register
*/
public WebSubmissionPlace(String configInfo, String dir, String placeLoc) throws IOException {
super(configInfo, dir, placeLoc);
configure();
}
/**
* Create for test
*/
public WebSubmissionPlace(String configInfo) throws IOException {
super(configInfo, "WebSubmissionPlace.www.example.com:8001");
configure();
}
/**
* Configure our stuff
*/
protected void configure() {
outputTypes = configG.findEntries("OUTPUT_DATA_TYPE", ".*");
viewTypes = configG.findEntries("OUTPUT_VIEW_TYPE", ".*");
}
/**
* Consume the data object list
*/
@Override
public List<IBaseDataObject> agentProcessHeavyDuty(List<IBaseDataObject> payloadList) {
// Nuke the form that got us here
for (IBaseDataObject payload : payloadList) {
nukeMyProxies(payload);
}
// Sort the list of records
Collections.sort(payloadList, new emissary.util.ShortNameComparator());
// Grab the submission token
String token = payloadList.get(0).getStringParameter(DocumentAction.SUBMISSION_TOKEN);
// Store the payload
if (token != null) {
synchronized (map) {
logger.debug("Storing family tree payload " + token + " (" + payloadList.size() + ")");
List<IBaseDataObject> clones = new ArrayList<IBaseDataObject>();
for (IBaseDataObject d : payloadList) {
try {
clones.add(d.clone());
} catch (CloneNotSupportedException ex) {
logger.warn("Cannot clone payload", ex);
clones.add(d);
}
}
map.put(token, clones);
}
}
return Collections.emptyList();
}
/**
* Take something from the store, if found removed from map
*
* @param token the web submission token
* @return the stored family tree or null
*/
public List<IBaseDataObject> take(String token) {
List<IBaseDataObject> list = null;
synchronized (map) {
list = map.remove(token);
}
// Clear out unwanted data
if (list != null) {
for (IBaseDataObject d : list) {
// Test current forms and file type
if (!matchesAny(d.getAllCurrentForms(), outputTypes) && !matchesAny(d.getFileType(), outputTypes)) {
logger.debug("Clearing data " + d.getAllCurrentForms() + ", " + d.getFileType());
d.setData(null);
}
// Test alternate views
for (String avname : d.getAlternateViewNames()) {
if (!matchesAny(avname, viewTypes)) {
logger.debug("Clearing alt view " + avname);
d.addAlternateView(avname, null);
}
}
}
}
return list;
}
/**
* Match against all
*/
private boolean matchesAny(List<String> forms, List<String> patterns) {
for (String f : forms) {
if (f == null) {
continue;
}
for (String p : patterns) {
if (f.matches(p)) {
logger.debug("Pattern match " + f + " with " + p);
return true;
}
logger.debug("Pattern no-match " + f + " with " + p);
}
}
return false;
}
/**
* Match against all
*/
private boolean matchesAny(String form, List<String> patterns) {
if (form == null) {
return false;
}
for (String p : patterns) {
if (form.matches(p)) {
logger.debug("Pattern match " + form + " with " + p);
return true;
}
logger.debug("Pattern no-match " + form + " with " + p);
}
return false;
}
/**
* List the keys in the map
*/
public synchronized List<String> keys() {
return new ArrayList<String>(map.keySet());
}
/**
* Test run
*/
public static void main(String[] argv) {
mainRunner(WebSubmissionPlace.class.getName(), argv);
}
}
| 29.917582 | 116 | 0.553168 |
baa291ceef61012fbb043ba17e59369060bf4c6a | 1,625 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.util;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
public final class VersionInfoTest {
@Test
public void versionIsTheSameAsMavenProject() throws Exception {
assertThat(VersionInfo.SDK_VERSION).isEqualTo(getSdkVersionFromPom());
}
private String getSdkVersionFromPom() throws URISyntaxException, IOException {
Path pomPath = Paths.get(VersionInfo.class.getResource(".").toURI()).resolve("../../../../../../../pom.xml");
String pom = new String(Files.readAllBytes(pomPath));
Matcher match = Pattern.compile("<version>(.*)</version>").matcher(pom);
if (match.find()) {
return match.group(1);
}
throw new RuntimeException("Version not found in " + pomPath);
}
}
| 33.854167 | 117 | 0.710769 |
cdb0dca6a336f658c18a1fd526d194b10b0aa424 | 2,061 | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc., and individual contributors as indicated
* by the @authors tag.
*
* 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.jboss.as.controller.capability.registry;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.capability.Capability;
/**
* Registry that holds possible capabilities. <p>
* Possible capabilities are definitions of capabilities that are registered on resource to provide information
* of what all real or runtime capabilities will be registered once instance of said resource is added to resource tree.
*
* @author Tomaz Cerar (c) 2015 Red Hat Inc.
*/
public interface PossibleCapabilityRegistry {
/**
* Registers a possible capability with the system.
*
* @param capability the possible capability. Cannot be {@code null}
*/
void registerPossibleCapability(Capability capability, PathAddress registrationPoint);
/**
* Remove a previously registered possible capability if all registration points for it have been removed.
*
* @param capability the capability. Cannot be {@code null}
* @param registrationPoint the specific registration point that is being removed
* @return the capability that was removed, or {@code null} if no matching capability was registered or other
* registration points for the capability still exist
*/
CapabilityRegistration<?> removePossibleCapability(Capability capability, PathAddress registrationPoint);
}
| 38.886792 | 120 | 0.749636 |
c77cd80ec3db3fa95a8c12873b00a29ce8c21125 | 65,811 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datalabeling/v1beta1/evaluation.proto
package com.google.cloud.datalabeling.v1beta1;
/**
*
*
* <pre>
* Describes an evaluation between a machine learning model's predictions and
* ground truth labels. Created when an [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] runs successfully.
* </pre>
*
* Protobuf type {@code google.cloud.datalabeling.v1beta1.Evaluation}
*/
public final class Evaluation extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datalabeling.v1beta1.Evaluation)
EvaluationOrBuilder {
private static final long serialVersionUID = 0L;
// Use Evaluation.newBuilder() to construct.
private Evaluation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Evaluation() {
name_ = "";
annotationType_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new Evaluation();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private Evaluation(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
case 18:
{
com.google.cloud.datalabeling.v1beta1.EvaluationConfig.Builder subBuilder = null;
if (config_ != null) {
subBuilder = config_.toBuilder();
}
config_ =
input.readMessage(
com.google.cloud.datalabeling.v1beta1.EvaluationConfig.parser(),
extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(config_);
config_ = subBuilder.buildPartial();
}
break;
}
case 26:
{
com.google.protobuf.Timestamp.Builder subBuilder = null;
if (evaluationJobRunTime_ != null) {
subBuilder = evaluationJobRunTime_.toBuilder();
}
evaluationJobRunTime_ =
input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(evaluationJobRunTime_);
evaluationJobRunTime_ = subBuilder.buildPartial();
}
break;
}
case 34:
{
com.google.protobuf.Timestamp.Builder subBuilder = null;
if (createTime_ != null) {
subBuilder = createTime_.toBuilder();
}
createTime_ =
input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(createTime_);
createTime_ = subBuilder.buildPartial();
}
break;
}
case 42:
{
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.Builder subBuilder = null;
if (evaluationMetrics_ != null) {
subBuilder = evaluationMetrics_.toBuilder();
}
evaluationMetrics_ =
input.readMessage(
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.parser(),
extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(evaluationMetrics_);
evaluationMetrics_ = subBuilder.buildPartial();
}
break;
}
case 48:
{
int rawValue = input.readEnum();
annotationType_ = rawValue;
break;
}
case 56:
{
evaluatedItemCount_ = input.readInt64();
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datalabeling.v1beta1.EvaluationOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Evaluation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datalabeling.v1beta1.EvaluationOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Evaluation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datalabeling.v1beta1.Evaluation.class,
com.google.cloud.datalabeling.v1beta1.Evaluation.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
*
*
* <pre>
* Output only. Resource name of an evaluation. The name has the following
* format:
* "projects/<var>{project_id}</var>/datasets/<var>{dataset_id}</var>/evaluations/<var>{evaluation_id</var>}'
* </pre>
*
* <code>string name = 1;</code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Output only. Resource name of an evaluation. The name has the following
* format:
* "projects/<var>{project_id}</var>/datasets/<var>{dataset_id}</var>/evaluations/<var>{evaluation_id</var>}'
* </pre>
*
* <code>string name = 1;</code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CONFIG_FIELD_NUMBER = 2;
private com.google.cloud.datalabeling.v1beta1.EvaluationConfig config_;
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*
* @return Whether the config field is set.
*/
@java.lang.Override
public boolean hasConfig() {
return config_ != null;
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*
* @return The config.
*/
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.EvaluationConfig getConfig() {
return config_ == null
? com.google.cloud.datalabeling.v1beta1.EvaluationConfig.getDefaultInstance()
: config_;
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*/
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.EvaluationConfigOrBuilder getConfigOrBuilder() {
return getConfig();
}
public static final int EVALUATION_JOB_RUN_TIME_FIELD_NUMBER = 3;
private com.google.protobuf.Timestamp evaluationJobRunTime_;
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*
* @return Whether the evaluationJobRunTime field is set.
*/
@java.lang.Override
public boolean hasEvaluationJobRunTime() {
return evaluationJobRunTime_ != null;
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*
* @return The evaluationJobRunTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getEvaluationJobRunTime() {
return evaluationJobRunTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: evaluationJobRunTime_;
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getEvaluationJobRunTimeOrBuilder() {
return getEvaluationJobRunTime();
}
public static final int CREATE_TIME_FIELD_NUMBER = 4;
private com.google.protobuf.Timestamp createTime_;
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*
* @return Whether the createTime field is set.
*/
@java.lang.Override
public boolean hasCreateTime() {
return createTime_ != null;
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*
* @return The createTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getCreateTime() {
return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_;
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() {
return getCreateTime();
}
public static final int EVALUATION_METRICS_FIELD_NUMBER = 5;
private com.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluationMetrics_;
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*
* @return Whether the evaluationMetrics field is set.
*/
@java.lang.Override
public boolean hasEvaluationMetrics() {
return evaluationMetrics_ != null;
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*
* @return The evaluationMetrics.
*/
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.EvaluationMetrics getEvaluationMetrics() {
return evaluationMetrics_ == null
? com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.getDefaultInstance()
: evaluationMetrics_;
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*/
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.EvaluationMetricsOrBuilder
getEvaluationMetricsOrBuilder() {
return getEvaluationMetrics();
}
public static final int ANNOTATION_TYPE_FIELD_NUMBER = 6;
private int annotationType_;
/**
*
*
* <pre>
* Output only. Type of task that the model version being evaluated performs,
* as defined in the
* [evaluationJobConfig.inputConfig.annotationType][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]
* field of the evaluation job that created this evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.AnnotationType annotation_type = 6;</code>
*
* @return The enum numeric value on the wire for annotationType.
*/
@java.lang.Override
public int getAnnotationTypeValue() {
return annotationType_;
}
/**
*
*
* <pre>
* Output only. Type of task that the model version being evaluated performs,
* as defined in the
* [evaluationJobConfig.inputConfig.annotationType][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]
* field of the evaluation job that created this evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.AnnotationType annotation_type = 6;</code>
*
* @return The annotationType.
*/
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.AnnotationType getAnnotationType() {
@SuppressWarnings("deprecation")
com.google.cloud.datalabeling.v1beta1.AnnotationType result =
com.google.cloud.datalabeling.v1beta1.AnnotationType.valueOf(annotationType_);
return result == null
? com.google.cloud.datalabeling.v1beta1.AnnotationType.UNRECOGNIZED
: result;
}
public static final int EVALUATED_ITEM_COUNT_FIELD_NUMBER = 7;
private long evaluatedItemCount_;
/**
*
*
* <pre>
* Output only. The number of items in the ground truth dataset that were used
* for this evaluation. Only populated when the evaulation is for certain
* AnnotationTypes.
* </pre>
*
* <code>int64 evaluated_item_count = 7;</code>
*
* @return The evaluatedItemCount.
*/
@java.lang.Override
public long getEvaluatedItemCount() {
return evaluatedItemCount_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (config_ != null) {
output.writeMessage(2, getConfig());
}
if (evaluationJobRunTime_ != null) {
output.writeMessage(3, getEvaluationJobRunTime());
}
if (createTime_ != null) {
output.writeMessage(4, getCreateTime());
}
if (evaluationMetrics_ != null) {
output.writeMessage(5, getEvaluationMetrics());
}
if (annotationType_
!= com.google.cloud.datalabeling.v1beta1.AnnotationType.ANNOTATION_TYPE_UNSPECIFIED
.getNumber()) {
output.writeEnum(6, annotationType_);
}
if (evaluatedItemCount_ != 0L) {
output.writeInt64(7, evaluatedItemCount_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (config_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getConfig());
}
if (evaluationJobRunTime_ != null) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(3, getEvaluationJobRunTime());
}
if (createTime_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getCreateTime());
}
if (evaluationMetrics_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, getEvaluationMetrics());
}
if (annotationType_
!= com.google.cloud.datalabeling.v1beta1.AnnotationType.ANNOTATION_TYPE_UNSPECIFIED
.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(6, annotationType_);
}
if (evaluatedItemCount_ != 0L) {
size += com.google.protobuf.CodedOutputStream.computeInt64Size(7, evaluatedItemCount_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.datalabeling.v1beta1.Evaluation)) {
return super.equals(obj);
}
com.google.cloud.datalabeling.v1beta1.Evaluation other =
(com.google.cloud.datalabeling.v1beta1.Evaluation) obj;
if (!getName().equals(other.getName())) return false;
if (hasConfig() != other.hasConfig()) return false;
if (hasConfig()) {
if (!getConfig().equals(other.getConfig())) return false;
}
if (hasEvaluationJobRunTime() != other.hasEvaluationJobRunTime()) return false;
if (hasEvaluationJobRunTime()) {
if (!getEvaluationJobRunTime().equals(other.getEvaluationJobRunTime())) return false;
}
if (hasCreateTime() != other.hasCreateTime()) return false;
if (hasCreateTime()) {
if (!getCreateTime().equals(other.getCreateTime())) return false;
}
if (hasEvaluationMetrics() != other.hasEvaluationMetrics()) return false;
if (hasEvaluationMetrics()) {
if (!getEvaluationMetrics().equals(other.getEvaluationMetrics())) return false;
}
if (annotationType_ != other.annotationType_) return false;
if (getEvaluatedItemCount() != other.getEvaluatedItemCount()) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
if (hasConfig()) {
hash = (37 * hash) + CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getConfig().hashCode();
}
if (hasEvaluationJobRunTime()) {
hash = (37 * hash) + EVALUATION_JOB_RUN_TIME_FIELD_NUMBER;
hash = (53 * hash) + getEvaluationJobRunTime().hashCode();
}
if (hasCreateTime()) {
hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER;
hash = (53 * hash) + getCreateTime().hashCode();
}
if (hasEvaluationMetrics()) {
hash = (37 * hash) + EVALUATION_METRICS_FIELD_NUMBER;
hash = (53 * hash) + getEvaluationMetrics().hashCode();
}
hash = (37 * hash) + ANNOTATION_TYPE_FIELD_NUMBER;
hash = (53 * hash) + annotationType_;
hash = (37 * hash) + EVALUATED_ITEM_COUNT_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getEvaluatedItemCount());
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.datalabeling.v1beta1.Evaluation prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Describes an evaluation between a machine learning model's predictions and
* ground truth labels. Created when an [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] runs successfully.
* </pre>
*
* Protobuf type {@code google.cloud.datalabeling.v1beta1.Evaluation}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datalabeling.v1beta1.Evaluation)
com.google.cloud.datalabeling.v1beta1.EvaluationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datalabeling.v1beta1.EvaluationOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Evaluation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datalabeling.v1beta1.EvaluationOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Evaluation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datalabeling.v1beta1.Evaluation.class,
com.google.cloud.datalabeling.v1beta1.Evaluation.Builder.class);
}
// Construct using com.google.cloud.datalabeling.v1beta1.Evaluation.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
name_ = "";
if (configBuilder_ == null) {
config_ = null;
} else {
config_ = null;
configBuilder_ = null;
}
if (evaluationJobRunTimeBuilder_ == null) {
evaluationJobRunTime_ = null;
} else {
evaluationJobRunTime_ = null;
evaluationJobRunTimeBuilder_ = null;
}
if (createTimeBuilder_ == null) {
createTime_ = null;
} else {
createTime_ = null;
createTimeBuilder_ = null;
}
if (evaluationMetricsBuilder_ == null) {
evaluationMetrics_ = null;
} else {
evaluationMetrics_ = null;
evaluationMetricsBuilder_ = null;
}
annotationType_ = 0;
evaluatedItemCount_ = 0L;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datalabeling.v1beta1.EvaluationOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Evaluation_descriptor;
}
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.Evaluation getDefaultInstanceForType() {
return com.google.cloud.datalabeling.v1beta1.Evaluation.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.Evaluation build() {
com.google.cloud.datalabeling.v1beta1.Evaluation result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.Evaluation buildPartial() {
com.google.cloud.datalabeling.v1beta1.Evaluation result =
new com.google.cloud.datalabeling.v1beta1.Evaluation(this);
result.name_ = name_;
if (configBuilder_ == null) {
result.config_ = config_;
} else {
result.config_ = configBuilder_.build();
}
if (evaluationJobRunTimeBuilder_ == null) {
result.evaluationJobRunTime_ = evaluationJobRunTime_;
} else {
result.evaluationJobRunTime_ = evaluationJobRunTimeBuilder_.build();
}
if (createTimeBuilder_ == null) {
result.createTime_ = createTime_;
} else {
result.createTime_ = createTimeBuilder_.build();
}
if (evaluationMetricsBuilder_ == null) {
result.evaluationMetrics_ = evaluationMetrics_;
} else {
result.evaluationMetrics_ = evaluationMetricsBuilder_.build();
}
result.annotationType_ = annotationType_;
result.evaluatedItemCount_ = evaluatedItemCount_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.datalabeling.v1beta1.Evaluation) {
return mergeFrom((com.google.cloud.datalabeling.v1beta1.Evaluation) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datalabeling.v1beta1.Evaluation other) {
if (other == com.google.cloud.datalabeling.v1beta1.Evaluation.getDefaultInstance())
return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
if (other.hasConfig()) {
mergeConfig(other.getConfig());
}
if (other.hasEvaluationJobRunTime()) {
mergeEvaluationJobRunTime(other.getEvaluationJobRunTime());
}
if (other.hasCreateTime()) {
mergeCreateTime(other.getCreateTime());
}
if (other.hasEvaluationMetrics()) {
mergeEvaluationMetrics(other.getEvaluationMetrics());
}
if (other.annotationType_ != 0) {
setAnnotationTypeValue(other.getAnnotationTypeValue());
}
if (other.getEvaluatedItemCount() != 0L) {
setEvaluatedItemCount(other.getEvaluatedItemCount());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.datalabeling.v1beta1.Evaluation parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.datalabeling.v1beta1.Evaluation) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Output only. Resource name of an evaluation. The name has the following
* format:
* "projects/<var>{project_id}</var>/datasets/<var>{dataset_id}</var>/evaluations/<var>{evaluation_id</var>}'
* </pre>
*
* <code>string name = 1;</code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Output only. Resource name of an evaluation. The name has the following
* format:
* "projects/<var>{project_id}</var>/datasets/<var>{dataset_id}</var>/evaluations/<var>{evaluation_id</var>}'
* </pre>
*
* <code>string name = 1;</code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Output only. Resource name of an evaluation. The name has the following
* format:
* "projects/<var>{project_id}</var>/datasets/<var>{dataset_id}</var>/evaluations/<var>{evaluation_id</var>}'
* </pre>
*
* <code>string name = 1;</code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Resource name of an evaluation. The name has the following
* format:
* "projects/<var>{project_id}</var>/datasets/<var>{dataset_id}</var>/evaluations/<var>{evaluation_id</var>}'
* </pre>
*
* <code>string name = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Resource name of an evaluation. The name has the following
* format:
* "projects/<var>{project_id}</var>/datasets/<var>{dataset_id}</var>/evaluations/<var>{evaluation_id</var>}'
* </pre>
*
* <code>string name = 1;</code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
private com.google.cloud.datalabeling.v1beta1.EvaluationConfig config_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.datalabeling.v1beta1.EvaluationConfig,
com.google.cloud.datalabeling.v1beta1.EvaluationConfig.Builder,
com.google.cloud.datalabeling.v1beta1.EvaluationConfigOrBuilder>
configBuilder_;
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*
* @return Whether the config field is set.
*/
public boolean hasConfig() {
return configBuilder_ != null || config_ != null;
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*
* @return The config.
*/
public com.google.cloud.datalabeling.v1beta1.EvaluationConfig getConfig() {
if (configBuilder_ == null) {
return config_ == null
? com.google.cloud.datalabeling.v1beta1.EvaluationConfig.getDefaultInstance()
: config_;
} else {
return configBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*/
public Builder setConfig(com.google.cloud.datalabeling.v1beta1.EvaluationConfig value) {
if (configBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
config_ = value;
onChanged();
} else {
configBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*/
public Builder setConfig(
com.google.cloud.datalabeling.v1beta1.EvaluationConfig.Builder builderForValue) {
if (configBuilder_ == null) {
config_ = builderForValue.build();
onChanged();
} else {
configBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*/
public Builder mergeConfig(com.google.cloud.datalabeling.v1beta1.EvaluationConfig value) {
if (configBuilder_ == null) {
if (config_ != null) {
config_ =
com.google.cloud.datalabeling.v1beta1.EvaluationConfig.newBuilder(config_)
.mergeFrom(value)
.buildPartial();
} else {
config_ = value;
}
onChanged();
} else {
configBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*/
public Builder clearConfig() {
if (configBuilder_ == null) {
config_ = null;
onChanged();
} else {
config_ = null;
configBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*/
public com.google.cloud.datalabeling.v1beta1.EvaluationConfig.Builder getConfigBuilder() {
onChanged();
return getConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*/
public com.google.cloud.datalabeling.v1beta1.EvaluationConfigOrBuilder getConfigOrBuilder() {
if (configBuilder_ != null) {
return configBuilder_.getMessageOrBuilder();
} else {
return config_ == null
? com.google.cloud.datalabeling.v1beta1.EvaluationConfig.getDefaultInstance()
: config_;
}
}
/**
*
*
* <pre>
* Output only. Options used in the evaluation job that created this
* evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationConfig config = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.datalabeling.v1beta1.EvaluationConfig,
com.google.cloud.datalabeling.v1beta1.EvaluationConfig.Builder,
com.google.cloud.datalabeling.v1beta1.EvaluationConfigOrBuilder>
getConfigFieldBuilder() {
if (configBuilder_ == null) {
configBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.datalabeling.v1beta1.EvaluationConfig,
com.google.cloud.datalabeling.v1beta1.EvaluationConfig.Builder,
com.google.cloud.datalabeling.v1beta1.EvaluationConfigOrBuilder>(
getConfig(), getParentForChildren(), isClean());
config_ = null;
}
return configBuilder_;
}
private com.google.protobuf.Timestamp evaluationJobRunTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
evaluationJobRunTimeBuilder_;
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*
* @return Whether the evaluationJobRunTime field is set.
*/
public boolean hasEvaluationJobRunTime() {
return evaluationJobRunTimeBuilder_ != null || evaluationJobRunTime_ != null;
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*
* @return The evaluationJobRunTime.
*/
public com.google.protobuf.Timestamp getEvaluationJobRunTime() {
if (evaluationJobRunTimeBuilder_ == null) {
return evaluationJobRunTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: evaluationJobRunTime_;
} else {
return evaluationJobRunTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*/
public Builder setEvaluationJobRunTime(com.google.protobuf.Timestamp value) {
if (evaluationJobRunTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
evaluationJobRunTime_ = value;
onChanged();
} else {
evaluationJobRunTimeBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*/
public Builder setEvaluationJobRunTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (evaluationJobRunTimeBuilder_ == null) {
evaluationJobRunTime_ = builderForValue.build();
onChanged();
} else {
evaluationJobRunTimeBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*/
public Builder mergeEvaluationJobRunTime(com.google.protobuf.Timestamp value) {
if (evaluationJobRunTimeBuilder_ == null) {
if (evaluationJobRunTime_ != null) {
evaluationJobRunTime_ =
com.google.protobuf.Timestamp.newBuilder(evaluationJobRunTime_)
.mergeFrom(value)
.buildPartial();
} else {
evaluationJobRunTime_ = value;
}
onChanged();
} else {
evaluationJobRunTimeBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*/
public Builder clearEvaluationJobRunTime() {
if (evaluationJobRunTimeBuilder_ == null) {
evaluationJobRunTime_ = null;
onChanged();
} else {
evaluationJobRunTime_ = null;
evaluationJobRunTimeBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*/
public com.google.protobuf.Timestamp.Builder getEvaluationJobRunTimeBuilder() {
onChanged();
return getEvaluationJobRunTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*/
public com.google.protobuf.TimestampOrBuilder getEvaluationJobRunTimeOrBuilder() {
if (evaluationJobRunTimeBuilder_ != null) {
return evaluationJobRunTimeBuilder_.getMessageOrBuilder();
} else {
return evaluationJobRunTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: evaluationJobRunTime_;
}
}
/**
*
*
* <pre>
* Output only. Timestamp for when the evaluation job that created this
* evaluation ran.
* </pre>
*
* <code>.google.protobuf.Timestamp evaluation_job_run_time = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getEvaluationJobRunTimeFieldBuilder() {
if (evaluationJobRunTimeBuilder_ == null) {
evaluationJobRunTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getEvaluationJobRunTime(), getParentForChildren(), isClean());
evaluationJobRunTime_ = null;
}
return evaluationJobRunTimeBuilder_;
}
private com.google.protobuf.Timestamp createTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
createTimeBuilder_;
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*
* @return Whether the createTime field is set.
*/
public boolean hasCreateTime() {
return createTimeBuilder_ != null || createTime_ != null;
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*
* @return The createTime.
*/
public com.google.protobuf.Timestamp getCreateTime() {
if (createTimeBuilder_ == null) {
return createTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: createTime_;
} else {
return createTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*/
public Builder setCreateTime(com.google.protobuf.Timestamp value) {
if (createTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
createTime_ = value;
onChanged();
} else {
createTimeBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*/
public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (createTimeBuilder_ == null) {
createTime_ = builderForValue.build();
onChanged();
} else {
createTimeBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*/
public Builder mergeCreateTime(com.google.protobuf.Timestamp value) {
if (createTimeBuilder_ == null) {
if (createTime_ != null) {
createTime_ =
com.google.protobuf.Timestamp.newBuilder(createTime_).mergeFrom(value).buildPartial();
} else {
createTime_ = value;
}
onChanged();
} else {
createTimeBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*/
public Builder clearCreateTime() {
if (createTimeBuilder_ == null) {
createTime_ = null;
onChanged();
} else {
createTime_ = null;
createTimeBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*/
public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() {
onChanged();
return getCreateTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*/
public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() {
if (createTimeBuilder_ != null) {
return createTimeBuilder_.getMessageOrBuilder();
} else {
return createTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: createTime_;
}
}
/**
*
*
* <pre>
* Output only. Timestamp for when this evaluation was created.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getCreateTimeFieldBuilder() {
if (createTimeBuilder_ == null) {
createTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getCreateTime(), getParentForChildren(), isClean());
createTime_ = null;
}
return createTimeBuilder_;
}
private com.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluationMetrics_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics,
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.Builder,
com.google.cloud.datalabeling.v1beta1.EvaluationMetricsOrBuilder>
evaluationMetricsBuilder_;
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*
* @return Whether the evaluationMetrics field is set.
*/
public boolean hasEvaluationMetrics() {
return evaluationMetricsBuilder_ != null || evaluationMetrics_ != null;
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*
* @return The evaluationMetrics.
*/
public com.google.cloud.datalabeling.v1beta1.EvaluationMetrics getEvaluationMetrics() {
if (evaluationMetricsBuilder_ == null) {
return evaluationMetrics_ == null
? com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.getDefaultInstance()
: evaluationMetrics_;
} else {
return evaluationMetricsBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*/
public Builder setEvaluationMetrics(
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics value) {
if (evaluationMetricsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
evaluationMetrics_ = value;
onChanged();
} else {
evaluationMetricsBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*/
public Builder setEvaluationMetrics(
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.Builder builderForValue) {
if (evaluationMetricsBuilder_ == null) {
evaluationMetrics_ = builderForValue.build();
onChanged();
} else {
evaluationMetricsBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*/
public Builder mergeEvaluationMetrics(
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics value) {
if (evaluationMetricsBuilder_ == null) {
if (evaluationMetrics_ != null) {
evaluationMetrics_ =
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.newBuilder(evaluationMetrics_)
.mergeFrom(value)
.buildPartial();
} else {
evaluationMetrics_ = value;
}
onChanged();
} else {
evaluationMetricsBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*/
public Builder clearEvaluationMetrics() {
if (evaluationMetricsBuilder_ == null) {
evaluationMetrics_ = null;
onChanged();
} else {
evaluationMetrics_ = null;
evaluationMetricsBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*/
public com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.Builder
getEvaluationMetricsBuilder() {
onChanged();
return getEvaluationMetricsFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*/
public com.google.cloud.datalabeling.v1beta1.EvaluationMetricsOrBuilder
getEvaluationMetricsOrBuilder() {
if (evaluationMetricsBuilder_ != null) {
return evaluationMetricsBuilder_.getMessageOrBuilder();
} else {
return evaluationMetrics_ == null
? com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.getDefaultInstance()
: evaluationMetrics_;
}
}
/**
*
*
* <pre>
* Output only. Metrics comparing predictions to ground truth labels.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.EvaluationMetrics evaluation_metrics = 5;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics,
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.Builder,
com.google.cloud.datalabeling.v1beta1.EvaluationMetricsOrBuilder>
getEvaluationMetricsFieldBuilder() {
if (evaluationMetricsBuilder_ == null) {
evaluationMetricsBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics,
com.google.cloud.datalabeling.v1beta1.EvaluationMetrics.Builder,
com.google.cloud.datalabeling.v1beta1.EvaluationMetricsOrBuilder>(
getEvaluationMetrics(), getParentForChildren(), isClean());
evaluationMetrics_ = null;
}
return evaluationMetricsBuilder_;
}
private int annotationType_ = 0;
/**
*
*
* <pre>
* Output only. Type of task that the model version being evaluated performs,
* as defined in the
* [evaluationJobConfig.inputConfig.annotationType][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]
* field of the evaluation job that created this evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.AnnotationType annotation_type = 6;</code>
*
* @return The enum numeric value on the wire for annotationType.
*/
@java.lang.Override
public int getAnnotationTypeValue() {
return annotationType_;
}
/**
*
*
* <pre>
* Output only. Type of task that the model version being evaluated performs,
* as defined in the
* [evaluationJobConfig.inputConfig.annotationType][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]
* field of the evaluation job that created this evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.AnnotationType annotation_type = 6;</code>
*
* @param value The enum numeric value on the wire for annotationType to set.
* @return This builder for chaining.
*/
public Builder setAnnotationTypeValue(int value) {
annotationType_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Type of task that the model version being evaluated performs,
* as defined in the
* [evaluationJobConfig.inputConfig.annotationType][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]
* field of the evaluation job that created this evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.AnnotationType annotation_type = 6;</code>
*
* @return The annotationType.
*/
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.AnnotationType getAnnotationType() {
@SuppressWarnings("deprecation")
com.google.cloud.datalabeling.v1beta1.AnnotationType result =
com.google.cloud.datalabeling.v1beta1.AnnotationType.valueOf(annotationType_);
return result == null
? com.google.cloud.datalabeling.v1beta1.AnnotationType.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* Output only. Type of task that the model version being evaluated performs,
* as defined in the
* [evaluationJobConfig.inputConfig.annotationType][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]
* field of the evaluation job that created this evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.AnnotationType annotation_type = 6;</code>
*
* @param value The annotationType to set.
* @return This builder for chaining.
*/
public Builder setAnnotationType(com.google.cloud.datalabeling.v1beta1.AnnotationType value) {
if (value == null) {
throw new NullPointerException();
}
annotationType_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Type of task that the model version being evaluated performs,
* as defined in the
* [evaluationJobConfig.inputConfig.annotationType][google.cloud.datalabeling.v1beta1.EvaluationJobConfig.input_config]
* field of the evaluation job that created this evaluation.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.AnnotationType annotation_type = 6;</code>
*
* @return This builder for chaining.
*/
public Builder clearAnnotationType() {
annotationType_ = 0;
onChanged();
return this;
}
private long evaluatedItemCount_;
/**
*
*
* <pre>
* Output only. The number of items in the ground truth dataset that were used
* for this evaluation. Only populated when the evaulation is for certain
* AnnotationTypes.
* </pre>
*
* <code>int64 evaluated_item_count = 7;</code>
*
* @return The evaluatedItemCount.
*/
@java.lang.Override
public long getEvaluatedItemCount() {
return evaluatedItemCount_;
}
/**
*
*
* <pre>
* Output only. The number of items in the ground truth dataset that were used
* for this evaluation. Only populated when the evaulation is for certain
* AnnotationTypes.
* </pre>
*
* <code>int64 evaluated_item_count = 7;</code>
*
* @param value The evaluatedItemCount to set.
* @return This builder for chaining.
*/
public Builder setEvaluatedItemCount(long value) {
evaluatedItemCount_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The number of items in the ground truth dataset that were used
* for this evaluation. Only populated when the evaulation is for certain
* AnnotationTypes.
* </pre>
*
* <code>int64 evaluated_item_count = 7;</code>
*
* @return This builder for chaining.
*/
public Builder clearEvaluatedItemCount() {
evaluatedItemCount_ = 0L;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.datalabeling.v1beta1.Evaluation)
}
// @@protoc_insertion_point(class_scope:google.cloud.datalabeling.v1beta1.Evaluation)
private static final com.google.cloud.datalabeling.v1beta1.Evaluation DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datalabeling.v1beta1.Evaluation();
}
public static com.google.cloud.datalabeling.v1beta1.Evaluation getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Evaluation> PARSER =
new com.google.protobuf.AbstractParser<Evaluation>() {
@java.lang.Override
public Evaluation parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Evaluation(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Evaluation> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Evaluation> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.Evaluation getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| 31.869734 | 149 | 0.645622 |
d1d45cb9f1e8eac2a502bd31402cef7087824d62 | 10,398 | /*
* Copyright 2008 Marc Boorshtein
*
* 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 net.sourceforge.myvd.inserts.mapping;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPAttributeSet;
import com.novell.ldap.LDAPConstraints;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPModification;
import com.novell.ldap.LDAPSearchConstraints;
import com.novell.ldap.LDAPUrl;
import com.novell.ldap.util.DN;
import net.sourceforge.myvd.chain.AddInterceptorChain;
import net.sourceforge.myvd.chain.BindInterceptorChain;
import net.sourceforge.myvd.chain.CompareInterceptorChain;
import net.sourceforge.myvd.chain.DeleteInterceptorChain;
import net.sourceforge.myvd.chain.ExetendedOperationInterceptorChain;
import net.sourceforge.myvd.chain.ModifyInterceptorChain;
import net.sourceforge.myvd.chain.PostSearchCompleteInterceptorChain;
import net.sourceforge.myvd.chain.PostSearchEntryInterceptorChain;
import net.sourceforge.myvd.chain.RenameInterceptorChain;
import net.sourceforge.myvd.chain.SearchInterceptorChain;
import net.sourceforge.myvd.core.NameSpace;
import net.sourceforge.myvd.inserts.Insert;
import net.sourceforge.myvd.types.Attribute;
import net.sourceforge.myvd.types.Bool;
import net.sourceforge.myvd.types.DistinguishedName;
import net.sourceforge.myvd.types.Entry;
import net.sourceforge.myvd.types.ExtendedOperation;
import net.sourceforge.myvd.types.Filter;
import net.sourceforge.myvd.types.FilterNode;
import net.sourceforge.myvd.types.Int;
import net.sourceforge.myvd.types.Password;
import net.sourceforge.myvd.types.Results;
import net.sourceforge.myvd.util.NamingUtils;
public class DNAttributeMapper implements Insert {
HashSet<String> dnAttribs;
HashSet<String> urlAttribs;
String[] localBase;
String[] remoteBase;
String localBaseDN;
String remoteBaseDN;
public void add(AddInterceptorChain chain, Entry entry,
LDAPConstraints constraints) throws LDAPException {
Entry nentry = new Entry(this.mapEntry(entry.getEntry(), true));
chain.nextAdd(nentry, constraints);
}
public void bind(BindInterceptorChain chain, DistinguishedName dn,
Password pwd, LDAPConstraints constraints) throws LDAPException {
chain.nextBind(dn, pwd, constraints);
}
public void compare(CompareInterceptorChain chain, DistinguishedName dn,
Attribute attrib, LDAPConstraints constraints) throws LDAPException {
if (this.dnAttribs.contains(attrib.getAttribute().getBaseName())) {
LDAPAttribute nattrib = new LDAPAttribute(attrib.getAttribute().getName());
NamingUtils util = new NamingUtils();
nattrib.addValue(util.getRemoteMappedDN(new DN(attrib.getAttribute().getStringValue()), this.localBase, this.remoteBase).toString());
chain.nextCompare(dn, new Attribute(nattrib), constraints);
} else {
chain.nextCompare(dn, attrib, constraints);
}
}
public void configure(String name, Properties props, NameSpace nameSpace)
throws LDAPException {
this.dnAttribs = new HashSet<String>();
this.urlAttribs = new HashSet<String>();
StringTokenizer toker = new StringTokenizer(props.getProperty("dnAttribs",""),",",false);
while (toker.hasMoreTokens()) {
String attrib = toker.nextToken();
this.dnAttribs.add(attrib.toLowerCase());
}
toker = new StringTokenizer(props.getProperty("urlAttribs",""),",",false);
while (toker.hasMoreTokens()) {
String attrib = toker.nextToken();
this.urlAttribs.add(attrib.toLowerCase());
}
this.remoteBase = (new DN(props.getProperty("remoteBase",""))).explodeDN(false);
this.localBase = (new DN(props.getProperty("localBase",""))).explodeDN(false);
this.localBaseDN = props.getProperty("localBase","").toLowerCase();
this.remoteBaseDN = props.getProperty("remoteBase","").toLowerCase();
}
public void delete(DeleteInterceptorChain chain, DistinguishedName dn,
LDAPConstraints constraints) throws LDAPException {
chain.nextDelete(dn, constraints);
}
public void extendedOperation(ExetendedOperationInterceptorChain chain,
ExtendedOperation op, LDAPConstraints constraints)
throws LDAPException {
chain.nextExtendedOperations(op, constraints);
}
public String getName() {
// TODO Auto-generated method stub
return null;
}
public void modify(ModifyInterceptorChain chain, DistinguishedName dn,
ArrayList<LDAPModification> mods, LDAPConstraints constraints)
throws LDAPException {
NamingUtils util = new NamingUtils();
ArrayList<LDAPModification> nmods = new ArrayList<LDAPModification>();
Iterator<LDAPModification> it = mods.iterator();
while (it.hasNext()) {
LDAPModification mod = it.next();
LDAPAttribute attrib = mod.getAttribute();
LDAPAttribute nattrib = this.mapAttribute(true, util, attrib);
nmods.add(new LDAPModification(mod.getOp(),nattrib));
}
chain.nextModify(dn, nmods, constraints);
}
public void postSearchComplete(PostSearchCompleteInterceptorChain chain,
DistinguishedName base, Int scope, Filter filter,
ArrayList<Attribute> attributes, Bool typesOnly,
LDAPSearchConstraints constraints) throws LDAPException {
chain.nextPostSearchComplete(base, scope, filter, attributes, typesOnly, constraints);
}
public void postSearchEntry(PostSearchEntryInterceptorChain chain,
Entry entry, DistinguishedName base, Int scope, Filter filter,
ArrayList<Attribute> attributes, Bool typesOnly,
LDAPSearchConstraints constraints) throws LDAPException {
chain.nextPostSearchEntry(entry, base, scope, filter, attributes, typesOnly, constraints);
entry.setEntry(this.mapEntry(entry.getEntry(), false));
}
public void rename(RenameInterceptorChain chain, DistinguishedName dn,
DistinguishedName newRdn, Bool deleteOldRdn,
LDAPConstraints constraints) throws LDAPException {
chain.nextRename(dn, newRdn, deleteOldRdn, constraints);
}
public void rename(RenameInterceptorChain chain, DistinguishedName dn,
DistinguishedName newRdn, DistinguishedName newParentDN,
Bool deleteOldRdn, LDAPConstraints constraints)
throws LDAPException {
chain.nextRename(dn, newRdn, newParentDN, deleteOldRdn, constraints);
}
public void search(SearchInterceptorChain chain, DistinguishedName base,
Int scope, Filter filter, ArrayList<Attribute> attributes,
Bool typesOnly, Results results, LDAPSearchConstraints constraints)
throws LDAPException {
Filter nfilter = null;
try {
nfilter = new Filter((FilterNode) filter.getRoot().clone());
} catch (CloneNotSupportedException e) {
//can't happen
}
this.mapFilter(nfilter.getRoot());
chain.nextSearch(base, scope, nfilter, attributes, typesOnly, results, constraints);
}
public LDAPEntry mapEntry(LDAPEntry origEntry,boolean outbound) {
NamingUtils util = new NamingUtils();
LDAPAttributeSet nattribs = new LDAPAttributeSet();
LDAPAttributeSet origAttribs = origEntry.getAttributeSet();
Iterator it = origAttribs.iterator();
while (it.hasNext()) {
LDAPAttribute origAttrib = (LDAPAttribute) it.next();
LDAPAttribute nattrib = mapAttribute(outbound, util, origAttrib);
nattribs.add(nattrib);
}
return new LDAPEntry(origEntry.getDN(),nattribs);
}
private LDAPAttribute mapAttribute(boolean outbound, NamingUtils util, LDAPAttribute origAttrib) {
LDAPAttribute nattrib = new LDAPAttribute(origAttrib.getName());
if (this.dnAttribs.contains(origAttrib.getName().toLowerCase())) {
Enumeration enumer = origAttrib.getStringValues();
while (enumer.hasMoreElements()) {
String dn = (String) enumer.nextElement();
if (outbound) {
if (dn.toLowerCase().endsWith(this.localBaseDN)) {
nattrib.addValue(util.getRemoteMappedDN(new DN(dn), this.localBase, this.remoteBase).toString());
} else {
nattrib.addValue(dn);
}
} else {
if (dn.toLowerCase().endsWith(this.remoteBaseDN)) {
nattrib.addValue(util.getLocalMappedDN(new DN(dn), this.remoteBase, this.localBase).toString());
} else {
nattrib.addValue(dn);
}
}
}
} else if (this.urlAttribs.contains(origAttrib.getName().toLowerCase())) {
Enumeration enumer = origAttrib.getStringValues();
while (enumer.hasMoreElements()) {
String url = (String) enumer.nextElement();
String urlbase = url.substring(url.indexOf('/') + 3,url.indexOf('?'));
String nurl;
if (outbound) {
nurl = util.getRemoteMappedDN(new DN(urlbase), this.localBase, this.remoteBase).toString();
} else {
nurl = util.getLocalMappedDN(new DN(urlbase), this.remoteBase, this.localBase).toString();
}
nattrib.addValue("ldap:///" + nurl + url.substring(url.indexOf('?')));
}
} else {
Enumeration enumer = origAttrib.getByteValues();
while (enumer.hasMoreElements()) {
nattrib.addValue((byte[]) enumer.nextElement());
}
}
return nattrib;
}
private void mapFilter(FilterNode node) {
String name;
String newName;
NamingUtils util = new NamingUtils();
switch (node.getType()) {
case EQUALS :
if (this.dnAttribs.contains(node.getName().toLowerCase()) && node.getValue().toLowerCase().endsWith(this.localBaseDN)) {
node.setValue(util.getRemoteMappedDN(new DN(node.getValue()), this.localBase, this.remoteBase).toString());
}
break;
case SUBSTR :
case GREATER_THEN :
case LESS_THEN:
case PRESENCE :
break;
case AND:
case OR:
Iterator<FilterNode> it = node.getChildren().iterator();
while (it.hasNext()) {
mapFilter(it.next());
}
break;
case NOT : mapFilter(node.getNot());
}
}
public void shutdown() {
// TODO Auto-generated method stub
}
}
| 32.595611 | 136 | 0.744278 |
10d4b244a39bf3b06f7518e5a851ca93e4eb1ab5 | 3,268 | /*
* 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 catastro.logica.servicios;
import accesoDatos.AccesoDatos;
import catastro.logica.entidades.TipoLote;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
*
* @author Geovanny
*/
public class ServiciosTipoLote {
public static ArrayList<TipoLote> obtenerTiposLotes() throws Exception {
ArrayList<TipoLote> lst = new ArrayList<>();
AccesoDatos accesoDatos;
PreparedStatement prstm;
TipoLote tipoLote;
ResultSet resultSet;
String sql;
try {
accesoDatos = new AccesoDatos();
sql = "SELECT * from catastro.f_seleccionar_tipos_lote();";
resultSet = accesoDatos.ejecutaQuery(sql);
while (resultSet.next()) {
tipoLote = new TipoLote();
tipoLote.setIdTipoLote(resultSet.getInt("sr_id_tipo_lote"));
tipoLote.setNombre(resultSet.getString("chv_nombre"));
tipoLote.setCodigo(resultSet.getString("chv_codigo"));
tipoLote.setDescripcion(resultSet.getString("chv_descripcion"));
tipoLote.setEstadoLogico(resultSet.getString("ch_estado_logico"));
tipoLote.setFechaRegistro(resultSet.getTimestamp("ts_fecha_registro"));
tipoLote.setFechaActualizacion(resultSet.getTimestamp("ts_fecha_actualizacion"));
tipoLote.setFechaBaja(resultSet.getTimestamp("ts_fecha_baja"));
lst.add(tipoLote);
}
} catch (Exception e) {
throw e;
}
return lst;
}
public static TipoLote obtenerTipoLoteDadoCodigo(int codigo) throws Exception {
TipoLote tipoLote = null;
AccesoDatos accesoDatos;
String sql;
PreparedStatement prstm;
ResultSet resultSet;
try {
accesoDatos = new AccesoDatos();
sql = "SELECT * FROM catastro.f_seleccionar_tipo_lote_dado_codigo(?)";
prstm = accesoDatos.creaPreparedSmt(sql);
prstm.setInt(1, codigo);
resultSet = accesoDatos.ejecutaPrepared(prstm);
while (resultSet.next()) {
tipoLote = new TipoLote();
tipoLote.setIdTipoLote(resultSet.getInt("sr_id_tipo_lote"));
tipoLote.setNombre(resultSet.getString("chv_nombre"));
tipoLote.setCodigo(resultSet.getString("chv_codigo"));
tipoLote.setDescripcion(resultSet.getString("chv_descripcion"));
tipoLote.setEstadoLogico(resultSet.getString("ch_estado_logico"));
tipoLote.setFechaRegistro(resultSet.getTimestamp("ts_fecha_registro"));
tipoLote.setFechaActualizacion(resultSet.getTimestamp("ts_fecha_actualizacion"));
tipoLote.setFechaBaja(resultSet.getTimestamp("ts_fecha_baja"));
}
accesoDatos.desconectar();
} catch (Exception e) {
throw e;
}
return tipoLote;
}
}
| 40.345679 | 98 | 0.621175 |
55636af34528ebd6834952593636e858a91c4db1 | 1,946 | /*
* Copyright (C) 2007-2009 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jivesoftware.openfire.session;
import org.jivesoftware.openfire.StreamID;
import org.jivesoftware.openfire.session.*;
import org.xmpp.packet.JID;
/**
* Locator of sessions that know how to talk to Coherence cluster nodes.
*
* @author Gaston Dombiak
*/
public class RemoteSessionLocator implements org.jivesoftware.openfire.session.RemoteSessionLocator {
// TODO Keep a cache for a brief moment so we can reuse same instances (that use their own cache)
public ClientSession getClientSession(byte[] nodeID, JID address) {
return new RemoteClientSession(nodeID, address);
}
public ComponentSession getComponentSession(byte[] nodeID, JID address) {
return new RemoteComponentSession(nodeID, address);
}
public ConnectionMultiplexerSession getConnectionMultiplexerSession(byte[] nodeID, JID address) {
return new RemoteConnectionMultiplexerSession(nodeID, address);
}
public IncomingServerSession getIncomingServerSession(byte[] nodeID, StreamID streamID) {
return new RemoteIncomingServerSession(nodeID, streamID);
}
public OutgoingServerSession getOutgoingServerSession(byte[] nodeID, JID address) {
return new RemoteOutgoingServerSession(nodeID, address);
}
}
| 37.423077 | 102 | 0.732271 |
cf0fa1ff362a4d02f2589d44edcf9a36c657d47c | 11,618 | package cf.khanhsb.icare_v2.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.Objects;
import cf.khanhsb.icare_v2.Adapter.GymListViewAdapter;
import cf.khanhsb.icare_v2.List_Data_Activity;
import cf.khanhsb.icare_v2.Model.NonScrollListView;
import cf.khanhsb.icare_v2.R;
import cf.khanhsb.icare_v2.WorkoutHistoryActivity;
import static android.content.Context.MODE_PRIVATE;
public class GymFragment extends Fragment {
private FloatingActionButton viewButtonExercises;
private TextView workoutHeadline, workoutTitle,workoutTime,workoutRecommended,viewAll;
private Boolean gotPlan = false;
private ImageView clockIcon;
private FirebaseFirestore firestore;
private DocumentReference docRef;
private static final String tempEmail = "tempEmail";
private String workoutLabel,workoutDuration,workoutImage;
private LinearLayout timeLinear;
/**
* Gym listview
*/
private NonScrollListView listView,listView_intermediate,listView_advanced;
private String[] gymListTitle = {"Abs - Beginner",
"Chest - Beginner",
"Arm - Beginner",
"Leg - Beginner",
"Shoulder & Back - Beginner"};
private String[] gymListTitleIntermediate = {"Abs - Intermediate",
"Chest - Intermediate",
"Arm - Intermediate",
"Leg - Intermediate",
"Shoulder & Back - Intermediate"};
private String[] gymListTitleAdvanced = {"Abs - Advanced",
"Chest - Advanced",
"Arm - Advanced",
"Leg - Advanced",
"Shoulder & Back - Advanced"};
private String[] gymListTime = {"15 min", "6 min", "16 min", "21 min", "14 min"};
private String[] focusBodyPart = {"Abs","Chest","Arm","Leg","Shoulder & Back"};
private int[] gymListImage = {R.drawable.abs_workout_image,
R.drawable.chest_workout_image,
R.drawable.arm_workout_image,
R.drawable.leg_workout_image,
R.drawable.shoulder_workout_image};
/**
* Gym listview
*/
public GymFragment() {
// Required empty public constructor
}
public void callParentMethod(){
getActivity().onBackPressed();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gym, container, false);
viewButtonExercises = (FloatingActionButton) rootView.findViewById(R.id.fab_exercises);
workoutHeadline = (TextView) rootView.findViewById(R.id.workout_headline);
workoutTitle = (TextView) rootView.findViewById(R.id.workout_title);
clockIcon = (ImageView) rootView.findViewById(R.id.clockIcon);
workoutTime = rootView.findViewById(R.id.workout_time);
timeLinear = rootView.findViewById(R.id.time_linear);
workoutRecommended = rootView.findViewById(R.id.workout_recommended);
viewAll = rootView.findViewById(R.id.view_all_button);
SharedPreferences sharedPreferences = this.getActivity().
getSharedPreferences(tempEmail, MODE_PRIVATE);
String theTempEmail = sharedPreferences.getString("Email", "");
firestore = FirebaseFirestore.getInstance();
Runnable getRecentWorkoutRunnable = new Runnable() {
@Override
public void run() {
docRef = firestore.collection("workoutHistory").document(theTempEmail);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
workoutLabel = document.getString("workoutTitle");
if(workoutLabel != null){
workoutDuration = document.getString("workoutDuration");
workoutImage = document.getString("workoutImage");
workoutTitle.setText(workoutLabel);
workoutTime.setText(workoutDuration);
workoutHeadline.setText("Recent Workout");
timeLinear.setVisibility(View.VISIBLE);
workoutRecommended.setVisibility(View.INVISIBLE);
viewButtonExercises.setVisibility(View.VISIBLE);
viewButtonExercises.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), List_Data_Activity.class);
intent.putExtra("workoutTitle", workoutLabel);
intent.putExtra("workoutImage", Integer.parseInt(workoutImage));
intent.putExtra("workoutTime",workoutDuration);
String[] splitString = workoutLabel.split("-");
intent.putExtra("focusBodyPart",splitString[0].trim());
startActivity(intent);
requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.hold_position);
}
});
} else {
workoutHeadline.setText("No Recent Workout");
workoutTitle.setText("Let's workout and keep fit!");
viewButtonExercises.setVisibility(View.INVISIBLE);
timeLinear.setVisibility(View.GONE);
workoutRecommended.setVisibility(View.VISIBLE);
}
}
}
}
});
}
};
Thread getRecentWorkoutThread = new Thread(getRecentWorkoutRunnable);
getRecentWorkoutThread.start();
listView = (NonScrollListView) rootView.findViewById(R.id.classic_workout_listview);
GymListViewAdapter listViewAdapter = new GymListViewAdapter(getActivity(),
R.layout.item_workout_list,
gymListImage,
gymListTitle,
gymListTime);
listView.setAdapter(listViewAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), List_Data_Activity.class);
intent.putExtra("workoutTitle", gymListTitle[position]);
intent.putExtra("workoutImage", gymListImage[position]);
intent.putExtra("workoutTime",gymListTime[position]);
intent.putExtra("focusBodyPart",focusBodyPart[position]);
startActivity(intent);
requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.hold_position);
}
});
listView_intermediate = (NonScrollListView) rootView.findViewById(R.id.classic_workout_listview_intermediate);
GymListViewAdapter listViewAdapter_intermediate = new GymListViewAdapter(getActivity(),
R.layout.item_workout_list,
gymListImage,
gymListTitleIntermediate,
gymListTime);
listView_intermediate.setAdapter(listViewAdapter_intermediate);
listView_intermediate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), List_Data_Activity.class);
intent.putExtra("workoutTitle", gymListTitleIntermediate[position]);
intent.putExtra("workoutImage", gymListImage[position]);
intent.putExtra("workoutTime",gymListTime[position]);
intent.putExtra("focusBodyPart",focusBodyPart[position]);
startActivity(intent);
requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.hold_position);
}
});
listView_advanced = (NonScrollListView) rootView.findViewById(R.id.classic_workout_listview_advanced);
GymListViewAdapter listViewAdapter_advanced = new GymListViewAdapter(getActivity(),
R.layout.item_workout_list,
gymListImage,
gymListTitleAdvanced,
gymListTime);
listView_advanced.setAdapter(listViewAdapter_advanced);
listView_advanced.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), List_Data_Activity.class);
intent.putExtra("workoutTitle", gymListTitleAdvanced[position]);
intent.putExtra("workoutImage", gymListImage[position]);
intent.putExtra("workoutTime",gymListTime[position]);
intent.putExtra("focusBodyPart",focusBodyPart[position]);
startActivity(intent);
requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.hold_position);
}
});
clockIcon.setColorFilter(Color.WHITE);
viewButtonExercises.setColorFilter(getResources().getColor(R.color.lime_200));
viewButtonExercises.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gotPlan = true;
}
});
viewAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent toHistory = new Intent(getContext(), WorkoutHistoryActivity.class);
startActivity(toHistory);
requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.hold_position);
}
});
return rootView;
}
} | 47.227642 | 133 | 0.611809 |
ab9a19ac4c14236aea0566c0cdd20b84b1e44461 | 829 | package net.hotslicer.pancake.material;
import net.kyori.adventure.text.Component;
import net.minestom.server.item.Material;
import net.minestom.server.utils.NamespaceID;
/**
* @author Jenya705
*/
public interface PancakeMaterial {
static PancakeMaterial minestom(Material material) {
return new MinestomPancakeMaterial(material);
}
static PancakeMaterialBuilder builder() {
return new PancakeMaterialBuilder();
}
static PancakeMaterial of(NamespaceID namespace, int id, Material minestomMaterial, int maxAmount, Component customName) {
return new PancakeMaterialContainer(namespace, id, minestomMaterial, maxAmount, customName);
}
NamespaceID getNamespace();
int id();
Material getMinestomMaterial();
int getMaxAmount();
Component customName();
}
| 23.685714 | 126 | 0.735826 |
3751b8d5be1f8cffd0159fa6b5776f21ca34631d | 23,472 | /*
* 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 ttaiit.blogspot.com;
import javax.swing.JOptionPane;
/**
*
* @author shikha
*/
public class fork extends javax.swing.JFrame {
int arr[] = new int[2];
int a[]=new int[5];
int r[]=new int[7];
protected static int p=2; protected static int q=5;
protected static int s=7;
int flag=0;
/**
/**
* Creates new form fork
*/
public fork() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
L1 = new javax.swing.JLabel();
L2 = new javax.swing.JLabel();
L4 = new javax.swing.JLabel();
L5 = new javax.swing.JLabel();
L6 = new javax.swing.JLabel();
L7 = new javax.swing.JLabel();
L8 = new javax.swing.JLabel();
L9 = new javax.swing.JLabel();
L10 = new javax.swing.JLabel();
L12 = new javax.swing.JLabel();
L11 = new javax.swing.JLabel();
L13 = new javax.swing.JLabel();
L14 = new javax.swing.JLabel();
L15 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
L1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L1.setText("jLabel1");
L2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L2.setText("jLabel2");
L4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L4.setText("jLabel4");
L5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L5.setText("jLabel5");
L6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L6.setText("jLabel6");
L7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L7.setText("jLabel7");
L8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L8.setText("jLabel8");
L9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L9.setText("jLabel9");
L10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L10.setText("jLabel10");
L12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L12.setText("jLabel11");
L11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L11.setText("jLabel12");
L13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L13.setText("jLabel13");
L14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L14.setText("jLabel14");
L15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ttaiit/blogspot/com/imagess/iconfinder_fork_2693199.png"))); // NOI18N
L15.setText("jLabel15");
jButton1.setText("ROW 1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("ROW 2");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton2MouseClicked(evt);
}
});
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("ROW 3");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton3MouseClicked(evt);
}
});
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("PC MOVES");
jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton4MouseClicked(evt);
}
});
jButton5.setText("EXIT");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(486, 486, 486)
.addComponent(L2, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(L1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(366, 366, 366))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(L9, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(L10, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addComponent(L11, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(L12, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(22, 22, 22))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(L4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(L5, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(L6, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(L7, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(L13, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(L8, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(L14, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(46, 46, 46)
.addComponent(L15, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(104, 104, 104))
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(181, 181, 181)))
.addGap(86, 86, 86)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(363, 363, 363))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(L2, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(L1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(87, 87, 87)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(94, 94, 94)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(L7)
.addComponent(L8)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(58, 58, 58)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(L11)
.addComponent(L12, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(L13)
.addComponent(L14, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(L15)
.addComponent(L10)
.addComponent(L9, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(84, 84, 84)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(L4)
.addComponent(L5, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(L6))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton5)
.addGap(75, 75, 75))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(83, 83, 83))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if(flag==0){
flag=1;}
if(flag==1){
p--;
if(arr[0]==0){
L1.setVisible(false);
arr[0]=1;
}
else
{
L2.setVisible(false);
arr[1]=1;
}
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
if(flag==0){
flag=2;}
if(flag==2){
q--;
if(a[0]==0){
L4.setVisible(false);
a[0]=1;
}
else if(a[1]==0)
{
L5.setVisible(false);
a[1]=1;
}
else if(a[2]==0)
{
L6.setVisible(false);
a[2]=1;
}
else if(a[3]==0)
{
L7.setVisible(false);
a[3]=1;
}
else
{
L8.setVisible(false);
a[4]=1;
}}
}//GEN-LAST:event_jButton2MouseClicked
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
System.exit(0);
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
if(flag==0){
flag=3;}
if(flag==3){
s--;
if(r[0]==0)
{
L9.setVisible(false);
r[0]=1;
}
else if(r[1]==0)
{
L10.setVisible(false);
r[1]=1;
}
else if(r[2]==0)
{
L11.setVisible(false);
r[2]=1;
}
else if(r[3]==0)
{
L12.setVisible(false);
r[3]=1;
}
else if(r[4]==0)
{
L13.setVisible(false);
r[4]=1;
}
else if(r[5]==0)
{
L14.setVisible(false);
r[5]=1;
}
else
{
L15.setVisible(false);
r[6]=1;
}}
}//GEN-LAST:event_jButton3MouseClicked
private int[] nimsum(int p,int q,int s){
System.out.printf(""+ p+q+s);
int pos=0,nof=0;
int sum[][]=new int[3][3];
for(int i=0;i<3;i++){
if(i==0){
sum[i][0]=p/4;
sum[i][1]=(p%4)/2;
sum[i][2]=((p%4)%2)/1;
}
if(i==1){
sum[i][0]=q/4;
sum[i][1]=(q%4)/2;
sum[i][2]=((q%4)%2)/1;
}
if(i==2){
sum[i][0]=p/4;
sum[i][1]=(p%4)/2;
sum[i][2]=((p%4)%2)/1;
}
}
for(int i=0;i<3;i++){
int y=0;
for(int j=0;j<3;j++){
y=(y +sum[j][i]);
}
y=y%2;
if(y==1){
nof=i;
break;
}
}
for(int j=0; j<3; j++){
if(sum[j][nof]==1){
pos=j;
} }
if(nof==0){
nof=4;
}
if(nof==1){
nof=2;
}
if(nof==2){
nof=1;
}
// System.out.println(""+nof);
// System.out.println(""+pos);
int posnof[] = new int[]{nof, pos};
for(int i=0;i<2;i++)
System.out.println("" + posnof[i]);
return (posnof);
}
private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked
flag=0;
int[] copy= nimsum(p,q,s);
for(int i=0;i<2;i++){
System.out.println("" + copy[i]);
}
int n=0;
if(copy[1]==0){
if(arr[0]==0){
L1.setVisible(false);
arr[0]=1;
}
else
{
L2.setVisible(false);
arr[1]=1;
}
}
if(copy[1]==0){
if(copy[0]==4){
L14.setVisible(false);
JOptionPane.showMessageDialog(null,"As pc makes the last move pc wons!!!!");
}
}
if(copy[1]==1){
if(copy[0]==4){
q=q-4;
L4.setVisible(false);
a[0]=1;a[1]=1;
a[2]=2;a[3]=1;
L5.setVisible(false);
L6.setVisible(false);
L7.setVisible(false);
}
}
if(copy[1]==1){
if(copy[0]==1){
q=q-1;
L8.setVisible(false);
a[4]=1;
}
}
}
// if(a[0]==1){
// L9.setVisible(false);
// L10.setVisible(false);
// }
//if((arr[0]==1) && arr[1]==1){
// L15.setVisible(false);
/*}
if((a[1]==1) && (a[2]==1) && (a[3]==1) && (a[4]==1)){
L11.setVisible(false);
L12.setVisible(false);
L13.setVisible(false);
L14.setVisible(false);
JOptionPane.showMessageDialog(null,"As pc makes the last move pc wins!!!!");
}}
}//GEN-LAST:event_jButton4MouseClicked
*/
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(fork.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(fork.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(fork.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(fork.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new fork().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel L1;
private javax.swing.JLabel L10;
private javax.swing.JLabel L11;
private javax.swing.JLabel L12;
private javax.swing.JLabel L13;
private javax.swing.JLabel L14;
private javax.swing.JLabel L15;
private javax.swing.JLabel L2;
private javax.swing.JLabel L4;
private javax.swing.JLabel L5;
private javax.swing.JLabel L6;
private javax.swing.JLabel L7;
private javax.swing.JLabel L8;
private javax.swing.JLabel L9;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
// End of variables declaration//GEN-END:variables
}
| 42.521739 | 176 | 0.564886 |
42885f47f6064e66c476ae82ef01327495376a72 | 599 | package javarraria.inventory;
public class Inventory {
private String name = "";
private ItemStack[] slots;
public Inventory(String name,int slotsN) {
this.name = name;
this.slots = new ItemStack[slotsN];
}
public boolean isEmpty(int slot) {
return slots[slot] == null;
}
public int getCount(int slot) {
if (slots[slot].isEmpty()) return 0;
return slots[slot].getCount();
}
public void swap(int slot1,int slot2) {
ItemStack s1 = new ItemStack(slots[slot1]);
slots[slot1] = new ItemStack(slots[slot2]);
slots[slot2] = s1;
s1 = null;
}
}
| 23.038462 | 47 | 0.647746 |
2d246db297a1b973b579ecb408490f46dec93ba7 | 5,679 | /*
* 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.jackrabbit.oak.index.indexer.document.flatfile;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import com.google.common.base.Stopwatch;
import org.apache.commons.io.FileUtils;
import org.apache.jackrabbit.oak.index.indexer.document.LastModifiedRange;
import org.apache.jackrabbit.oak.index.indexer.document.NodeStateEntry;
import org.apache.jackrabbit.oak.index.indexer.document.NodeStateEntryTraverser;
import org.apache.jackrabbit.oak.index.indexer.document.NodeStateEntryTraverserFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.StandardSystemProperty.LINE_SEPARATOR;
import static org.apache.jackrabbit.oak.commons.IOUtils.humanReadableByteCount;
import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.FlatFileNodeStoreBuilder.OAK_INDEXER_MAX_SORT_MEMORY_IN_GB;
import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.FlatFileNodeStoreBuilder.OAK_INDEXER_MAX_SORT_MEMORY_IN_GB_DEFAULT;
import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.FlatFileStoreUtils.getSortedStoreFileName;
class StoreAndSortStrategy implements SortStrategy {
private static final String OAK_INDEXER_DELETE_ORIGINAL = "oak.indexer.deleteOriginal";
private static final int LINE_SEP_LENGTH = LINE_SEPARATOR.value().length();
private final Logger log = LoggerFactory.getLogger(getClass());
private final NodeStateEntryTraverserFactory nodeStatesFactory;
private final PathElementComparator comparator;
private final NodeStateEntryWriter entryWriter;
private final File storeDir;
private final boolean compressionEnabled;
private long entryCount;
private boolean deleteOriginal = Boolean.parseBoolean(System.getProperty(OAK_INDEXER_DELETE_ORIGINAL, "true"));
private int maxMemory = Integer.getInteger(OAK_INDEXER_MAX_SORT_MEMORY_IN_GB, OAK_INDEXER_MAX_SORT_MEMORY_IN_GB_DEFAULT);
private long textSize;
public StoreAndSortStrategy(NodeStateEntryTraverserFactory nodeStatesFactory, PathElementComparator comparator,
NodeStateEntryWriter entryWriter, File storeDir, boolean compressionEnabled) {
this.nodeStatesFactory = nodeStatesFactory;
this.comparator = comparator;
this.entryWriter = entryWriter;
this.storeDir = storeDir;
this.compressionEnabled = compressionEnabled;
}
@Override
public File createSortedStoreFile() throws IOException {
try (NodeStateEntryTraverser nodeStates = nodeStatesFactory.create(new LastModifiedRange(0,
Long.MAX_VALUE))) {
File storeFile = writeToStore(nodeStates, storeDir, getStoreFileName());
return sortStoreFile(storeFile);
}
}
@Override
public long getEntryCount() {
return entryCount;
}
private File sortStoreFile(File storeFile) throws IOException {
File sortWorkDir = new File(storeFile.getParent(), "sort-work-dir");
FileUtils.forceMkdir(sortWorkDir);
File sortedFile = new File(storeFile.getParentFile(), getSortedStoreFileName(compressionEnabled));
NodeStateEntrySorter sorter =
new NodeStateEntrySorter(comparator, storeFile, sortWorkDir, sortedFile);
logFlags();
sorter.setUseZip(compressionEnabled);
sorter.setMaxMemoryInGB(maxMemory);
sorter.setDeleteOriginal(deleteOriginal);
sorter.setActualFileSize(textSize);
sorter.sort();
return sorter.getSortedFile();
}
private File writeToStore(NodeStateEntryTraverser nodeStates, File dir, String fileName) throws IOException {
entryCount = 0;
File file = new File(dir, fileName);
Stopwatch sw = Stopwatch.createStarted();
try (BufferedWriter w = FlatFileStoreUtils.createWriter(file, compressionEnabled)) {
for (NodeStateEntry e : nodeStates) {
String line = entryWriter.toString(e);
w.append(line);
w.newLine();
textSize += line.length() + LINE_SEP_LENGTH;
entryCount++;
}
}
String sizeStr = compressionEnabled ? String.format("compressed/%s actual size", humanReadableByteCount(textSize)) : "";
log.info("Dumped {} nodestates in json format in {} ({} {})",entryCount, sw, humanReadableByteCount(file.length()), sizeStr);
return file;
}
private void logFlags() {
log.info("Delete original dump from traversal : {} ({})", deleteOriginal, OAK_INDEXER_DELETE_ORIGINAL);
log.info("Max heap memory (GB) to be used for merge sort : {} ({})", maxMemory, OAK_INDEXER_MAX_SORT_MEMORY_IN_GB);
}
private String getStoreFileName() {
return compressionEnabled ? "store.json.gz" : "store.json";
}
}
| 45.798387 | 139 | 0.735165 |
fb9ff81d6e5023ae51918d34c9ce24d497b31f1d | 910 | package com.five35.minecraft.greenthumb;
import java.util.Map;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.MCVersion;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.Name;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions;
@MCVersion("1.7.10")
@Name("GreenThumb")
@TransformerExclusions("com.five35.greenthumb.")
public class LoadingPlugin implements IFMLLoadingPlugin {
@Override
public String getAccessTransformerClass() {
return null;
}
@Override
public String[] getASMTransformerClass() {
return new String[] { "com.five35.minecraft.greenthumb.BonemealTransformer" };
}
@Override
public String getModContainerClass() {
return null;
}
@Override
public String getSetupClass() {
return null;
}
@Override
public void injectData(final Map<String, Object> data) {}
}
| 25.277778 | 81 | 0.791209 |
c6c868ccdcf3ccbf8d8efcd92503a4c496e8c6a8 | 706 | package com.easy.cloud.core.operator.sysfilterconfig.pojo.query;
import com.easy.cloud.core.basic.pojo.query.EcBaseQuery;
/**
* 描述:查询类
*
* @author THINK
* @date 2018-06-25 16:36:55
*/
public class SysFilterConfigQuery extends EcBaseQuery {
/**
* url的匹配模式
*/
private String urlPattern;
/**
* 过滤器的名称
*/
private String filterName;
public String getUrlPattern() {
return urlPattern;
}
public void setUrlPattern(String urlPattern) {
this.urlPattern = urlPattern;
}
public String getFilterName() {
return filterName;
}
public void setFilterName(String filterName) {
this.filterName = filterName;
}
}
| 19.081081 | 64 | 0.641643 |
a7debaba2e3b444b8daf097066ff3ee83bf7ec4d | 7,229 | package com.ruoyi.merchant.controller;
import java.util.Date;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.channel.domain.ChannelInfo;
import com.ruoyi.channel.domain.ChannelProductAuth;
import com.ruoyi.channel.service.IChannelInfoService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.merchant.domain.MerInfo;
import com.ruoyi.merchant.domain.MerProductAuth;
import com.ruoyi.merchant.service.IMerInfoService;
import com.ruoyi.merchant.service.IMerProductAuthService;
import com.ruoyi.product.domain.ProductInfo;
import com.ruoyi.product.service.IProductInfoService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
/**
* 商户产品授权Controller
*
* @author ruoyi
* @date 2021-05-05
*/
@Controller
@RequestMapping("/merchant/auth")
public class MerProductAuthController extends BaseController
{
private String prefix = "merchant/auth";
@Autowired
IProductInfoService productService;
@Autowired
private IChannelInfoService channelInfoService;
@Autowired
private IMerInfoService merInfoService;
@Autowired
private IMerProductAuthService merProductAuthService;
@RequiresPermissions("merchant:auth:view")
@GetMapping()
public String auth()
{
return prefix + "/auth";
}
/**
* 查询商户产品授权列表
*/
@RequiresPermissions("merchant:auth:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(MerProductAuth merProductAuth)
{
startPage();
List<MerProductAuth> list = merProductAuthService.selectMerProductAuthList(merProductAuth);
return getDataTable(list);
}
/**
* 导出商户产品授权列表
*/
@RequiresPermissions("merchant:auth:export")
@Log(title = "商户产品授权", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ResponseBody
public AjaxResult export(MerProductAuth merProductAuth)
{
List<MerProductAuth> list = merProductAuthService.selectMerProductAuthList(merProductAuth);
ExcelUtil<MerProductAuth> util = new ExcelUtil<MerProductAuth>(MerProductAuth.class);
return util.exportExcel(list, "商户产品授权数据");
}
/**
* 新增商户产品授权
*/
@GetMapping("/add")
public String add(ModelMap mmap)
{
ChannelInfo channelInfo=new ChannelInfo();
channelInfo.setStatus(1);
List<ChannelInfo> infoList = channelInfoService.selectChannelInfoList(channelInfo);
MerInfo merInfo=new MerInfo();
merInfo.setStatus(1);
List<MerInfo> merInfoList = merInfoService.selectMerInfoList(merInfo);
mmap.put("infoList", infoList);
mmap.put("merInfoList", merInfoList);
return prefix + "/add";
}
/**
* 新增保存商户产品授权
*/
@RequiresPermissions("merchant:auth:add")
@Log(title = "商户产品授权", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
@Transactional
public AjaxResult addSave(String productType,String productOne,String productTwo,Long channelId,Long merId,String rate)
{
ProductInfo productInfo =new ProductInfo();
ChannelInfo channelInfo = channelInfoService.selectChannelInfoById(channelId);
MerInfo merInfo = merInfoService.selectMerInfoById(merId);
if(!"".equals(productTwo)) {
productInfo.setCode(productTwo);
List<ProductInfo> infoListForFun = productService.selectProductInfoListForFun(productInfo);
for (ProductInfo productInfo3 : infoListForFun) {
MerProductAuth merProductAuth=new MerProductAuth();
merProductAuth.setMerId(merId);
merProductAuth.setChannelCode(channelInfo.getChannelCode());
merProductAuth.setChannelId(channelInfo.getId());
merProductAuth.setProductCode(productInfo3.getCode());
merProductAuth.setProductId(productInfo3.getId());
merProductAuth.setRate(rate);
merProductAuth.setRateType(1);
merProductAuthService.insertMerProductAuth(merProductAuth);
}
}else if(!"".equals(productOne)){
productInfo.setCode(productOne);
List<ProductInfo> infoListForFun = productService.selectProductInfoListForFun(productInfo);
for (ProductInfo productInfo3 : infoListForFun) {
MerProductAuth merProductAuth=new MerProductAuth();
merProductAuth.setMerId(merId);
merProductAuth.setChannelCode(channelInfo.getChannelCode());
merProductAuth.setChannelId(channelInfo.getId());
merProductAuth.setProductCode(productInfo3.getCode());
merProductAuth.setProductId(productInfo3.getId());
merProductAuth.setRate(rate);
merProductAuth.setRateType(1);
merProductAuthService.insertMerProductAuth(merProductAuth);
}
}else {
productInfo.setParentCode(productType);
List<ProductInfo> productInfoList = productService.selectProductInfoList(productInfo);
for (ProductInfo productInfo2 : productInfoList) {
List<ProductInfo> infoListForFun = productService.selectProductInfoListForFun(productInfo2);
for (ProductInfo productInfo3 : infoListForFun) {
MerProductAuth merProductAuth=new MerProductAuth();
merProductAuth.setMerId(merId);
merProductAuth.setChannelCode(channelInfo.getChannelCode());
merProductAuth.setChannelId(channelInfo.getId());
merProductAuth.setProductCode(productInfo3.getCode());
merProductAuth.setProductId(productInfo3.getId());
merProductAuth.setRate(rate);
merProductAuth.setRateType(1);
merProductAuthService.insertMerProductAuth(merProductAuth);
}
}
}
return toAjax(1);
}
/**
* 修改商户产品授权
*/
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") Long id, ModelMap mmap)
{
MerProductAuth merProductAuth = merProductAuthService.selectMerProductAuthById(id);
mmap.put("merProductAuth", merProductAuth);
return prefix + "/edit";
}
/**
* 修改保存商户产品授权
*/
@RequiresPermissions("merchant:auth:edit")
@Log(title = "商户产品授权", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(MerProductAuth merProductAuth)
{
return toAjax(merProductAuthService.updateMerProductAuth(merProductAuth));
}
/**
* 删除商户产品授权
*/
@RequiresPermissions("merchant:auth:remove")
@Log(title = "商户产品授权", businessType = BusinessType.DELETE)
@PostMapping( "/remove")
@ResponseBody
public AjaxResult remove(String ids)
{
return toAjax(merProductAuthService.deleteMerProductAuthByIds(ids));
}
}
| 35.787129 | 123 | 0.736478 |
0a17664e085697f68b778f2206cdb1e938ad9f01 | 1,874 | package patternMatching.fcpm;
import patternMatching.fcpm.preprocessing.Product;
import patternMatching.fcpm.table.APTableStatisticsFactory;
import patternMatching.fcpm.table.DebuggingAPTable;
import patternMatching.fcpm.table.IAPTable;
import patternMatching.fcpm.table.array.ArrayBasedTable;
import patternMatching.fcpm.table.builder.IPatternMatchingConfig;
import patternMatching.fcpm.table.concurrent.SynchronizedTableWrapper;
import patternMatching.fcpm.table.concurrent.hash.ConcurrentBuildInHashTableBasedTable;
public final class MultiThreadWithSharedTablePatternMatchingContextFactory implements IPatternMatchingContextFactory
{
private final IPatternMatchingConfig config;
public MultiThreadWithSharedTablePatternMatchingContextFactory(IPatternMatchingConfig config)
{
this.config = config;
}
@Override
public IPatternMatchingContext create(Product[] patternSlp, Product[] textSlp)
{
switch (config.getAPTableType())
{
case Array: {
IAPTable table = new SynchronizedTableWrapper(new ArrayBasedTable(patternSlp.length, textSlp.length));
if(config.withStatistics())
table = new DebuggingAPTable(table, new APTableStatisticsFactory());
return new PatternMatchingContext(table, patternSlp, textSlp);
}
case OwnHashTable:
throw new RuntimeException();
case BuildInHashTable: {
IAPTable table = new ConcurrentBuildInHashTableBasedTable(patternSlp.length, textSlp.length);
if(config.withStatistics())
throw new RuntimeException();
return new PatternMatchingContext(table, patternSlp, textSlp);
}
}
throw new IllegalArgumentException();
}
}
| 42.590909 | 119 | 0.702775 |
0c8c3c32d0e182ce15189a06720bc99eaa78cb6a | 4,010 | package com.apollographql.apollo.sample.feed;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import com.apollographql.apollo.ApolloCall;
import com.apollographql.apollo.ApolloCallback;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.exception.ApolloException;
import com.apollographql.apollo.fetcher.ApolloResponseFetchers;
import com.apollographql.apollo.sample.FeedQuery;
import com.apollographql.apollo.sample.GitHuntApplication;
import com.apollographql.apollo.sample.R;
import com.apollographql.apollo.sample.detail.GitHuntEntryDetailActivity;
import com.apollographql.apollo.sample.type.FeedType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jetbrains.annotations.NotNull;
import static com.apollographql.apollo.sample.FeedQuery.FeedEntry;
public class GitHuntFeedActivity extends AppCompatActivity implements GitHuntNavigator {
static final String TAG = GitHuntFeedActivity.class.getSimpleName();
private static final int FEED_SIZE = 20;
GitHuntApplication application;
ViewGroup content;
ProgressBar progressBar;
GitHuntFeedRecyclerViewAdapter feedAdapter;
Handler uiHandler = new Handler(Looper.getMainLooper());
ApolloCall<FeedQuery.Data> githuntFeedCall;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_githunt_feed);
application = (GitHuntApplication) getApplication();
content = (ViewGroup) findViewById(R.id.content_holder);
progressBar = (ProgressBar) findViewById(R.id.loading_bar);
RecyclerView feedRecyclerView = (RecyclerView) findViewById(R.id.rv_feed_list);
feedAdapter = new GitHuntFeedRecyclerViewAdapter(this);
feedRecyclerView.setAdapter(feedAdapter);
feedRecyclerView.setLayoutManager(new LinearLayoutManager(this));
fetchFeed();
}
private ApolloCall.Callback<FeedQuery.Data> dataCallback
= new ApolloCallback<>(new ApolloCall.Callback<FeedQuery.Data>() {
@Override public void onResponse(@NotNull Response<FeedQuery.Data> response) {
feedAdapter.setFeed(feedResponseToEntriesWithRepositories(response));
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
}
@Override public void onFailure(@NotNull ApolloException e) {
Log.e(TAG, e.getMessage(), e);
}
}, uiHandler);
List<FeedEntry> feedResponseToEntriesWithRepositories(Response<FeedQuery.Data> response) {
List<FeedEntry> feedEntriesWithRepos = new ArrayList<>();
final FeedQuery.Data responseData = response.data();
if (responseData == null) {
return Collections.emptyList();
}
final List<FeedEntry> feedEntries = responseData.feedEntries();
if (feedEntries == null) {
return Collections.emptyList();
}
for (FeedEntry entry : feedEntries) {
if (entry.repository() != null) {
feedEntriesWithRepos.add(entry);
}
}
return feedEntriesWithRepos;
}
private void fetchFeed() {
final FeedQuery feedQuery = FeedQuery.builder()
.limit(FEED_SIZE)
.type(FeedType.HOT)
.build();
githuntFeedCall = application.apolloClient()
.query(feedQuery)
.responseFetcher(ApolloResponseFetchers.NETWORK_FIRST);
githuntFeedCall.enqueue(dataCallback);
}
@Override public void startGitHuntActivity(String repoFullName) {
final Intent intent = GitHuntEntryDetailActivity.newIntent(this, repoFullName);
startActivity(intent);
}
@Override protected void onDestroy() {
super.onDestroy();
if (githuntFeedCall != null) {
githuntFeedCall.cancel();
}
}
}
| 33.697479 | 92 | 0.763342 |
721abf603346dc38be455da48453ec36d3bca716 | 206 | package sudoku.constants;
public class Messages {
public static final String GAME_COMPLETE = "Congratulations, you habe won!";
public static final String ERROR = "An error has occured.";
}
| 25.75 | 81 | 0.713592 |
2bdf48e70240b2986c4d62b5ece5f3aeb538fe4d | 3,784 | package org.test.webcam.controller.view;
import java.io.Serializable;
import java.security.Principal;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.test.webcam.controller.data.types.JsonOutput;
import org.test.webcam.controller.data.types.ScrollableSettings;
import org.test.webcam.model.domain.entity.view.UserRolesView;
import org.test.webcam.model.service.view.UserRolesViewService;
import org.test.webcam.util.SObjectListner;
@Controller
public class UserRolesViewController implements Serializable {
private static final long serialVersionUID = -4165513685393461L;
@Autowired
private UserRolesViewService userrolesviewService;
@Autowired
private SObjectListner sObjectListner;
private Boolean debug = false;
@Cacheable(value = "userrolesview_id", key = "T(java.util.Objects).hash(#root.methodName, #id, #principal, #settings)")
@RequestMapping(value = "/data/userrolesview/{id}", method = RequestMethod.GET)
@PreAuthorize(value = "hasRole('ROLE_USER')")
public @ResponseBody Map<String, Object> viewById(
@PathVariable String id, ScrollableSettings settings,
Principal principal) throws Exception {
UserRolesView userrolesview = null;
try {
settings.setSasUser(JsonOutput.readSasUser(principal));
try {
Integer idRaw = new Integer(id);
settings.setId(idRaw);
} catch (NumberFormatException e) {
settings.setId(id);
e.printStackTrace();
}
userrolesview = sObjectListner.viewById(settings.getSasUser(), userrolesviewService.findById(settings));
} catch (Exception e) {
e.printStackTrace();
return JsonOutput.mapError("Error while retrieving userrolesview from database: "
+ e.getLocalizedMessage());
}
if (userrolesview == null) {
return JsonOutput.mapError("Error, Cant find data for " + id);
} else {
return JsonOutput.mapSingle(userrolesview);
}
}
@Cacheable(value = "userrolesview", key = "T(java.util.Objects).hash(#root.methodName, #principal, #settings)")
@RequestMapping(value = "/data/userrolesview", method = RequestMethod.GET)
@PreAuthorize(value = "hasRole('ROLE_USER')")
public @ResponseBody Map<String, Object> view(
ScrollableSettings settings, Principal principal) throws Exception {
try {
settings.setSasUser(JsonOutput.readSasUser(principal));
return JsonOutput.map(sObjectListner.view(settings.getSasUser(), userrolesviewService.findAll(settings)));
} catch (Exception e) {
e.printStackTrace();
return JsonOutput.mapError("Error while retrieving userrolesview from database: "
+ e.getLocalizedMessage());
}
}
@Cacheable(value = "userrolesview_scrollable", key = "T(java.util.Objects).hash(#root.methodName, #principal, #settings)")
@RequestMapping(value = "/data/userrolesview/scrollable", method = RequestMethod.GET)
@PreAuthorize(value = "hasRole('ROLE_USER')")
public @ResponseBody Map<String, Object> viewScrollable(
ScrollableSettings settings, Principal principal) throws Exception {
try {
settings.setSasUser(JsonOutput.readSasUser(principal));
return JsonOutput.map(sObjectListner.viewScrollable(settings.getSasUser(), userrolesviewService.findAllScrollable(settings)));
} catch (Exception e) {
e.printStackTrace();
return JsonOutput.mapError("Error while retrieving userrolesview from database: "
+ e.getLocalizedMessage());
}
}
}
| 39.010309 | 129 | 0.772463 |
2e6e834600def75ec7c43a3c32cf79fa505ba051 | 11,693 | /*
* Copyright 2013-2016 Brian Thomas Matthews
*
* 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.btmatthews.maven.plugins.ldap;
import com.unboundid.ldap.sdk.*;
import com.unboundid.ldif.LDIFChangeRecord;
import com.unboundid.ldif.LDIFException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
/**
* Unit test the format handler API.
*
* @author <a href="mailto:[email protected]">Brian Matthews</a>
* @since 1.2.0
*/
public final class TestFormatHandler {
/**
* Mock for the connection to the LDAP directory server.
*/
@Mock
private LDAPInterface connection;
/**
* Mock for the input stream from which directory entries are read.
*/
@Mock
private InputStream inputStream;
/**
* Mock for the output stream to which directory entries are written.
*/
@Mock
private OutputStream outputStream;
/**
* Mock for the object that reads LDAP directory entries from an input stream.
*/
@Mock
private FormatReader reader;
/**
* Mock for the object that writes LDAP directory entries to an output stream.
*/
@Mock
private FormatWriter writer;
/**
* Mock for the object used to log information and error messages.
*/
@Mock
private FormatLogger logger;
/**
* The main test fixture is which extends {@link AbstractFormatHandler}.
*/
private FormatHandler handler;
/**
* Prepare for test case execution by creating the mock objects and test fixtures.
*/
@Before
public void setUp() {
initMocks(this);
handler = new AbstractFormatHandler() {
@Override
protected FormatWriter createWriter(final OutputStream outputStream,
final FormatLogger logger) {
return writer;
}
@Override
protected FormatReader openReader(final InputStream inputStream,
final FormatLogger logger) {
return reader;
}
};
}
/**
* Verify that the exception is logged and the reader is closed when an {@link LDIFException} happens while reading from
* the underlying input stream.
*
* @throws Exception If there was an unexpected problem executing the test case.
*/
@Test
public void handleLDIFExceptionWhileReading() throws Exception {
doThrow(LDIFException.class).when(reader).nextRecord();
handler.load(connection, inputStream, false, logger);
verify(reader).nextRecord();
verify(logger).logError(eq("Error parsing directory entry read from the input stream"), any(LDIFException.class));
verify(reader).close();
verifyNoMoreInteractions(reader, connection, inputStream, logger);
}
/**
* Verify that the exception is logged and the reader is closed when an {@link IOException} happens while reading from
* the underlying input stream.
*
* @throws Exception If there was an unexpected problem executing the test case.
*/
@Test
public void handleIOExceptionWhileReading() throws Exception {
doThrow(IOException.class).when(reader).nextRecord();
handler.load(connection, inputStream, false, logger);
verify(reader).nextRecord();
verify(logger).logError(eq("I/O error reading directory entry from input stream"), any(IOException.class));
verify(reader).close();
verifyNoMoreInteractions(reader, connection, inputStream, logger);
}
/**
* Verify that the exception is logged when an {@link IOException} happens while closing the underlying
* input stream.
*
* @throws Exception If there was an unexpected problem executing the test case.
*/
@Test
public void handleIOExceptionWhileClosing() throws Exception {
doThrow(IOException.class).when(reader).close();
handler.load(connection, inputStream, false, logger);
verify(reader).nextRecord();
verify(logger).logError(eq("I/O error closing the input stream reader"), any(IOException.class));
verify(reader).close();
verifyNoMoreInteractions(reader, connection, inputStream, logger);
}
/**
* Verify that the exception is logged and the reader is closed when a {@link LDAPException} happens while
* processing the record read from the underlying input stream.
*
* @throws Exception If there was an unexpected problem executing the test case.
*/
@Test
public void handleLDAPExceptionWhileProcessing() throws Exception {
final LDIFChangeRecord first = mock(LDIFChangeRecord.class);
when(reader.nextRecord()).thenReturn(first);
doThrow(LDAPException.class).when(first).processChange(same(connection), eq(true));
handler.load(connection, inputStream, false, logger);
verify(reader).nextRecord();
verify(first).processChange(same(connection), eq(true));
verify(logger).logError(eq("Error loading directory entry into the LDAP directory server"), any(LDAPException.class));
verify(reader).close();
verifyNoMoreInteractions(reader, connection, inputStream, logger);
}
/**
* Verify the behaviour of
* {@link FormatHandler#load(com.unboundid.ldap.sdk.LDAPInterface, java.io.InputStream, boolean, FormatLogger)}
* when the input stream is empty.
*
* @throws Exception If there was an unexpected error executing the test case.
*/
@Test
public void loadEmptyFile() throws Exception {
handler.load(connection, inputStream, true, logger);
verify(reader).nextRecord();
verify(reader).close();
verifyNoMoreInteractions(reader, connection, inputStream, logger);
}
/**
* Verify the behaviour of
* {@link FormatHandler#load(com.unboundid.ldap.sdk.LDAPInterface, java.io.InputStream, boolean, FormatLogger)}
* when the input stream is empty has only one record.
*
* @throws Exception If there was an unexpected error executing the test case.
*/
@Test
public void loadFileWithOneItem() throws Exception {
final LDIFChangeRecord first = mock(LDIFChangeRecord.class);
when(reader.nextRecord()).thenReturn(first, null);
handler.load(connection, inputStream, true, logger);
verify(reader, times(2)).nextRecord();
verify(first).processChange(same(connection), eq(true));
verify(reader).close();
verifyNoMoreInteractions(reader, connection, inputStream, logger);
}
/**
* Verify the behaviour of
* {@link FormatHandler#load(com.unboundid.ldap.sdk.LDAPInterface, java.io.InputStream, boolean, FormatLogger)}
* when the input stream is empty has two records.
*
* @throws Exception If there was an unexpected error executing the test case.
*/
@Test
public void loadFileWithTwoItems() throws Exception {
final LDIFChangeRecord first = mock(LDIFChangeRecord.class);
final LDIFChangeRecord second = mock(LDIFChangeRecord.class);
when(reader.nextRecord()).thenReturn(first, second, null);
handler.load(connection, inputStream, true, logger);
verify(reader, times(3)).nextRecord();
verify(first).processChange(same(connection), eq(true));
verify(second).processChange(same(connection), eq(true));
verify(reader).close();
verifyNoMoreInteractions(reader, connection, inputStream, logger);
}
/**
* Verify the correct behaviour of
* {@link FormatHandler#dump(com.unboundid.ldap.sdk.LDAPInterface, String, String, java.io.OutputStream, FormatLogger)}
* when the result set is empty.
*
* @throws Exception If there was an exception executing the test.
*/
@Test
public void dumpEmptyResultSet() throws Exception {
final SearchResult result = FormatTestUtils.createSearchResult();
when(connection.search(any(SearchRequest.class))).thenReturn(result);
handler.dump(connection, "dc=btmatthews,dc=com", "(objectclass=*)", outputStream, logger);
verify(connection).search(any(SearchRequest.class));
verify(writer).close();
verifyNoMoreInteractions(writer, connection, outputStream, logger);
}
/**
* Verify the correct behaviour of
* {@link FormatHandler#dump(com.unboundid.ldap.sdk.LDAPInterface, String, String, java.io.OutputStream, FormatLogger)}
* when the result set contains only one entry.
*
* @throws Exception If there was an exception executing the test.
*/
@Test
public void dumpResultSetWithOneItem() throws Exception {
final SearchResultEntry first = FormatTestUtils.createSearchResultEntry(
"ou=People,dc=btmatthews,dc=com",
"ou", "People",
"objectclass", "organisationalUnit");
final SearchResult result = FormatTestUtils.createSearchResult(first);
when(connection.search(any(SearchRequest.class))).thenReturn(result);
handler.dump(connection, "dc=btmatthews,dc=com", "(objectclass=*)", outputStream, logger);
verify(connection).search(any(SearchRequest.class));
verify(writer).printEntry(same(first));
verify(writer).close();
verifyNoMoreInteractions(writer, connection, outputStream, logger);
}
/**
* Verify the correct behaviour of
* {@link FormatHandler#dump(com.unboundid.ldap.sdk.LDAPInterface, String, String, java.io.OutputStream, FormatLogger)}
* when the result set contains two entries.
*
* @throws Exception If there was an exception executing the test.
*/
@Test
public void dumpResultSetWithTwoItems() throws Exception {
final SearchResultEntry first = FormatTestUtils.createSearchResultEntry(
"ou=People,dc=btmatthews,dc=com",
"ou", "People",
"objectclass", "organisationalUnit");
final SearchResultEntry second = FormatTestUtils.createSearchResultEntry(
"cn=Bart Simpson,ou=People,dc=btmatthews,dc=com",
"cn", "Bart Simpson",
"sn", "Simpson",
"givenName", "Bart",
"uid", "bsimpson",
"objectclass", "inetOrgPerson");
final SearchResult result = FormatTestUtils.createSearchResult(first, second);
when(connection.search(any(SearchRequest.class))).thenReturn(result);
handler.dump(connection, "dc=btmatthews,dc=com", "(objectclass=*)", outputStream, logger);
verify(connection).search(any(SearchRequest.class));
verify(writer).printEntry(same(first));
verify(writer).printEntry(same(second));
verify(writer).close();
verifyNoMoreInteractions(writer, connection, outputStream, logger);
}
}
| 40.600694 | 126 | 0.671684 |
85444c2d690964c7afbd20eb47dc225123b7bc29 | 1,308 | package com.overlord.mathematics.iterative;
import java.util.Arrays;
/*
* @Description:
*
* @author MischaGeng
* @Created Date: 2020/03/30
* @Since JDK 1.8
* @Title: BinarySearch
* @ProjectName overlord
*
* @Modified by:
* @Modified date:
* @Problem no:
*/
public class BinarySearch {
public static void main(String[] args) {
String[] dictionary = {"i", "am", "one", "of", "the", "authors", "in", "geekbang"};
Arrays.sort(dictionary);
String wordToFind = "ok";
boolean found = BinarySearch.search(dictionary, wordToFind);
if (found) {
System.out.println(String.format("找到了单词%s", wordToFind));
} else {
System.out.println(String.format("未能找到单词%s", wordToFind));
}
}
private static boolean search(String[] dic, String str) {
int min = 0;
int max = dic.length - 1;
while (true) {
int middle = (min + max) / 2;
if (str.equals(dic[middle])) {
return Boolean.TRUE;
}
if (str.compareTo(dic[middle]) < 0) {
max = middle - 1;
} else {
min = middle + 1;
}
if (max < min) {
return Boolean.FALSE;
}
}
}
}
| 21.096774 | 91 | 0.511468 |
22caaaebac4e1b0c6f917746c4aca80a590802ef | 4,468 | package com.yunbao.video.dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.yunbao.common.adapter.RefreshAdapter;
import com.yunbao.common.custom.CommonRefreshView;
import com.yunbao.common.http.HttpCallback;
import com.yunbao.video.R;
import com.yunbao.video.adapter.MusicAdapter;
import com.yunbao.video.bean.MusicBean;
import com.yunbao.video.http.VideoHttpConsts;
import com.yunbao.video.http.VideoHttpUtil;
import com.yunbao.video.interfaces.VideoMusicActionListener;
import java.util.Arrays;
import java.util.List;
/**
* Created by cxf on 2018/12/7.
*/
public class VideoMusicClassDialog extends PopupWindow implements View.OnClickListener {
private Context mContext;
private View mParent;
private String mTitle;
private String mClassId;
private CommonRefreshView mRefreshView;
private MusicAdapter mAdapter;
private VideoMusicActionListener mActionListener;
public VideoMusicClassDialog(Context context, View parent, String title, String classId, VideoMusicActionListener actionListener) {
mContext = context;
mParent = parent;
mTitle = title;
mClassId = classId;
mActionListener = actionListener;
setContentView(initView());
setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
setBackgroundDrawable(new ColorDrawable());
setOutsideTouchable(true);
setClippingEnabled(false);
setFocusable(true);
setAnimationStyle(R.style.leftToRightAnim);
setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
VideoHttpUtil.cancel(VideoHttpConsts.GET_MUSIC_LIST);
if (mAdapter != null) {
mAdapter.setActionListener(null);
}
if (mActionListener != null) {
mActionListener.onStopMusic();
}
mActionListener = null;
}
});
}
private View initView() {
View v = LayoutInflater.from(mContext).inflate(R.layout.view_video_music_class, null);
TextView title = v.findViewById(R.id.title);
if (!TextUtils.isEmpty(mTitle)) {
title.setText(mTitle);
}
mRefreshView = v.findViewById(R.id.refreshView);
mRefreshView.setEmptyLayoutId(R.layout.view_no_data_music_class);
mRefreshView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
mRefreshView.setDataHelper(new CommonRefreshView.DataHelper<MusicBean>() {
@Override
public RefreshAdapter<MusicBean> getAdapter() {
if (mAdapter == null) {
mAdapter = new MusicAdapter(mContext);
mAdapter.setActionListener(mActionListener);
}
return mAdapter;
}
@Override
public void loadData(int p, HttpCallback callback) {
if (!TextUtils.isEmpty(mClassId)) {
VideoHttpUtil.getMusicList(mClassId, p, callback);
}
}
@Override
public List<MusicBean> processData(String[] info) {
return JSON.parseArray(Arrays.toString(info), MusicBean.class);
}
@Override
public void onRefreshSuccess(List<MusicBean> list, int listCount) {
}
@Override
public void onRefreshFailure() {
}
@Override
public void onLoadMoreSuccess(List<MusicBean> loadItemList, int loadItemCount) {
}
@Override
public void onLoadMoreFailure() {
}
});
v.findViewById(R.id.btn_close).setOnClickListener(this);
return v;
}
public void show() {
showAtLocation(mParent, Gravity.BOTTOM, 0, 0);
if (mRefreshView != null) {
mRefreshView.initData();
}
}
@Override
public void onClick(View v) {
dismiss();
}
}
| 31.687943 | 135 | 0.640107 |
65abd180644ebd4487cc0ce66d54cd70ae148ccd | 486 | package com.lgwork.sys.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import com.lgwork.domain.po.FileStoragePO;
/**
*
* 文件储存
*
* @author irays
*
*/
public interface FileStorageDAO extends JpaRepository<FileStoragePO, Long>, JpaSpecificationExecutor<FileStoragePO> {
/**
* 根据code获取文件
* @param fileCode
* @return
*/
FileStoragePO findByFileCode(String fileCode);
}
| 17.357143 | 117 | 0.751029 |
c2c3c25799773bfa4e920295d1d8e5658daba945 | 54,078 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.itextpdf.text.pdf.codec;
import com.itextpdf.text.error_messages.MessageLocalization;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
public class JBIG2SegmentReader
{
public static class JBIG2Page
{
public void addSegment(JBIG2Segment jbig2segment)
{
segs.put(((Object) (Integer.valueOf(jbig2segment.segmentNumber))), ((Object) (jbig2segment)));
// 0 0:aload_0
// 1 1:getfield #26 <Field SortedMap segs>
// 2 4:aload_1
// 3 5:getfield #42 <Field int JBIG2SegmentReader$JBIG2Segment.segmentNumber>
// 4 8:invokestatic #48 <Method Integer Integer.valueOf(int)>
// 5 11:aload_1
// 6 12:invokeinterface #54 <Method Object SortedMap.put(Object, Object)>
// 7 17:pop
// 8 18:return
}
public byte[] getData(boolean flag)
throws IOException
{
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
// 0 0:new #60 <Class ByteArrayOutputStream>
// 1 3:dup
// 2 4:invokespecial #61 <Method void ByteArrayOutputStream()>
// 3 7:astore_2
Iterator iterator = segs.keySet().iterator();
// 4 8:aload_0
// 5 9:getfield #26 <Field SortedMap segs>
// 6 12:invokeinterface #65 <Method Set SortedMap.keySet()>
// 7 17:invokeinterface #71 <Method Iterator Set.iterator()>
// 8 22:astore_3
do
{
if(!iterator.hasNext())
break;
// 9 23:aload_3
// 10 24:invokeinterface #77 <Method boolean Iterator.hasNext()>
// 11 29:ifeq 189
Object obj = ((Object) ((Integer)iterator.next()));
// 12 32:aload_3
// 13 33:invokeinterface #81 <Method Object Iterator.next()>
// 14 38:checkcast #44 <Class Integer>
// 15 41:astore 4
obj = ((Object) ((JBIG2Segment)segs.get(obj)));
// 16 43:aload_0
// 17 44:getfield #26 <Field SortedMap segs>
// 18 47:aload 4
// 19 49:invokeinterface #85 <Method Object SortedMap.get(Object)>
// 20 54:checkcast #39 <Class JBIG2SegmentReader$JBIG2Segment>
// 21 57:astore 4
if(!flag || ((JBIG2Segment) (obj)).type != 51 && ((JBIG2Segment) (obj)).type != 49)
//* 22 59:iload_1
//* 23 60:ifeq 83
//* 24 63:aload 4
//* 25 65:getfield #88 <Field int JBIG2SegmentReader$JBIG2Segment.type>
//* 26 68:bipush 51
//* 27 70:icmpeq 23
//* 28 73:aload 4
//* 29 75:getfield #88 <Field int JBIG2SegmentReader$JBIG2Segment.type>
//* 30 78:bipush 49
//* 31 80:icmpeq 23
{
if(flag)
//* 32 83:iload_1
//* 33 84:ifeq 177
{
byte abyte0[] = JBIG2SegmentReader.copyByteArray(((JBIG2Segment) (obj)).headerData);
// 34 87:aload 4
// 35 89:getfield #92 <Field byte[] JBIG2SegmentReader$JBIG2Segment.headerData>
// 36 92:invokestatic #96 <Method byte[] JBIG2SegmentReader.copyByteArray(byte[])>
// 37 95:astore 5
if(((JBIG2Segment) (obj)).page_association_size)
//* 38 97:aload 4
//* 39 99:getfield #100 <Field boolean JBIG2SegmentReader$JBIG2Segment.page_association_size>
//* 40 102:ifeq 165
{
abyte0[((JBIG2Segment) (obj)).page_association_offset] = 0;
// 41 105:aload 5
// 42 107:aload 4
// 43 109:getfield #103 <Field int JBIG2SegmentReader$JBIG2Segment.page_association_offset>
// 44 112:iconst_0
// 45 113:bastore
abyte0[((JBIG2Segment) (obj)).page_association_offset + 1] = 0;
// 46 114:aload 5
// 47 116:aload 4
// 48 118:getfield #103 <Field int JBIG2SegmentReader$JBIG2Segment.page_association_offset>
// 49 121:iconst_1
// 50 122:iadd
// 51 123:iconst_0
// 52 124:bastore
abyte0[((JBIG2Segment) (obj)).page_association_offset + 2] = 0;
// 53 125:aload 5
// 54 127:aload 4
// 55 129:getfield #103 <Field int JBIG2SegmentReader$JBIG2Segment.page_association_offset>
// 56 132:iconst_2
// 57 133:iadd
// 58 134:iconst_0
// 59 135:bastore
abyte0[((JBIG2Segment) (obj)).page_association_offset + 3] = 1;
// 60 136:aload 5
// 61 138:aload 4
// 62 140:getfield #103 <Field int JBIG2SegmentReader$JBIG2Segment.page_association_offset>
// 63 143:iconst_3
// 64 144:iadd
// 65 145:iconst_1
// 66 146:bastore
} else
//* 67 147:aload_2
//* 68 148:aload 5
//* 69 150:invokevirtual #107 <Method void ByteArrayOutputStream.write(byte[])>
//* 70 153:aload_2
//* 71 154:aload 4
//* 72 156:getfield #110 <Field byte[] JBIG2SegmentReader$JBIG2Segment.data>
//* 73 159:invokevirtual #107 <Method void ByteArrayOutputStream.write(byte[])>
//* 74 162:goto 23
{
abyte0[((JBIG2Segment) (obj)).page_association_offset] = 1;
// 75 165:aload 5
// 76 167:aload 4
// 77 169:getfield #103 <Field int JBIG2SegmentReader$JBIG2Segment.page_association_offset>
// 78 172:iconst_1
// 79 173:bastore
}
bytearrayoutputstream.write(abyte0);
} else
//* 80 174:goto 147
{
bytearrayoutputstream.write(((JBIG2Segment) (obj)).headerData);
// 81 177:aload_2
// 82 178:aload 4
// 83 180:getfield #92 <Field byte[] JBIG2SegmentReader$JBIG2Segment.headerData>
// 84 183:invokevirtual #107 <Method void ByteArrayOutputStream.write(byte[])>
}
bytearrayoutputstream.write(((JBIG2Segment) (obj)).data);
}
} while(true);
// 85 186:goto 153
bytearrayoutputstream.close();
// 86 189:aload_2
// 87 190:invokevirtual #113 <Method void ByteArrayOutputStream.close()>
return bytearrayoutputstream.toByteArray();
// 88 193:aload_2
// 89 194:invokevirtual #117 <Method byte[] ByteArrayOutputStream.toByteArray()>
// 90 197:areturn
}
public final int page;
public int pageBitmapHeight;
public int pageBitmapWidth;
private final SortedMap segs = new TreeMap();
private final JBIG2SegmentReader sr;
public JBIG2Page(int i, JBIG2SegmentReader jbig2segmentreader)
{
// 0 0:aload_0
// 1 1:invokespecial #21 <Method void Object()>
// 2 4:aload_0
// 3 5:new #23 <Class TreeMap>
// 4 8:dup
// 5 9:invokespecial #24 <Method void TreeMap()>
// 6 12:putfield #26 <Field SortedMap segs>
pageBitmapWidth = -1;
// 7 15:aload_0
// 8 16:iconst_m1
// 9 17:putfield #28 <Field int pageBitmapWidth>
pageBitmapHeight = -1;
// 10 20:aload_0
// 11 21:iconst_m1
// 12 22:putfield #30 <Field int pageBitmapHeight>
page = i;
// 13 25:aload_0
// 14 26:iload_1
// 15 27:putfield #32 <Field int page>
sr = jbig2segmentreader;
// 16 30:aload_0
// 17 31:aload_2
// 18 32:putfield #34 <Field JBIG2SegmentReader sr>
// 19 35:return
}
}
public static class JBIG2Segment
implements Comparable
{
public int compareTo(JBIG2Segment jbig2segment)
{
return segmentNumber - jbig2segment.segmentNumber;
// 0 0:aload_0
// 1 1:getfield #59 <Field int segmentNumber>
// 2 4:aload_1
// 3 5:getfield #59 <Field int segmentNumber>
// 4 8:isub
// 5 9:ireturn
}
public volatile int compareTo(Object obj)
{
return compareTo((JBIG2Segment)obj);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:checkcast #2 <Class JBIG2SegmentReader$JBIG2Segment>
// 3 5:invokevirtual #65 <Method int compareTo(JBIG2SegmentReader$JBIG2Segment)>
// 4 8:ireturn
}
public int countOfReferredToSegments;
public byte data[];
public long dataLength;
public boolean deferredNonRetain;
public byte headerData[];
public int page;
public int page_association_offset;
public boolean page_association_size;
public int referredToSegmentNumbers[];
public final int segmentNumber;
public boolean segmentRetentionFlags[];
public int type;
public JBIG2Segment(int i)
{
// 0 0:aload_0
// 1 1:invokespecial #33 <Method void Object()>
dataLength = -1L;
// 2 4:aload_0
// 3 5:ldc2w #34 <Long -1L>
// 4 8:putfield #37 <Field long dataLength>
page = -1;
// 5 11:aload_0
// 6 12:iconst_m1
// 7 13:putfield #39 <Field int page>
referredToSegmentNumbers = null;
// 8 16:aload_0
// 9 17:aconst_null
// 10 18:putfield #41 <Field int[] referredToSegmentNumbers>
segmentRetentionFlags = null;
// 11 21:aload_0
// 12 22:aconst_null
// 13 23:putfield #43 <Field boolean[] segmentRetentionFlags>
type = -1;
// 14 26:aload_0
// 15 27:iconst_m1
// 16 28:putfield #45 <Field int type>
deferredNonRetain = false;
// 17 31:aload_0
// 18 32:iconst_0
// 19 33:putfield #47 <Field boolean deferredNonRetain>
countOfReferredToSegments = -1;
// 20 36:aload_0
// 21 37:iconst_m1
// 22 38:putfield #49 <Field int countOfReferredToSegments>
data = null;
// 23 41:aload_0
// 24 42:aconst_null
// 25 43:putfield #51 <Field byte[] data>
headerData = null;
// 26 46:aload_0
// 27 47:aconst_null
// 28 48:putfield #53 <Field byte[] headerData>
page_association_size = false;
// 29 51:aload_0
// 30 52:iconst_0
// 31 53:putfield #55 <Field boolean page_association_size>
page_association_offset = -1;
// 32 56:aload_0
// 33 57:iconst_m1
// 34 58:putfield #57 <Field int page_association_offset>
segmentNumber = i;
// 35 61:aload_0
// 36 62:iload_1
// 37 63:putfield #59 <Field int segmentNumber>
// 38 66:return
}
}
public JBIG2SegmentReader(RandomAccessFileOrArray randomaccessfileorarray)
throws IOException
{
// 0 0:aload_0
// 1 1:invokespecial #75 <Method void Object()>
// 2 4:aload_0
// 3 5:new #77 <Class TreeMap>
// 4 8:dup
// 5 9:invokespecial #78 <Method void TreeMap()>
// 6 12:putfield #80 <Field SortedMap segments>
// 7 15:aload_0
// 8 16:new #77 <Class TreeMap>
// 9 19:dup
// 10 20:invokespecial #78 <Method void TreeMap()>
// 11 23:putfield #82 <Field SortedMap pages>
// 12 26:aload_0
// 13 27:new #84 <Class TreeSet>
// 14 30:dup
// 15 31:invokespecial #85 <Method void TreeSet()>
// 16 34:putfield #87 <Field SortedSet globals>
number_of_pages = -1;
// 17 37:aload_0
// 18 38:iconst_m1
// 19 39:putfield #89 <Field int number_of_pages>
read = false;
// 20 42:aload_0
// 21 43:iconst_0
// 22 44:putfield #91 <Field boolean read>
ra = randomaccessfileorarray;
// 23 47:aload_0
// 24 48:aload_1
// 25 49:putfield #93 <Field RandomAccessFileOrArray ra>
// 26 52:return
}
public static byte[] copyByteArray(byte abyte0[])
{
byte abyte1[] = new byte[abyte0.length];
// 0 0:aload_0
// 1 1:arraylength
// 2 2:newarray byte[]
// 3 4:astore_1
System.arraycopy(((Object) (abyte0)), 0, ((Object) (abyte1)), 0, abyte0.length);
// 4 5:aload_0
// 5 6:iconst_0
// 6 7:aload_1
// 7 8:iconst_0
// 8 9:aload_0
// 9 10:arraylength
// 10 11:invokestatic #103 <Method void System.arraycopy(Object, int, Object, int, int)>
return abyte1;
// 11 14:aload_1
// 12 15:areturn
}
public byte[] getGlobal(boolean flag)
{
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
// 0 0:new #107 <Class ByteArrayOutputStream>
// 1 3:dup
// 2 4:invokespecial #108 <Method void ByteArrayOutputStream()>
// 3 7:astore_2
Iterator iterator = globals.iterator();
// 4 8:aload_0
// 5 9:getfield #87 <Field SortedSet globals>
// 6 12:invokeinterface #114 <Method Iterator SortedSet.iterator()>
// 7 17:astore_3
_L3:
JBIG2Segment jbig2segment;
if(!iterator.hasNext())
break MISSING_BLOCK_LABEL_97;
// 8 18:aload_3
// 9 19:invokeinterface #120 <Method boolean Iterator.hasNext()>
// 10 24:ifeq 97
jbig2segment = (JBIG2Segment)iterator.next();
// 11 27:aload_3
// 12 28:invokeinterface #124 <Method Object Iterator.next()>
// 13 33:checkcast #9 <Class JBIG2SegmentReader$JBIG2Segment>
// 14 36:astore 4
if(!flag) goto _L2; else goto _L1
// 15 38:iload_1
// 16 39:ifeq 62
_L1:
if(jbig2segment.type == 51 || jbig2segment.type == 49) goto _L3; else goto _L2
// 17 42:aload 4
// 18 44:getfield #127 <Field int JBIG2SegmentReader$JBIG2Segment.type>
// 19 47:bipush 51
// 20 49:icmpeq 18
// 21 52:aload 4
// 22 54:getfield #127 <Field int JBIG2SegmentReader$JBIG2Segment.type>
// 23 57:bipush 49
// 24 59:icmpeq 18
_L2:
IOException ioexception;
bytearrayoutputstream.write(jbig2segment.headerData);
// 25 62:aload_2
// 26 63:aload 4
// 27 65:getfield #131 <Field byte[] JBIG2SegmentReader$JBIG2Segment.headerData>
// 28 68:invokevirtual #135 <Method void ByteArrayOutputStream.write(byte[])>
bytearrayoutputstream.write(jbig2segment.data);
// 29 71:aload_2
// 30 72:aload 4
// 31 74:getfield #138 <Field byte[] JBIG2SegmentReader$JBIG2Segment.data>
// 32 77:invokevirtual #135 <Method void ByteArrayOutputStream.write(byte[])>
goto _L3
//* 33 80:goto 18
//* 34 83:astore_3
//* 35 84:aload_3
//* 36 85:invokevirtual #141 <Method void IOException.printStackTrace()>
//* 37 88:aload_2
//* 38 89:invokevirtual #145 <Method int ByteArrayOutputStream.size()>
//* 39 92:ifgt 104
//* 40 95:aconst_null
//* 41 96:areturn
try
{
bytearrayoutputstream.close();
// 42 97:aload_2
// 43 98:invokevirtual #148 <Method void ByteArrayOutputStream.close()>
}
// Misplaced declaration of an exception variable
catch(IOException ioexception)
{
ioexception.printStackTrace();
}
if(bytearrayoutputstream.size() <= 0)
return null;
else
//* 44 101:goto 88
return bytearrayoutputstream.toByteArray();
// 45 104:aload_2
// 46 105:invokevirtual #152 <Method byte[] ByteArrayOutputStream.toByteArray()>
// 47 108:areturn
}
public JBIG2Page getPage(int i)
{
return (JBIG2Page)pages.get(((Object) (Integer.valueOf(i))));
// 0 0:aload_0
// 1 1:getfield #82 <Field SortedMap pages>
// 2 4:iload_1
// 3 5:invokestatic #160 <Method Integer Integer.valueOf(int)>
// 4 8:invokeinterface #166 <Method Object SortedMap.get(Object)>
// 5 13:checkcast #6 <Class JBIG2SegmentReader$JBIG2Page>
// 6 16:areturn
}
public int getPageHeight(int i)
{
return ((JBIG2Page)pages.get(((Object) (Integer.valueOf(i))))).pageBitmapHeight;
// 0 0:aload_0
// 1 1:getfield #82 <Field SortedMap pages>
// 2 4:iload_1
// 3 5:invokestatic #160 <Method Integer Integer.valueOf(int)>
// 4 8:invokeinterface #166 <Method Object SortedMap.get(Object)>
// 5 13:checkcast #6 <Class JBIG2SegmentReader$JBIG2Page>
// 6 16:getfield #171 <Field int JBIG2SegmentReader$JBIG2Page.pageBitmapHeight>
// 7 19:ireturn
}
public int getPageWidth(int i)
{
return ((JBIG2Page)pages.get(((Object) (Integer.valueOf(i))))).pageBitmapWidth;
// 0 0:aload_0
// 1 1:getfield #82 <Field SortedMap pages>
// 2 4:iload_1
// 3 5:invokestatic #160 <Method Integer Integer.valueOf(int)>
// 4 8:invokeinterface #166 <Method Object SortedMap.get(Object)>
// 5 13:checkcast #6 <Class JBIG2SegmentReader$JBIG2Page>
// 6 16:getfield #175 <Field int JBIG2SegmentReader$JBIG2Page.pageBitmapWidth>
// 7 19:ireturn
}
public int numberOfPages()
{
return pages.size();
// 0 0:aload_0
// 1 1:getfield #82 <Field SortedMap pages>
// 2 4:invokeinterface #177 <Method int SortedMap.size()>
// 3 9:ireturn
}
public void read()
throws IOException
{
if(read)
//* 0 0:aload_0
//* 1 1:getfield #91 <Field boolean read>
//* 2 4:ifeq 24
throw new IllegalStateException(MessageLocalization.getComposedMessage("already.attempted.a.read.on.this.jbig2.file", new Object[0]));
// 3 7:new #179 <Class IllegalStateException>
// 4 10:dup
// 5 11:ldc1 #181 <String "already.attempted.a.read.on.this.jbig2.file">
// 6 13:iconst_0
// 7 14:anewarray Object[]
// 8 17:invokestatic #187 <Method String MessageLocalization.getComposedMessage(String, Object[])>
// 9 20:invokespecial #190 <Method void IllegalStateException(String)>
// 10 23:athrow
read = true;
// 11 24:aload_0
// 12 25:iconst_1
// 13 26:putfield #91 <Field boolean read>
readFileHeader();
// 14 29:aload_0
// 15 30:invokevirtual #193 <Method void readFileHeader()>
if(sequential)
//* 16 33:aload_0
//* 17 34:getfield #195 <Field boolean sequential>
//* 18 37:ifeq 87
{
do
{
JBIG2Segment jbig2segment = readHeader();
// 19 40:aload_0
// 20 41:invokevirtual #199 <Method JBIG2SegmentReader$JBIG2Segment readHeader()>
// 21 44:astore_1
readSegment(jbig2segment);
// 22 45:aload_0
// 23 46:aload_1
// 24 47:invokevirtual #203 <Method void readSegment(JBIG2SegmentReader$JBIG2Segment)>
segments.put(((Object) (Integer.valueOf(jbig2segment.segmentNumber))), ((Object) (jbig2segment)));
// 25 50:aload_0
// 26 51:getfield #80 <Field SortedMap segments>
// 27 54:aload_1
// 28 55:getfield #206 <Field int JBIG2SegmentReader$JBIG2Segment.segmentNumber>
// 29 58:invokestatic #160 <Method Integer Integer.valueOf(int)>
// 30 61:aload_1
// 31 62:invokeinterface #210 <Method Object SortedMap.put(Object, Object)>
// 32 67:pop
} while(ra.getFilePointer() < ra.length());
// 33 68:aload_0
// 34 69:getfield #93 <Field RandomAccessFileOrArray ra>
// 35 72:invokevirtual #216 <Method long RandomAccessFileOrArray.getFilePointer()>
// 36 75:aload_0
// 37 76:getfield #93 <Field RandomAccessFileOrArray ra>
// 38 79:invokevirtual #219 <Method long RandomAccessFileOrArray.length()>
// 39 82:lcmp
// 40 83:iflt 40
} else
//* 41 86:return
{
Object obj;
do
{
obj = ((Object) (readHeader()));
// 42 87:aload_0
// 43 88:invokevirtual #199 <Method JBIG2SegmentReader$JBIG2Segment readHeader()>
// 44 91:astore_1
segments.put(((Object) (Integer.valueOf(((JBIG2Segment) (obj)).segmentNumber))), obj);
// 45 92:aload_0
// 46 93:getfield #80 <Field SortedMap segments>
// 47 96:aload_1
// 48 97:getfield #206 <Field int JBIG2SegmentReader$JBIG2Segment.segmentNumber>
// 49 100:invokestatic #160 <Method Integer Integer.valueOf(int)>
// 50 103:aload_1
// 51 104:invokeinterface #210 <Method Object SortedMap.put(Object, Object)>
// 52 109:pop
} while(((JBIG2Segment) (obj)).type != 51);
// 53 110:aload_1
// 54 111:getfield #127 <Field int JBIG2SegmentReader$JBIG2Segment.type>
// 55 114:bipush 51
// 56 116:icmpne 87
obj = ((Object) (segments.keySet().iterator()));
// 57 119:aload_0
// 58 120:getfield #80 <Field SortedMap segments>
// 59 123:invokeinterface #223 <Method Set SortedMap.keySet()>
// 60 128:invokeinterface #226 <Method Iterator Set.iterator()>
// 61 133:astore_1
while(((Iterator) (obj)).hasNext())
//* 62 134:aload_1
//* 63 135:invokeinterface #120 <Method boolean Iterator.hasNext()>
//* 64 140:ifeq 86
readSegment((JBIG2Segment)segments.get(((Iterator) (obj)).next()));
// 65 143:aload_0
// 66 144:aload_0
// 67 145:getfield #80 <Field SortedMap segments>
// 68 148:aload_1
// 69 149:invokeinterface #124 <Method Object Iterator.next()>
// 70 154:invokeinterface #166 <Method Object SortedMap.get(Object)>
// 71 159:checkcast #9 <Class JBIG2SegmentReader$JBIG2Segment>
// 72 162:invokevirtual #203 <Method void readSegment(JBIG2SegmentReader$JBIG2Segment)>
}
//* 73 165:goto 134
}
void readFileHeader()
throws IOException
{
boolean flag1 = true;
// 0 0:iconst_1
// 1 1:istore_3
ra.seek(0L);
// 2 2:aload_0
// 3 3:getfield #93 <Field RandomAccessFileOrArray ra>
// 4 6:lconst_0
// 5 7:invokevirtual #230 <Method void RandomAccessFileOrArray.seek(long)>
byte abyte0[] = new byte[8];
// 6 10:bipush 8
// 7 12:newarray byte[]
// 8 14:astore 4
ra.read(abyte0);
// 9 16:aload_0
// 10 17:getfield #93 <Field RandomAccessFileOrArray ra>
// 11 20:aload 4
// 12 22:invokevirtual #233 <Method int RandomAccessFileOrArray.read(byte[])>
// 13 25:pop
for(int i = 0; i < abyte0.length; i++)
//* 14 26:iconst_0
//* 15 27:istore_1
//* 16 28:iload_1
//* 17 29:aload 4
//* 18 31:arraylength
//* 19 32:icmpge 111
if(abyte0[i] != (new byte[] {
-105, 74, 66, 50, 13, 10, 26, 10
})[i])
//* 20 35:aload 4
//* 21 37:iload_1
//* 22 38:baload
//* 23 39:bipush 8
//* 24 41:newarray byte[]
//* 25 43:dup
//* 26 44:iconst_0
//* 27 45:ldc1 #234 <Int -105>
//* 28 47:bastore
//* 29 48:dup
//* 30 49:iconst_1
//* 31 50:ldc1 #235 <Int 74>
//* 32 52:bastore
//* 33 53:dup
//* 34 54:iconst_2
//* 35 55:ldc1 #236 <Int 66>
//* 36 57:bastore
//* 37 58:dup
//* 38 59:iconst_3
//* 39 60:ldc1 #17 <Int 50>
//* 40 62:bastore
//* 41 63:dup
//* 42 64:iconst_4
//* 43 65:ldc1 #237 <Int 13>
//* 44 67:bastore
//* 45 68:dup
//* 46 69:iconst_5
//* 47 70:ldc1 #238 <Int 10>
//* 48 72:bastore
//* 49 73:dup
//* 50 74:bipush 6
//* 51 76:ldc1 #239 <Int 26>
//* 52 78:bastore
//* 53 79:dup
//* 54 80:bipush 7
//* 55 82:ldc1 #238 <Int 10>
//* 56 84:bastore
//* 57 85:iload_1
//* 58 86:baload
//* 59 87:icmpeq 104
throw new IllegalStateException(MessageLocalization.getComposedMessage("file.header.idstring.not.good.at.byte.1", i));
// 60 90:new #179 <Class IllegalStateException>
// 61 93:dup
// 62 94:ldc1 #241 <String "file.header.idstring.not.good.at.byte.1">
// 63 96:iload_1
// 64 97:invokestatic #244 <Method String MessageLocalization.getComposedMessage(String, int)>
// 65 100:invokespecial #190 <Method void IllegalStateException(String)>
// 66 103:athrow
// 67 104:iload_1
// 68 105:iconst_1
// 69 106:iadd
// 70 107:istore_1
//* 71 108:goto 28
int j = ra.read();
// 72 111:aload_0
// 73 112:getfield #93 <Field RandomAccessFileOrArray ra>
// 74 115:invokevirtual #246 <Method int RandomAccessFileOrArray.read()>
// 75 118:istore_1
boolean flag;
if((j & 1) == 1)
//* 76 119:iload_1
//* 77 120:iconst_1
//* 78 121:iand
//* 79 122:iconst_1
//* 80 123:icmpne 171
flag = true;
// 81 126:iconst_1
// 82 127:istore_2
else
//* 83 128:aload_0
//* 84 129:iload_2
//* 85 130:putfield #195 <Field boolean sequential>
//* 86 133:iload_1
//* 87 134:iconst_2
//* 88 135:iand
//* 89 136:ifne 176
//* 90 139:iload_3
//* 91 140:istore_2
//* 92 141:aload_0
//* 93 142:iload_2
//* 94 143:putfield #248 <Field boolean number_of_pages_known>
//* 95 146:iload_1
//* 96 147:sipush 252
//* 97 150:iand
//* 98 151:ifeq 181
//* 99 154:new #179 <Class IllegalStateException>
//* 100 157:dup
//* 101 158:ldc1 #250 <String "file.header.flags.bits.2.7.not.0">
//* 102 160:iconst_0
//* 103 161:anewarray Object[]
//* 104 164:invokestatic #187 <Method String MessageLocalization.getComposedMessage(String, Object[])>
//* 105 167:invokespecial #190 <Method void IllegalStateException(String)>
//* 106 170:athrow
flag = false;
// 107 171:iconst_0
// 108 172:istore_2
sequential = flag;
if((j & 2) == 0)
flag = flag1;
else
//* 109 173:goto 128
flag = false;
// 110 176:iconst_0
// 111 177:istore_2
number_of_pages_known = flag;
if((j & 0xfc) != 0)
throw new IllegalStateException(MessageLocalization.getComposedMessage("file.header.flags.bits.2.7.not.0", new Object[0]));
//* 112 178:goto 141
if(number_of_pages_known)
//* 113 181:aload_0
//* 114 182:getfield #248 <Field boolean number_of_pages_known>
//* 115 185:ifeq 199
number_of_pages = ra.readInt();
// 116 188:aload_0
// 117 189:aload_0
// 118 190:getfield #93 <Field RandomAccessFileOrArray ra>
// 119 193:invokevirtual #253 <Method int RandomAccessFileOrArray.readInt()>
// 120 196:putfield #89 <Field int number_of_pages>
// 121 199:return
}
JBIG2Segment readHeader()
throws IOException
{
int i;
int k;
int i1;
int j1;
int k1;
int l1;
boolean flag;
int ai[];
JBIG2Segment jbig2segment;
k1 = (int)ra.getFilePointer();
// 0 0:aload_0
// 1 1:getfield #93 <Field RandomAccessFileOrArray ra>
// 2 4:invokevirtual #216 <Method long RandomAccessFileOrArray.getFilePointer()>
// 3 7:l2i
// 4 8:istore 5
l1 = ra.readInt();
// 5 10:aload_0
// 6 11:getfield #93 <Field RandomAccessFileOrArray ra>
// 7 14:invokevirtual #253 <Method int RandomAccessFileOrArray.readInt()>
// 8 17:istore 6
jbig2segment = new JBIG2Segment(l1);
// 9 19:new #9 <Class JBIG2SegmentReader$JBIG2Segment>
// 10 22:dup
// 11 23:iload 6
// 12 25:invokespecial #256 <Method void JBIG2SegmentReader$JBIG2Segment(int)>
// 13 28:astore 11
i = ra.read();
// 14 30:aload_0
// 15 31:getfield #93 <Field RandomAccessFileOrArray ra>
// 16 34:invokevirtual #246 <Method int RandomAccessFileOrArray.read()>
// 17 37:istore_1
if((i & 0x80) == 128)
//* 18 38:iload_1
//* 19 39:sipush 128
//* 20 42:iand
//* 21 43:sipush 128
//* 22 46:icmpne 256
flag = true;
// 23 49:iconst_1
// 24 50:istore 7
else
//* 25 52:aload 11
//* 26 54:iload 7
//* 27 56:putfield #259 <Field boolean JBIG2SegmentReader$JBIG2Segment.deferredNonRetain>
//* 28 59:iload_1
//* 29 60:bipush 64
//* 30 62:iand
//* 31 63:bipush 64
//* 32 65:icmpne 262
//* 33 68:iconst_1
//* 34 69:istore 7
//* 35 71:aload 11
//* 36 73:iload_1
//* 37 74:bipush 63
//* 38 76:iand
//* 39 77:putfield #127 <Field int JBIG2SegmentReader$JBIG2Segment.type>
//* 40 80:aload_0
//* 41 81:getfield #93 <Field RandomAccessFileOrArray ra>
//* 42 84:invokevirtual #246 <Method int RandomAccessFileOrArray.read()>
//* 43 87:istore 4
//* 44 89:iload 4
//* 45 91:sipush 224
//* 46 94:iand
//* 47 95:iconst_5
//* 48 96:ishr
//* 49 97:istore_3
//* 50 98:aconst_null
//* 51 99:astore 9
//* 52 101:iload_3
//* 53 102:bipush 7
//* 54 104:icmpne 274
//* 55 107:aload_0
//* 56 108:getfield #93 <Field RandomAccessFileOrArray ra>
//* 57 111:aload_0
//* 58 112:getfield #93 <Field RandomAccessFileOrArray ra>
//* 59 115:invokevirtual #216 <Method long RandomAccessFileOrArray.getFilePointer()>
//* 60 118:lconst_1
//* 61 119:lsub
//* 62 120:invokevirtual #230 <Method void RandomAccessFileOrArray.seek(long)>
//* 63 123:aload_0
//* 64 124:getfield #93 <Field RandomAccessFileOrArray ra>
//* 65 127:invokevirtual #253 <Method int RandomAccessFileOrArray.readInt()>
//* 66 130:ldc2 #260 <Int 0x1fffffff>
//* 67 133:iand
//* 68 134:istore_3
//* 69 135:iload_3
//* 70 136:iconst_1
//* 71 137:iadd
//* 72 138:newarray boolean[]
//* 73 140:astore 9
//* 74 142:iconst_0
//* 75 143:istore_1
//* 76 144:iconst_0
//* 77 145:istore_2
//* 78 146:iload_1
//* 79 147:bipush 8
//* 80 149:irem
//* 81 150:istore 4
//* 82 152:iload 4
//* 83 154:ifne 165
//* 84 157:aload_0
//* 85 158:getfield #93 <Field RandomAccessFileOrArray ra>
//* 86 161:invokevirtual #246 <Method int RandomAccessFileOrArray.read()>
//* 87 164:istore_2
//* 88 165:iconst_1
//* 89 166:iload 4
//* 90 168:ishl
//* 91 169:iload_2
//* 92 170:iand
//* 93 171:iload 4
//* 94 173:ishr
//* 95 174:iconst_1
//* 96 175:icmpne 268
//* 97 178:iconst_1
//* 98 179:istore 8
//* 99 181:aload 9
//* 100 183:iload_1
//* 101 184:iload 8
//* 102 186:bastore
//* 103 187:iload_1
//* 104 188:iconst_1
//* 105 189:iadd
//* 106 190:istore 4
//* 107 192:iload 4
//* 108 194:istore_1
//* 109 195:iload 4
//* 110 197:iload_3
//* 111 198:icmple 146
//* 112 201:iload_3
//* 113 202:istore_1
//* 114 203:aload 11
//* 115 205:aload 9
//* 116 207:putfield #264 <Field boolean[] JBIG2SegmentReader$JBIG2Segment.segmentRetentionFlags>
//* 117 210:aload 11
//* 118 212:iload_1
//* 119 213:putfield #267 <Field int JBIG2SegmentReader$JBIG2Segment.countOfReferredToSegments>
//* 120 216:iload_1
//* 121 217:iconst_1
//* 122 218:iadd
//* 123 219:newarray int[]
//* 124 221:astore 9
//* 125 223:iconst_1
//* 126 224:istore_2
//* 127 225:iload_2
//* 128 226:iload_1
//* 129 227:icmpgt 420
//* 130 230:iload 6
//* 131 232:sipush 256
//* 132 235:icmpgt 383
//* 133 238:aload 9
//* 134 240:iload_2
//* 135 241:aload_0
//* 136 242:getfield #93 <Field RandomAccessFileOrArray ra>
//* 137 245:invokevirtual #246 <Method int RandomAccessFileOrArray.read()>
//* 138 248:iastore
//* 139 249:iload_2
//* 140 250:iconst_1
//* 141 251:iadd
//* 142 252:istore_2
//* 143 253:goto 225
flag = false;
// 144 256:iconst_0
// 145 257:istore 7
jbig2segment.deferredNonRetain = flag;
if((i & 0x40) == 64)
flag = true;
else
//* 146 259:goto 52
flag = false;
// 147 262:iconst_0
// 148 263:istore 7
jbig2segment.type = i & 0x3f;
j1 = ra.read();
i1 = (j1 & 0xe0) >> 5;
ai = null;
if(i1 != 7) goto _L2; else goto _L1
_L1:
ra.seek(ra.getFilePointer() - 1L);
i1 = ra.readInt() & 0x1fffffff;
ai = ((int []) (new boolean[i1 + 1]));
i = 0;
k = 0;
do
{
j1 = i % 8;
if(j1 == 0)
k = ra.read();
boolean flag1;
if((1 << j1 & k) >> j1 == 1)
flag1 = true;
else
//* 149 265:goto 71
flag1 = false;
// 150 268:iconst_0
// 151 269:istore 8
ai[i] = flag1;
j1 = i + 1;
i = j1;
} while(j1 <= i1);
i = i1;
_L4:
jbig2segment.segmentRetentionFlags = ((boolean []) (ai));
jbig2segment.countOfReferredToSegments = i;
ai = new int[i + 1];
k = 1;
while(k <= i)
{
boolean flag2;
boolean aflag[];
if(l1 <= 256)
ai[k] = ra.read();
else
//* 152 271:goto 181
//* 153 274:iload_3
//* 154 275:iconst_4
//* 155 276:icmpgt 336
//* 156 279:iload_3
//* 157 280:iconst_1
//* 158 281:iadd
//* 159 282:newarray boolean[]
//* 160 284:astore 10
//* 161 286:iconst_0
//* 162 287:istore_2
//* 163 288:iload_3
//* 164 289:istore_1
//* 165 290:aload 10
//* 166 292:astore 9
//* 167 294:iload_2
//* 168 295:iload_3
//* 169 296:icmpgt 203
//* 170 299:iconst_1
//* 171 300:iload_2
//* 172 301:ishl
//* 173 302:iload 4
//* 174 304:bipush 31
//* 175 306:iand
//* 176 307:iand
//* 177 308:iload_2
//* 178 309:ishr
//* 179 310:iconst_1
//* 180 311:icmpne 330
//* 181 314:iconst_1
//* 182 315:istore 8
//* 183 317:aload 10
//* 184 319:iload_2
//* 185 320:iload 8
//* 186 322:bastore
//* 187 323:iload_2
//* 188 324:iconst_1
//* 189 325:iadd
//* 190 326:istore_2
//* 191 327:goto 288
//* 192 330:iconst_0
//* 193 331:istore 8
//* 194 333:goto 317
//* 195 336:iload_3
//* 196 337:iconst_5
//* 197 338:icmpeq 349
//* 198 341:iload_3
//* 199 342:istore_1
//* 200 343:iload_3
//* 201 344:bipush 6
//* 202 346:icmpne 203
//* 203 349:new #179 <Class IllegalStateException>
//* 204 352:dup
//* 205 353:ldc2 #269 <String "count.of.referred.to.segments.had.bad.value.in.header.for.segment.1.starting.at.2">
//* 206 356:iconst_2
//* 207 357:anewarray Object[]
//* 208 360:dup
//* 209 361:iconst_0
//* 210 362:iload 6
//* 211 364:invokestatic #274 <Method String String.valueOf(int)>
//* 212 367:aastore
//* 213 368:dup
//* 214 369:iconst_1
//* 215 370:iload 5
//* 216 372:invokestatic #274 <Method String String.valueOf(int)>
//* 217 375:aastore
//* 218 376:invokestatic #187 <Method String MessageLocalization.getComposedMessage(String, Object[])>
//* 219 379:invokespecial #190 <Method void IllegalStateException(String)>
//* 220 382:athrow
if(l1 <= 0x10000)
//* 221 383:iload 6
//* 222 385:ldc2 #275 <Int 0x10000>
//* 223 388:icmpgt 405
ai[k] = ra.readUnsignedShort();
// 224 391:aload 9
// 225 393:iload_2
// 226 394:aload_0
// 227 395:getfield #93 <Field RandomAccessFileOrArray ra>
// 228 398:invokevirtual #278 <Method int RandomAccessFileOrArray.readUnsignedShort()>
// 229 401:iastore
else
//* 230 402:goto 249
ai[k] = (int)ra.readUnsignedInt();
// 231 405:aload 9
// 232 407:iload_2
// 233 408:aload_0
// 234 409:getfield #93 <Field RandomAccessFileOrArray ra>
// 235 412:invokevirtual #281 <Method long RandomAccessFileOrArray.readUnsignedInt()>
// 236 415:l2i
// 237 416:iastore
k++;
}
break MISSING_BLOCK_LABEL_420;
// 238 417:goto 249
_L2:
if(i1 > 4)
break MISSING_BLOCK_LABEL_336;
aflag = new boolean[i1 + 1];
k = 0;
_L5:
i = i1;
ai = ((int []) (aflag));
if(k > i1) goto _L4; else goto _L3
_L3:
if((1 << k & (j1 & 0x1f)) >> k == 1)
flag2 = true;
else
flag2 = false;
aflag[k] = flag2;
k++;
goto _L5
if(i1 == 5)
break; /* Loop/switch isn't completed */
i = i1;
if(i1 != 6) goto _L4; else goto _L6
_L6:
throw new IllegalStateException(MessageLocalization.getComposedMessage("count.of.referred.to.segments.had.bad.value.in.header.for.segment.1.starting.at.2", new Object[] {
String.valueOf(l1), String.valueOf(k1)
}));
jbig2segment.referredToSegmentNumbers = ai;
// 239 420:aload 11
// 240 422:aload 9
// 241 424:putfield #285 <Field int[] JBIG2SegmentReader$JBIG2Segment.referredToSegmentNumbers>
int l = (int)ra.getFilePointer();
// 242 427:aload_0
// 243 428:getfield #93 <Field RandomAccessFileOrArray ra>
// 244 431:invokevirtual #216 <Method long RandomAccessFileOrArray.getFilePointer()>
// 245 434:l2i
// 246 435:istore_2
int j;
if(flag)
//* 247 436:iload 7
//* 248 438:ifeq 494
j = ra.readInt();
// 249 441:aload_0
// 250 442:getfield #93 <Field RandomAccessFileOrArray ra>
// 251 445:invokevirtual #253 <Method int RandomAccessFileOrArray.readInt()>
// 252 448:istore_1
else
//* 253 449:iload_1
//* 254 450:ifge 505
//* 255 453:new #179 <Class IllegalStateException>
//* 256 456:dup
//* 257 457:ldc2 #287 <String "page.1.invalid.for.segment.2.starting.at.3">
//* 258 460:iconst_3
//* 259 461:anewarray Object[]
//* 260 464:dup
//* 261 465:iconst_0
//* 262 466:iload_1
//* 263 467:invokestatic #274 <Method String String.valueOf(int)>
//* 264 470:aastore
//* 265 471:dup
//* 266 472:iconst_1
//* 267 473:iload 6
//* 268 475:invokestatic #274 <Method String String.valueOf(int)>
//* 269 478:aastore
//* 270 479:dup
//* 271 480:iconst_2
//* 272 481:iload 5
//* 273 483:invokestatic #274 <Method String String.valueOf(int)>
//* 274 486:aastore
//* 275 487:invokestatic #187 <Method String MessageLocalization.getComposedMessage(String, Object[])>
//* 276 490:invokespecial #190 <Method void IllegalStateException(String)>
//* 277 493:athrow
j = ra.read();
// 278 494:aload_0
// 279 495:getfield #93 <Field RandomAccessFileOrArray ra>
// 280 498:invokevirtual #246 <Method int RandomAccessFileOrArray.read()>
// 281 501:istore_1
if(j < 0)
throw new IllegalStateException(MessageLocalization.getComposedMessage("page.1.invalid.for.segment.2.starting.at.3", new Object[] {
String.valueOf(j), String.valueOf(l1), String.valueOf(k1)
}));
//* 282 502:goto 449
jbig2segment.page = j;
// 283 505:aload 11
// 284 507:iload_1
// 285 508:putfield #290 <Field int JBIG2SegmentReader$JBIG2Segment.page>
jbig2segment.page_association_size = flag;
// 286 511:aload 11
// 287 513:iload 7
// 288 515:putfield #293 <Field boolean JBIG2SegmentReader$JBIG2Segment.page_association_size>
jbig2segment.page_association_offset = l - k1;
// 289 518:aload 11
// 290 520:iload_2
// 291 521:iload 5
// 292 523:isub
// 293 524:putfield #296 <Field int JBIG2SegmentReader$JBIG2Segment.page_association_offset>
if(j > 0 && !pages.containsKey(((Object) (Integer.valueOf(j)))))
//* 294 527:iload_1
//* 295 528:ifle 570
//* 296 531:aload_0
//* 297 532:getfield #82 <Field SortedMap pages>
//* 298 535:iload_1
//* 299 536:invokestatic #160 <Method Integer Integer.valueOf(int)>
//* 300 539:invokeinterface #300 <Method boolean SortedMap.containsKey(Object)>
//* 301 544:ifne 570
pages.put(((Object) (Integer.valueOf(j))), ((Object) (new JBIG2Page(j, this))));
// 302 547:aload_0
// 303 548:getfield #82 <Field SortedMap pages>
// 304 551:iload_1
// 305 552:invokestatic #160 <Method Integer Integer.valueOf(int)>
// 306 555:new #6 <Class JBIG2SegmentReader$JBIG2Page>
// 307 558:dup
// 308 559:iload_1
// 309 560:aload_0
// 310 561:invokespecial #303 <Method void JBIG2SegmentReader$JBIG2Page(int, JBIG2SegmentReader)>
// 311 564:invokeinterface #210 <Method Object SortedMap.put(Object, Object)>
// 312 569:pop
if(j > 0)
//* 313 570:iload_1
//* 314 571:ifle 654
((JBIG2Page)pages.get(((Object) (Integer.valueOf(j))))).addSegment(jbig2segment);
// 315 574:aload_0
// 316 575:getfield #82 <Field SortedMap pages>
// 317 578:iload_1
// 318 579:invokestatic #160 <Method Integer Integer.valueOf(int)>
// 319 582:invokeinterface #166 <Method Object SortedMap.get(Object)>
// 320 587:checkcast #6 <Class JBIG2SegmentReader$JBIG2Page>
// 321 590:aload 11
// 322 592:invokevirtual #306 <Method void JBIG2SegmentReader$JBIG2Page.addSegment(JBIG2SegmentReader$JBIG2Segment)>
else
//* 323 595:aload 11
//* 324 597:aload_0
//* 325 598:getfield #93 <Field RandomAccessFileOrArray ra>
//* 326 601:invokevirtual #281 <Method long RandomAccessFileOrArray.readUnsignedInt()>
//* 327 604:putfield #310 <Field long JBIG2SegmentReader$JBIG2Segment.dataLength>
//* 328 607:aload_0
//* 329 608:getfield #93 <Field RandomAccessFileOrArray ra>
//* 330 611:invokevirtual #216 <Method long RandomAccessFileOrArray.getFilePointer()>
//* 331 614:l2i
//* 332 615:istore_1
//* 333 616:aload_0
//* 334 617:getfield #93 <Field RandomAccessFileOrArray ra>
//* 335 620:iload 5
//* 336 622:i2l
//* 337 623:invokevirtual #230 <Method void RandomAccessFileOrArray.seek(long)>
//* 338 626:iload_1
//* 339 627:iload 5
//* 340 629:isub
//* 341 630:newarray byte[]
//* 342 632:astore 9
//* 343 634:aload_0
//* 344 635:getfield #93 <Field RandomAccessFileOrArray ra>
//* 345 638:aload 9
//* 346 640:invokevirtual #233 <Method int RandomAccessFileOrArray.read(byte[])>
//* 347 643:pop
//* 348 644:aload 11
//* 349 646:aload 9
//* 350 648:putfield #131 <Field byte[] JBIG2SegmentReader$JBIG2Segment.headerData>
//* 351 651:aload 11
//* 352 653:areturn
globals.add(((Object) (jbig2segment)));
// 353 654:aload_0
// 354 655:getfield #87 <Field SortedSet globals>
// 355 658:aload 11
// 356 660:invokeinterface #313 <Method boolean SortedSet.add(Object)>
// 357 665:pop
jbig2segment.dataLength = ra.readUnsignedInt();
j = (int)ra.getFilePointer();
ra.seek(k1);
ai = ((int []) (new byte[j - k1]));
ra.read(((byte []) (ai)));
jbig2segment.headerData = ((byte []) (ai));
return jbig2segment;
//* 358 666:goto 595
}
void readSegment(JBIG2Segment jbig2segment)
throws IOException
{
int j = (int)ra.getFilePointer();
// 0 0:aload_0
// 1 1:getfield #93 <Field RandomAccessFileOrArray ra>
// 2 4:invokevirtual #216 <Method long RandomAccessFileOrArray.getFilePointer()>
// 3 7:l2i
// 4 8:istore_3
if(jbig2segment.dataLength != 0xffffffffL)
//* 5 9:aload_1
//* 6 10:getfield #310 <Field long JBIG2SegmentReader$JBIG2Segment.dataLength>
//* 7 13:ldc2w #314 <Long 0xffffffffL>
//* 8 16:lcmp
//* 9 17:ifne 21
//* 10 20:return
{
byte abyte0[] = new byte[(int)jbig2segment.dataLength];
// 11 21:aload_1
// 12 22:getfield #310 <Field long JBIG2SegmentReader$JBIG2Segment.dataLength>
// 13 25:l2i
// 14 26:newarray byte[]
// 15 28:astore 5
ra.read(abyte0);
// 16 30:aload_0
// 17 31:getfield #93 <Field RandomAccessFileOrArray ra>
// 18 34:aload 5
// 19 36:invokevirtual #233 <Method int RandomAccessFileOrArray.read(byte[])>
// 20 39:pop
jbig2segment.data = abyte0;
// 21 40:aload_1
// 22 41:aload 5
// 23 43:putfield #138 <Field byte[] JBIG2SegmentReader$JBIG2Segment.data>
if(jbig2segment.type == 48)
//* 24 46:aload_1
//* 25 47:getfield #127 <Field int JBIG2SegmentReader$JBIG2Segment.type>
//* 26 50:bipush 48
//* 27 52:icmpne 20
{
int i = (int)ra.getFilePointer();
// 28 55:aload_0
// 29 56:getfield #93 <Field RandomAccessFileOrArray ra>
// 30 59:invokevirtual #216 <Method long RandomAccessFileOrArray.getFilePointer()>
// 31 62:l2i
// 32 63:istore_2
ra.seek(j);
// 33 64:aload_0
// 34 65:getfield #93 <Field RandomAccessFileOrArray ra>
// 35 68:iload_3
// 36 69:i2l
// 37 70:invokevirtual #230 <Method void RandomAccessFileOrArray.seek(long)>
j = ra.readInt();
// 38 73:aload_0
// 39 74:getfield #93 <Field RandomAccessFileOrArray ra>
// 40 77:invokevirtual #253 <Method int RandomAccessFileOrArray.readInt()>
// 41 80:istore_3
int k = ra.readInt();
// 42 81:aload_0
// 43 82:getfield #93 <Field RandomAccessFileOrArray ra>
// 44 85:invokevirtual #253 <Method int RandomAccessFileOrArray.readInt()>
// 45 88:istore 4
ra.seek(i);
// 46 90:aload_0
// 47 91:getfield #93 <Field RandomAccessFileOrArray ra>
// 48 94:iload_2
// 49 95:i2l
// 50 96:invokevirtual #230 <Method void RandomAccessFileOrArray.seek(long)>
JBIG2Page jbig2page = (JBIG2Page)pages.get(((Object) (Integer.valueOf(jbig2segment.page))));
// 51 99:aload_0
// 52 100:getfield #82 <Field SortedMap pages>
// 53 103:aload_1
// 54 104:getfield #290 <Field int JBIG2SegmentReader$JBIG2Segment.page>
// 55 107:invokestatic #160 <Method Integer Integer.valueOf(int)>
// 56 110:invokeinterface #166 <Method Object SortedMap.get(Object)>
// 57 115:checkcast #6 <Class JBIG2SegmentReader$JBIG2Page>
// 58 118:astore 5
if(jbig2page == null)
//* 59 120:aload 5
//* 60 122:ifnonnull 143
{
throw new IllegalStateException(MessageLocalization.getComposedMessage("referring.to.widht.height.of.page.we.havent.seen.yet.1", jbig2segment.page));
// 61 125:new #179 <Class IllegalStateException>
// 62 128:dup
// 63 129:ldc2 #317 <String "referring.to.widht.height.of.page.we.havent.seen.yet.1">
// 64 132:aload_1
// 65 133:getfield #290 <Field int JBIG2SegmentReader$JBIG2Segment.page>
// 66 136:invokestatic #244 <Method String MessageLocalization.getComposedMessage(String, int)>
// 67 139:invokespecial #190 <Method void IllegalStateException(String)>
// 68 142:athrow
} else
{
jbig2page.pageBitmapWidth = j;
// 69 143:aload 5
// 70 145:iload_3
// 71 146:putfield #175 <Field int JBIG2SegmentReader$JBIG2Page.pageBitmapWidth>
jbig2page.pageBitmapHeight = k;
// 72 149:aload 5
// 73 151:iload 4
// 74 153:putfield #171 <Field int JBIG2SegmentReader$JBIG2Page.pageBitmapHeight>
return;
// 75 156:return
}
}
}
}
public String toString()
{
if(read)
//* 0 0:aload_0
//* 1 1:getfield #91 <Field boolean read>
//* 2 4:ifeq 31
return (new StringBuilder()).append("Jbig2SegmentReader: number of pages: ").append(numberOfPages()).toString();
// 3 7:new #321 <Class StringBuilder>
// 4 10:dup
// 5 11:invokespecial #322 <Method void StringBuilder()>
// 6 14:ldc2 #324 <String "Jbig2SegmentReader: number of pages: ">
// 7 17:invokevirtual #328 <Method StringBuilder StringBuilder.append(String)>
// 8 20:aload_0
// 9 21:invokevirtual #330 <Method int numberOfPages()>
// 10 24:invokevirtual #333 <Method StringBuilder StringBuilder.append(int)>
// 11 27:invokevirtual #335 <Method String StringBuilder.toString()>
// 12 30:areturn
else
return "Jbig2SegmentReader in indeterminate state.";
// 13 31:ldc2 #337 <String "Jbig2SegmentReader in indeterminate state.">
// 14 34:areturn
}
public static final int END_OF_FILE = 51;
public static final int END_OF_PAGE = 49;
public static final int END_OF_STRIPE = 50;
public static final int EXTENSION = 62;
public static final int IMMEDIATE_GENERIC_REFINEMENT_REGION = 42;
public static final int IMMEDIATE_GENERIC_REGION = 38;
public static final int IMMEDIATE_HALFTONE_REGION = 22;
public static final int IMMEDIATE_LOSSLESS_GENERIC_REFINEMENT_REGION = 43;
public static final int IMMEDIATE_LOSSLESS_GENERIC_REGION = 39;
public static final int IMMEDIATE_LOSSLESS_HALFTONE_REGION = 23;
public static final int IMMEDIATE_LOSSLESS_TEXT_REGION = 7;
public static final int IMMEDIATE_TEXT_REGION = 6;
public static final int INTERMEDIATE_GENERIC_REFINEMENT_REGION = 40;
public static final int INTERMEDIATE_GENERIC_REGION = 36;
public static final int INTERMEDIATE_HALFTONE_REGION = 20;
public static final int INTERMEDIATE_TEXT_REGION = 4;
public static final int PAGE_INFORMATION = 48;
public static final int PATTERN_DICTIONARY = 16;
public static final int PROFILES = 52;
public static final int SYMBOL_DICTIONARY = 0;
public static final int TABLES = 53;
private final SortedSet globals = new TreeSet();
private int number_of_pages;
private boolean number_of_pages_known;
private final SortedMap pages = new TreeMap();
private RandomAccessFileOrArray ra;
private boolean read;
private final SortedMap segments = new TreeMap();
private boolean sequential;
}
| 39.444201 | 172 | 0.551278 |
f1bf8af39eec9a91cd1d4ba3f386f8c12504bfb2 | 2,895 | /**
* Copyright (C) 2008-2010 Matt Gumbley, DevZendo.org <http://devzendo.org>
*
* 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.devzendo.minimiser.pluginmanager;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
/**
* The default implementation of the PluginRegistry.
*
* @author matt
*
*/
public final class DefaultPluginRegistry implements PluginRegistry {
private final Set<PluginDescriptor> mPluginDescriptors;
private ApplicationPluginDescriptor mApplicationPluginDescriptor;
/**
* Construct the default plugin registry
*/
public DefaultPluginRegistry() {
mPluginDescriptors = new HashSet<PluginDescriptor>();
}
/**
* {@inheritDoc}
*/
public ApplicationPluginDescriptor getApplicationPluginDescriptor() {
return mApplicationPluginDescriptor;
}
/**
* {@inheritDoc}
*/
public List<PluginDescriptor> getPluginDescriptors() {
return new ArrayList<PluginDescriptor>(mPluginDescriptors);
}
/**
* {@inheritDoc}
*/
public void addPluginDescriptor(final PluginDescriptor pluginDescriptor) {
if (pluginDescriptor.isApplication()) {
if (mApplicationPluginDescriptor != null && !mApplicationPluginDescriptor.equals(pluginDescriptor)) {
throw new IllegalStateException("Cannot add multiple application plugin descriptors");
}
mApplicationPluginDescriptor = (ApplicationPluginDescriptor) pluginDescriptor;
}
mPluginDescriptors.add(pluginDescriptor);
}
/**
* {@inheritDoc}
*/
public String getApplicationName() {
if (mApplicationPluginDescriptor != null) {
final String appName = mApplicationPluginDescriptor.getName();
if (!StringUtils.isBlank(appName)) {
return appName;
}
}
return UNKNOWN_APPLICATION;
}
/**
* {@inheritDoc}
*/
public String getApplicationVersion() {
if (mApplicationPluginDescriptor != null) {
final String appVersion = mApplicationPluginDescriptor.getVersion();
if (!StringUtils.isBlank(appVersion)) {
return appVersion;
}
}
return UNKNOWN_VERSION;
}
}
| 30.15625 | 113 | 0.669775 |
b91c553d8d512e7ee9933d1bc5c80674ce3990ed | 4,790 | /**
* 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.
*
* Copyright 2012-2016 the original author or authors.
*/
package org.assertj.examples.custom;
import org.assertj.core.api.AbstractAssert;
import org.assertj.core.util.Objects;
import org.assertj.examples.data.Race;
import org.assertj.examples.data.TolkienCharacter;
/**
* A simple class to illustrate how to extend AssertJ assertions with custom ones to make assertions speicific to
* {@link TolkienCharacter}.
*
* @author Joel Costigliola
*/
// 1 - Remember to inherit from AbstractAssert !
public class TolkienCharacterAssert extends
AbstractAssert<TolkienCharacterAssert, TolkienCharacter> {
// 2 - Write a constructor to build your assertion class from the object you want make assertions on.
/**
* Creates a new </code>{@link TolkienCharacterAssert}</code> to make assertions on actual TolkienCharacter.
*
* @param actual the TolkienCharacter we want to make assertions on.
*/
public TolkienCharacterAssert(TolkienCharacter actual) {
super(actual, TolkienCharacterAssert.class);
}
// 3 - A fluent entry point to your specific assertion class
// the other option here is to gather all your specific assertions entry point to a class inehriting from Assertions
// thus this class will be your oonly entry poiny to all AssertJ assertions and YOURS.
// see MyProjectAssertions for an example.
/**
* An entry point for TolkienCharacterAssert to follow AssertJ standard <code>assertThat()</code> statements.<br>
* With a static import, one's can write directly : <code>assertThat(frodo).hasName("Frodo");</code>
*
* @param actual the TolkienCharacter we want to make assertions on.
* @return a new </code>{@link TolkienCharacterAssert}</code>
*/
public static TolkienCharacterAssert assertThat(TolkienCharacter actual) {
return new TolkienCharacterAssert(actual);
}
// 4 - a specific assertion
/**
* Verifies that the actual TolkienCharacter's name is equal to the given one.
*
* @param name the given name to compare the actual TolkienCharacter's name to.
* @return this assertion object.
* @throws AssertionError - if the actual TolkienCharacter's name is not equal to the given one.
*/
public TolkienCharacterAssert hasName(String name) {
// check that actual TolkienCharacter we want to make assertions on is not null.
isNotNull();
// check condition
if (!actual.getName().equals(name)) {
failWithMessage("Expected character's name to be <%s> but was <%s>", name, actual.getName());
}
// return the current assertion for method chaining
return this;
}
/**
* Verifies that the actual TolkienCharacter's race is equal to the given one.
* @param race the given race to compare the actual TolkienCharacter's race to.
* @return this assertion object.
* @throws AssertionError - if the actual TolkienCharacter's race is not equal to the given one.
*/
public TolkienCharacterAssert hasRace(Race race) {
// check that actual TolkienCharacter we want to make assertions on is not null.
isNotNull();
// overrides the default error message with a more explicit one
String assertjErrorMessage = "\nExpected race of:\n <%s>\nto be:\n <%s>\nbut was:\n <%s>";
// null safe check
Race actualRace = actual.getRace();
if (!Objects.areEqual(actualRace, race)) {
failWithMessage(assertjErrorMessage, actual, race, actualRace);
}
// return the current assertion for method chaining
return this;
}
// another specific assertion
/**
* Verifies that the actual TolkienCharacter's age is equal to the given one.
*
* @param age the given age to compare the actual TolkienCharacter's age to.
* @return this assertion object.
* @throws AssertionError - if the actual TolkienCharacter's age is not equal to the given one.
*/
public TolkienCharacterAssert hasAge(int age) {
// check that actual TolkienCharacter we want to make assertions on is not null.
isNotNull();
// check condition
if (actual.age != age) {
failWithMessage("Expected character's age to be <%s> but was <%s>", age, actual.age);
}
// return the current assertion for method chaining
return this;
}
}
| 39.916667 | 118 | 0.719833 |
42fde27d280a7e7ae1801245e3705e934e4252c1 | 984 | package com.mcjty.mytutorial.setup;
import com.mcjty.mytutorial.blocks.FirstBlockScreen;
import com.mcjty.mytutorial.blocks.ModBlocks;
import com.mcjty.mytutorial.entities.WeirdMobEntity;
import com.mcjty.mytutorial.entities.WeirdMobRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScreenManager;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.world.World;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
public class ClientProxy implements IProxy {
@Override
public void init() {
ScreenManager.registerFactory(ModBlocks.FIRSTBLOCK_CONTAINER, FirstBlockScreen::new);
RenderingRegistry.registerEntityRenderingHandler(WeirdMobEntity.class, WeirdMobRenderer::new);
}
@Override
public World getClientWorld() {
return Minecraft.getInstance().world;
}
@Override
public PlayerEntity getClientPlayer() {
return Minecraft.getInstance().player;
}
}
| 31.741935 | 102 | 0.779472 |
0ceb640e17172cb53d2aa02cc282f13ee181ed94 | 2,794 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.core.commons.services.image;
import org.olat.core.logging.OLog;
import org.olat.core.logging.Tracing;
import org.olat.core.util.StringHelper;
/**
*
* @author srosse, [email protected], http://www.frentix
*
*/
public class Size {
private static final OLog log = Tracing.createLoggerFor(Size.class);
private final int width;
private final int height;
private final int xOffset;
private final int yOffset;
private final boolean changed;
public Size(int width, int height, boolean changed) {
this(width, height, 0, 0, changed);
}
public Size(int width, int height, int xOffset, int yOffset, boolean changed) {
this.width = width;
this.height = height;
this.xOffset = xOffset;
this.yOffset = yOffset;
this.changed = changed;
}
public static Size parseString(String str) {
Size size = null;
int index = str.indexOf('x');
if(index > 0) {
String widthStr = str.substring(0, index);
String heightStr = str.substring(index+1);
if(StringHelper.isLong(widthStr) && StringHelper.isLong(heightStr)) {
try {
int width = Integer.parseInt(widthStr);
int height = Integer.parseInt(heightStr);
size = new Size(width, height, false);
} catch (NumberFormatException e) {
log.warn("", e);
}
}
}
return size;
}
public int getWidth() {
if(width <= 0) {
return 1;
}
return width;
}
public int getHeight() {
if(height <= 0) {
return 1;
}
return height;
}
public int getXOffset() {
if(xOffset < 0) {
return 0;
}
return xOffset;
}
public int getYOffset() {
if(yOffset < 0) {
return 0;
}
return yOffset;
}
public boolean isChanged() {
return changed;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Size[width=").append(width)
.append(":height=").append(height)
.append(":changed=").append(changed)
.append("]").append(super.toString());
return sb.toString();
}
}
| 24.508772 | 82 | 0.675376 |
1cb6df1141077890589f29465a701b468e4b0f73 | 3,632 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.ant;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileList;
import org.apache.tools.ant.types.FileSet;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
public class CheckZipTask extends Task {
private String zipfile = null;
private List<FileSet> filesets = new ArrayList<FileSet>();
private List<FileList> filelists = new ArrayList<FileList>();
/**
* Add a set of files to touch
*/
public void addFileset(FileSet set) {
filesets.add(set);
}
/**
* Add a filelist to touch
*/
public void addFilelist(FileList list) {
filelists.add(list);
}
// The method executing the task
@Override
public void execute() throws BuildException {
myLog("Check " + zipfile);
try {
loadZipFile(new SFile(zipfile));
for (FileList fileList : filelists) {
manageFileList(fileList);
}
} catch (IOException e) {
e.printStackTrace();
throw new BuildException(e.toString());
}
}
private void manageFileList(FileList fileList) {
boolean error = false;
final String[] srcFiles = fileList.getFiles(getProject());
for (String s : srcFiles) {
if (isPresentInFile(s) == false) {
myLog("Missing " + s);
error = true;
}
}
if (error) {
throw new BuildException("Some entries are missing in the zipfile");
}
}
private boolean isPresentInFile(String s) {
return entries.contains(s);
}
private final List<String> entries = new ArrayList<String>();
private void loadZipFile(SFile file) throws IOException {
this.entries.clear();
final PrintWriter pw = SecurityUtils.createPrintWriter("tmp.txt");
final InputStream tmp = file.openFile();
if (tmp == null) {
throw new FileNotFoundException();
}
final ZipInputStream zis = new ZipInputStream(tmp);
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
final String fileName = ze.getName();
this.entries.add(fileName);
if (fileName.endsWith("/") == false) {
pw.println("<file name=\"" + fileName + "\" />");
}
ze = zis.getNextEntry();
}
pw.close();
zis.close();
}
private synchronized void myLog(String s) {
this.log(s);
}
public void setZipfile(String s) {
this.zipfile = s;
}
}
| 26.129496 | 76 | 0.674284 |
b7b15818bab66fd0267a90da7f470db9c0a894b5 | 655 | package p;
import java.util.function.*;
class I<E> {
<F> String searchForRefs() {
return "";
}
/**
* @see I#searchForRefs()
*/
public void bar() {
this.searchForRefs();
Supplier<String> v1 = new I<Integer>()::<>searchForRefs;
Supplier<String> v2 = this::<>searchForRefs;
Function<I<Integer>, String> v3 = I<Integer>::<>searchForRefs;
Function<I<Integer>, String> v4 = I::<>searchForRefs;
Function<I<Integer>, String> v5 = I::<Object>searchForRefs;
searchForRefs();
}
}
class Sub extends I<Object> {
Supplier<String> hexer3 = super::<>searchForRefs;
}
| 22.586207 | 70 | 0.584733 |
89a4d9408cca84d6cc42d774a5d6e4353ba8e330 | 3,489 | package cz.vutbr.fit.openmrdp.model;
import cz.vutbr.fit.openmrdp.model.base.RDFTriple;
import cz.vutbr.fit.openmrdp.model.informationbase.InformationBaseService;
import cz.vutbr.fit.openmrdp.model.informationbase.InformationBaseTestService;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
/**
* @author Jiri Koudelka
* @since 17.03.2018.
*/
public final class LocationTreeServiceTest {
private static final String DEFAULT_LEVEL_UP_PATH_PREDICATE = "<loc:locatedIn>";
private static final String DEFAULT_DELIMITER = "\\";
private static final String EXPECTED_PATH_FOR_FUEL1_RESOURCE = "urn:uuid:room1\\urn:uuid:box1\\urn:uuid:fuel1";
private static final String FUEL_RESOURCE_NAME = "urn:uuid:fuel1";
private static final String TEST_RESOURCE_NAME = "urn:uuid:test";
private static final String NON_EXISTING_RESOURCE_NAME = "urn:uuid:nonExistingResourceName";
private static final String NEW_TEST_RESOURCE = "urn:uuid:newTestResource";
private final LocationTreeService service = new LocationTreeService(DEFAULT_DELIMITER, DEFAULT_LEVEL_UP_PATH_PREDICATE);
@Before
public void initializeLocationTree() {
service.createLocationTree(createLocationInformationTestSet());
}
@Test
public void findLocationForExistingResource() {
assertThat(service.findResourceLocation(FUEL_RESOURCE_NAME), is(EXPECTED_PATH_FOR_FUEL1_RESOURCE));
}
@Test
public void findLocationForNonExistingResource() {
assertThat(service.findResourceLocation(NON_EXISTING_RESOURCE_NAME), is(nullValue()));
}
private Set<RDFTriple> createLocationInformationTestSet() {
Set<RDFTriple> locationInformation = new HashSet<>();
InformationBaseService service = new InformationBaseTestService();
for (RDFTriple triple : service.loadInformationBase()) {
if (triple.getPredicate().equals(DEFAULT_LEVEL_UP_PATH_PREDICATE)) {
locationInformation.add(triple);
}
}
return locationInformation;
}
@Test
public void addLocationInformation() {
RDFTriple newLocationInformation = new RDFTriple(TEST_RESOURCE_NAME, "<loc:locatedIn>", FUEL_RESOURCE_NAME);
service.addLocationInformation(newLocationInformation);
assertThat(service.findResourceLocation(TEST_RESOURCE_NAME), is("urn:uuid:room1\\urn:uuid:box1\\urn:uuid:fuel1\\urn:uuid:test"));
}
@Test
public void addLocationInformationWithContainsInfo() {
RDFTriple newLocationInformation = new RDFTriple(FUEL_RESOURCE_NAME, "<loc:contains>", TEST_RESOURCE_NAME);
service.addLocationInformation(newLocationInformation);
assertThat(service.findResourceLocation(TEST_RESOURCE_NAME), is(nullValue()));
}
@Test
public void removeLocationFromTree() {
RDFTriple newLocationInformation = new RDFTriple(NEW_TEST_RESOURCE, "<loc:locatedIn>", FUEL_RESOURCE_NAME);
service.addLocationInformation(newLocationInformation);
assertThat(service.findResourceLocation(NEW_TEST_RESOURCE), is("urn:uuid:room1\\urn:uuid:box1\\urn:uuid:fuel1\\urn:uuid:newTestResource"));
service.removeLocationInformation(newLocationInformation);
assertThat(service.findResourceLocation(NEW_TEST_RESOURCE), is(nullValue()));
}
} | 39.647727 | 147 | 0.752078 |
52554990c83085d37d3ac25c56c332ebeeac95d3 | 3,040 | package com.datastax.events;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.demo.utils.KillableRunner;
import com.datastax.demo.utils.PropertyHelper;
import com.datastax.demo.utils.ThreadUtils;
import com.datastax.demo.utils.Timer;
import com.datastax.events.data.EventGenerator;
import com.datastax.events.model.Event;
import com.datastax.events.service.EventService;
public class Main {
private static Logger logger = LoggerFactory.getLogger(Main.class);
public Main() {
String noOfEventsStr = PropertyHelper.getProperty("noOfEvents", "10000");
int noOfDays = Integer.parseInt(PropertyHelper.getProperty("noOfDays", "32"));
BlockingQueue<Event> queue = new ArrayBlockingQueue<Event>(100);
List<KillableRunner> tasks = new ArrayList<>();
//Executor for Threads
int noOfThreads = Integer.parseInt(PropertyHelper.getProperty("noOfThreads", "4"));
ExecutorService executor = Executors.newFixedThreadPool(noOfThreads);
EventService service = new EventService();
int noOfEvents = Integer.parseInt(noOfEventsStr);
int totalEvents = noOfEvents*noOfDays;
logger.info("Writing " + totalEvents + " historic events");
for (int i = 0; i < noOfThreads; i++) {
KillableRunner task = new EventWriter(service, queue);
executor.execute(task);
tasks.add(task);
}
Timer timer = new Timer();
for (int i = 0; i < totalEvents; i++) {
try{
queue.put(EventGenerator.createRandomEvent(noOfEvents, noOfDays));
if (EventGenerator.eventCounter.get() % 100000 == 0){
sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
timer.end();
logger.info("Writing realtime events");
Random r = new Random();
while(true){
try{
queue.put(EventGenerator.createRandomEventNow());
sleep(new Double(Math.random()*15).intValue());
double d = r.nextGaussian()*-1d;
//Create an random event
int test = new Double(Math.random()*10).intValue();
if (d*test < 1){
logger.info("Creating random events");
int someNumber = new Double(Math.random()*10).intValue();
for (int i=0; i < someNumber; i++){
queue.put(EventGenerator.createRandomEventNow());
if (new Double(Math.random()*100).intValue() > 2){
sleep(new Double(Math.random()*100).intValue());
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
ThreadUtils.shutdown(tasks, executor);
System.exit(0);
}
private void sleep(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
new Main();
System.exit(0);
}
}
| 24.715447 | 85 | 0.679934 |
24ae30f8531ef11f055095901f11b9c70f0b1a6c | 1,550 | //
// ========================================================================
// Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.osgi.httpservice;
import javax.servlet.http.HttpServlet;
/**
* For jetty agnostic handling of errors issued by the HttpService.
* Pass a servlet to the method setHttpServiceErrorHandler.
* In the servlet to read the status code of the error or the message or the exception,
* use org.eclipse.jetty.server.Dispatch's constants:
* int errorCode = httpServletRequest.getAttribute(Dispatcher.ERROR_STATUS_CODE)
* for example.
*/
public class HttpServiceErrorHandlerHelper
{
private static HttpServlet _customErrorHandler;
public static HttpServlet getCustomErrorHandler()
{
return _customErrorHandler;
}
public static void setHttpServiceErrorHandler(HttpServlet servlet)
{
_customErrorHandler = servlet;
}
}
| 33.695652 | 87 | 0.645806 |
403013f338c23ebd6fc429069c066f79ca73e019 | 4,720 | package com.angelolamonaca.bitcoinWalletTracker.activities;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.sqlite.SQLiteConstraintException;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.angelolamonaca.bitcoinWalletTracker.R;
import com.angelolamonaca.bitcoinWalletTracker.data.Wallet;
import com.angelolamonaca.bitcoinWalletTracker.data.WalletDao;
import com.angelolamonaca.bitcoinWalletTracker.data.WalletDatabase;
import org.json.JSONException;
import org.json.JSONObject;
public class AddWalletActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.N)
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wallet_add);
Toolbar myToolbar = findViewById(R.id.topAppBar);
setSupportActionBar(myToolbar);
Button addWalletButton = findViewById(R.id.add_wallet_button);
addWalletButton.setOnClickListener(view -> {
EditText addWallettAddressEditText = findViewById(R.id.add_wallet_address);
String newWalletAddress = addWallettAddressEditText.getEditableText().toString();
WalletDatabase walletDatabase = WalletDatabase.getInstance(getApplicationContext());
WalletDao walletDao = walletDatabase.walletDao();
final String blockStreamApiCallString = "https://blockstream.info/api/address/" + newWalletAddress;
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, blockStreamApiCallString, null,
response -> {
try {
JSONObject data = response.getJSONObject("chain_stats");
Object balanceObject = data.get("funded_txo_sum");
if (!balanceObject.toString().isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.add_a_wallet))
.setMessage(getString(R.string.sure_to_add_address) + "\n" + newWalletAddress)
.setPositiveButton(R.string.yes_add_it, (dialog, id) -> {
Wallet newWallet = new Wallet(newWalletAddress);
try {
walletDao.insertAll(newWallet);
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
} catch (SQLiteConstraintException e) {
Log.e("Error.SQLite", e.getMessage());
TextView addWalletErrorTextView = findViewById(R.id.add_wallet_error);
addWalletErrorTextView.setText(getString(R.string.this_address_is_already_on_your_list));
}
})
.setNegativeButton(R.string.no_maybe_later, (dialog, id) -> {
// User cancelled the dialog
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
} catch (JSONException e) {
Log.d("Error.JSON", e.getMessage());
}
},
error -> {
Log.d("Error.Response", error.toString());
TextView addWalletErrorTextView = findViewById(R.id.add_wallet_error);
addWalletErrorTextView.setText(getString(R.string.address_should_have_one_satoshi));
}
);
queue.add(getRequest);
});
}
}
| 47.2 | 137 | 0.576271 |
ddcb499a9dc1e5e9f0086e2eaa83de7769e4284e | 1,009 | package interviewquestions.medium;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sherxon on 1/24/17.
*/
public class SummaryRanges {
public static void main(String[] args) {
System.out.println(summaryRanges(new int[]{0}));
}
static List<String> summaryRanges(int[] a) {
List<String> list = new ArrayList<>();
if (a.length == 0) return list;
String s = String.valueOf(a[0]);
list.add(s);
for (int i = 1; i < a.length; i++) {
if (a[i] - 1 != a[i - 1]) {
s = list.get(list.size() - 1);
if (!s.equals(String.valueOf(a[i - 1])))
list.set(list.size() - 1, s + "->" + a[i - 1]);
list.add(String.valueOf(a[i]));
} else if (a.length - 1 == i) {
s = list.get(list.size() - 1);
list.set(list.size() - 1, s + "->" + a[i]);
}
}
return list;
}
}
| 29.676471 | 68 | 0.459861 |
183b9959b92593a47874b1109b47aeae3663754d | 2,453 | /**
* Copyright 2021-2022 jinzhaosn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jinzhaosn.data.pusher.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.jinzhaosn.common.model.ResultVo;
import com.github.jinzhaosn.data.pusher.service.RestPushDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 数据推送,用于外部系统REST调用传递数据,用于websocket推送
*
* @auther [email protected]
* @date 2022年02月14日
*/
@RestController
@RequestMapping("/v1/data")
public class DataPusherController {
private static final Logger logger = LoggerFactory.getLogger(DataPusherController.class);
@Autowired
RestPushDataService pushService;
/**
* 推送数据给用户
*
* @param username 用户
* @param dest 目标地址
* @param data 数据
* @return 推送结果
*/
@PostMapping("/pushToUser")
public ResultVo<?> pushToUser(
@RequestParam("username") String username, @RequestParam("dest") String dest,
@RequestBody JSONObject data) {
logger.info("push to user:[{}] dest:[{}]", username, dest);
pushService.pushToUser(username, dest, data);
return ResultVo.success();
}
/**
* 推送数据给主题
*
* @param topic 主题
* @param data 数据
* @return 推送结果
*/
@PostMapping("/pushToBroadcast")
public ResultVo<?> pushToBroadcast(String topic, @RequestBody JSONObject data) {
logger.info("push to broadcast: [{}]", topic);
pushService.pushToBroadcast(topic, data);
return ResultVo.success();
}
}
| 32.706667 | 93 | 0.710151 |
9b6c5e50f63c5cb9422280b69cb7193b34732c51 | 1,030 | package io.confluent.developer.moviesgenerator;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import static io.confluent.developer.moviesgenerator.Producer.MOVIES_TOPIC;
import static io.confluent.developer.moviesgenerator.Producer.RATINGS_TOPIC;
@SpringBootApplication
public class MoviesGeneratorApplication {
public static void main(String[] args) {
SpringApplication.run(MoviesGeneratorApplication.class, args);
}
@Value("${my.topics.replication.factor:1}")
Short replicationFactor;
@Value("${my.topics.partitions.count:1}")
Integer partitions;
@Bean
NewTopic ratingsTopic() {
return new NewTopic(RATINGS_TOPIC, partitions, replicationFactor);
}
@Bean
NewTopic moviesTopic() {
return new NewTopic(MOVIES_TOPIC, partitions, replicationFactor);
}
}
| 27.837838 | 76 | 0.798058 |
60d6fbd645fd700707f0adc33e52be50e0935dbc | 21,024 | // 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 org.jetbrains.groovy.compiler.rt;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovyjarjarasm.asm.Opcodes;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.classgen.GeneratorContext;
import org.codehaus.groovy.control.*;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.codehaus.groovy.control.messages.WarningMessage;
import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit;
import org.codehaus.groovy.tools.javac.JavaCompiler;
import org.codehaus.groovy.tools.javac.JavaCompilerFactory;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* @author peter
*/
@SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"})
public class DependentGroovycRunner {
public static final String TEMP_RESOURCE_SUFFIX = "___" + new Random().nextInt() + "_neverHappen";
public static final String[] RESOURCES_TO_MASK = {"META-INF/services/org.codehaus.groovy.transform.ASTTransformation", "META-INF/services/org.codehaus.groovy.runtime.ExtensionModule"};
private static final String STUB_DIR = "stubDir";
@SuppressWarnings("unused")
public static boolean runGroovyc(boolean forStubs, String argsPath,
@Nullable String configScript,
@Nullable String targetBytecode, @Nullable Queue mailbox) {
File argsFile = new File(argsPath);
CompilerConfiguration config = createCompilerConfiguration(targetBytecode);
config.setClasspath("");
config.setOutput(new PrintWriter(System.err));
config.setWarningLevel(WarningMessage.PARANOIA);
final List<CompilerMessage> compilerMessages = new ArrayList<CompilerMessage>();
final List<CompilationUnitPatcher> patchers = new ArrayList<CompilationUnitPatcher>();
final List<File> srcFiles = new ArrayList<File>();
final Map<String, File> class2File = new HashMap<String, File>();
final String[] finalOutputRef = new String[1];
fillFromArgsFile(argsFile, config, patchers, compilerMessages, srcFiles, class2File, finalOutputRef);
if (srcFiles.isEmpty()) return true;
String[] finalOutputs = finalOutputRef[0].split(File.pathSeparator);
if (forStubs) {
Map<String, Object> options = new HashMap<String, Object>();
options.put(STUB_DIR, config.getTargetDirectory());
options.put("keepStubs", Boolean.TRUE);
config.setJointCompilationOptions(options);
if (mailbox != null) {
config.setTargetDirectory(finalOutputs[0]);
}
}
try {
boolean asm = !"false".equals(System.getProperty(GroovyRtConstants.GROOVYC_ASM_RESOLVING_ONLY));
config.getOptimizationOptions().put("asmResolving", asm);
config.getOptimizationOptions().put("classLoaderResolving", !asm);
}
catch (NoSuchMethodError ignored) { // old groovyc's don't have optimization options
}
if (configScript != null && configScript.length() > 0) {
try {
applyConfigurationScript(new File(configScript), config);
}
catch (LinkageError ignored) {
}
}
System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: loading sources...");
renameResources(finalOutputs, "", TEMP_RESOURCE_SUFFIX);
final List<GroovyCompilerWrapper.OutputItem> compiledFiles;
try {
final AstAwareResourceLoader resourceLoader = new AstAwareResourceLoader(class2File);
final GroovyCompilerWrapper wrapper = new GroovyCompilerWrapper(compilerMessages, forStubs);
final CompilationUnit unit = createCompilationUnit(forStubs, config, buildClassLoaderFor(config, resourceLoader), mailbox, wrapper);
unit.addPhaseOperation(new CompilationUnit.SourceUnitOperation() {
@Override
public void call(SourceUnit source) throws CompilationFailedException {
File file = new File(source.getName());
for (ClassNode aClass : source.getAST().getClasses()) {
resourceLoader.myClass2File.put(aClass.getName(), file);
}
}
}, Phases.CONVERSION);
addSources(forStubs, srcFiles, unit);
runPatchers(patchers, compilerMessages, unit, resourceLoader, srcFiles);
System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: compiling...");
compiledFiles = wrapper.compile(unit, forStubs && mailbox == null ? Phases.CONVERSION : Phases.ALL);
}
finally {
renameResources(finalOutputs, TEMP_RESOURCE_SUFFIX, "");
System.out.println(GroovyRtConstants.CLEAR_PRESENTABLE);
}
System.out.println();
reportCompiledItems(compiledFiles);
int errorCount = 0;
for (CompilerMessage message : compilerMessages) {
if (message.getCategory() == GroovyCompilerMessageCategories.ERROR) {
if (errorCount > 100) {
continue;
}
errorCount++;
}
printMessage(message);
}
return false;
}
private static CompilerConfiguration createCompilerConfiguration(@Nullable String targetBytecode) {
CompilerConfiguration config = new CompilerConfiguration();
if (targetBytecode != null) {
config.setTargetBytecode(targetBytecode);
}
if (config.getTargetBytecode() == null) {
// unsupported value (e.g. "1.6" with older Groovyc versions which know only 1.5)
// clear env because CompilerConfiguration constructor just sets the target bytecode to null on encountering invalid value in the env
System.clearProperty(GroovyRtConstants.GROOVY_TARGET_BYTECODE);
// now recreate conf taking the default from VM version
config = new CompilerConfiguration();
if (config.getTargetBytecode() == null) {
throw new AssertionError("Cannot determine bytecode target");
}
}
return config;
}
// adapted from https://github.com/gradle/gradle/blob/c4fdfb57d336b1a0f1b27354c758c61c0a586942/subprojects/language-groovy/src/main/java/org/gradle/api/internal/tasks/compile/ApiGroovyCompiler.java
private static void applyConfigurationScript(File configScript, CompilerConfiguration configuration) {
Binding binding = new Binding();
binding.setVariable("configuration", configuration);
CompilerConfiguration configuratorConfig = new CompilerConfiguration();
ImportCustomizer customizer = new ImportCustomizer();
customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
configuratorConfig.addCompilationCustomizers(customizer);
try {
new GroovyShell(binding, configuratorConfig).evaluate(configScript);
}
catch (Exception e) {
e.printStackTrace();
}
}
private static void renameResources(String[] finalOutputs, String removeSuffix, String addSuffix) {
for (String output : finalOutputs) {
for (String res : RESOURCES_TO_MASK) {
File file = new File(output, res + removeSuffix);
if (file.exists()) {
file.renameTo(new File(output, res + addSuffix));
}
}
}
}
private static String fillFromArgsFile(File argsFile, CompilerConfiguration compilerConfiguration, List<? super CompilationUnitPatcher> patchers, List<? super CompilerMessage> compilerMessages,
List<? super File> srcFiles, Map<String, File> class2File, String[] finalOutputs) {
String moduleClasspath = null;
BufferedReader reader = null;
FileInputStream stream;
try {
stream = new FileInputStream(argsFile);
reader = new BufferedReader(new InputStreamReader(stream));
reader.readLine(); // skip classpath
String line;
while ((line = reader.readLine()) != null) {
if (!GroovyRtConstants.SRC_FILE.equals(line)) {
break;
}
final File file = new File(reader.readLine());
srcFiles.add(file);
}
while (line != null) {
if (line.equals("class2src")) {
while (!GroovyRtConstants.END.equals(line = reader.readLine())) {
class2File.put(line, new File(reader.readLine()));
}
}
else if (line.startsWith(GroovyRtConstants.PATCHERS)) {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String s;
while (!GroovyRtConstants.END.equals(s = reader.readLine())) {
try {
final Class<?> patcherClass = classLoader.loadClass(s);
final CompilationUnitPatcher patcher = (CompilationUnitPatcher)patcherClass.newInstance();
patchers.add(patcher);
}
catch (InstantiationException e) {
addExceptionInfo(compilerMessages, e, "Couldn't instantiate " + s);
}
catch (IllegalAccessException e) {
addExceptionInfo(compilerMessages, e, "Couldn't instantiate " + s);
}
catch (ClassNotFoundException e) {
addExceptionInfo(compilerMessages, e, "Couldn't instantiate " + s);
}
}
}
else if (line.startsWith(GroovyRtConstants.ENCODING)) {
compilerConfiguration.setSourceEncoding(reader.readLine());
}
else if (line.startsWith(GroovyRtConstants.OUTPUTPATH)) {
compilerConfiguration.setTargetDirectory(reader.readLine());
}
else if (line.startsWith(GroovyRtConstants.FINAL_OUTPUTPATH)) {
finalOutputs[0] = reader.readLine();
}
line = reader.readLine();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
argsFile.delete();
}
}
return moduleClasspath;
}
private static void addSources(boolean forStubs, List<? extends File> srcFiles, final CompilationUnit unit) {
for (final File file : srcFiles) {
if (forStubs && file.getName().endsWith(".java")) {
continue;
}
unit.addSource(new SourceUnit(file, unit.getConfiguration(), unit.getClassLoader(), unit.getErrorCollector()));
}
}
private static void runPatchers(List<? extends CompilationUnitPatcher> patchers, List<? super CompilerMessage> compilerMessages, CompilationUnit unit, final AstAwareResourceLoader loader, List<File> srcFiles) {
if (!patchers.isEmpty()) {
for (CompilationUnitPatcher patcher : patchers) {
try {
patcher.patchCompilationUnit(unit, loader, srcFiles.toArray(new File[0]));
}
catch (LinkageError e) {
addExceptionInfo(compilerMessages, e, "Couldn't run " + patcher.getClass().getName());
}
}
}
}
private static void reportCompiledItems(List<? extends GroovyCompilerWrapper.OutputItem> compiledFiles) {
for (GroovyCompilerWrapper.OutputItem compiledFile : compiledFiles) {
/*
* output path
* source file
* output root directory
*/
System.out.print(GroovyRtConstants.COMPILED_START);
System.out.print(compiledFile.getOutputPath());
System.out.print(GroovyRtConstants.SEPARATOR);
System.out.print(compiledFile.getSourceFile());
System.out.print(GroovyRtConstants.COMPILED_END);
System.out.println();
}
}
private static void printMessage(CompilerMessage message) {
System.out.print(GroovyRtConstants.MESSAGES_START);
System.out.print(message.getCategory());
System.out.print(GroovyRtConstants.SEPARATOR);
System.out.print(message.getMessage());
System.out.print(GroovyRtConstants.SEPARATOR);
System.out.print(message.getUrl());
System.out.print(GroovyRtConstants.SEPARATOR);
System.out.print(message.getLineNum());
System.out.print(GroovyRtConstants.SEPARATOR);
System.out.print(message.getColumnNum());
System.out.print(GroovyRtConstants.SEPARATOR);
System.out.print(GroovyRtConstants.MESSAGES_END);
System.out.println();
}
private static void addExceptionInfo(List<? super CompilerMessage> compilerMessages, Throwable e, String message) {
final StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
compilerMessages.add(new CompilerMessage(GroovyCompilerMessageCategories.WARNING, message + ":\n" + writer, "<exception>", -1, -1));
}
private static CompilationUnit createCompilationUnit(final boolean forStubs,
final CompilerConfiguration config,
final GroovyClassLoader classLoader,
Queue mailbox, GroovyCompilerWrapper wrapper) {
final GroovyClassLoader transformLoader = new GroovyClassLoader(classLoader);
try {
if (forStubs) {
return createStubGenerator(config, classLoader, transformLoader, mailbox, wrapper);
}
}
catch (NoClassDefFoundError ignore) { // older groovy distributions just don't have stub generation capability
}
CompilationUnit unit;
try {
unit = new CompilationUnit(config, null, classLoader, transformLoader) {
@Override
public void gotoPhase(int phase) throws CompilationFailedException {
super.gotoPhase(phase);
if (phase <= Phases.ALL) {
System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: " + getPhaseDescription());
}
}
};
}
catch (NoSuchMethodError e) {
//groovy 1.5.x
unit = new CompilationUnit(config, null, classLoader) {
@Override
public void gotoPhase(int phase) throws CompilationFailedException {
super.gotoPhase(phase);
if (phase <= Phases.ALL) {
System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: " + getPhaseDescription());
}
}
};
}
return unit;
}
private static CompilationUnit createStubGenerator(final CompilerConfiguration config,
final GroovyClassLoader classLoader,
final GroovyClassLoader transformLoader,
final Queue<Object> mailbox,
final GroovyCompilerWrapper wrapper) {
final JavaAwareCompilationUnit unit = new JavaAwareCompilationUnit(config, classLoader) {
private boolean annoRemovedAdded;
@Override
public GroovyClassLoader getTransformLoader() {
return transformLoader;
}
@Override
public void addPhaseOperation(PrimaryClassNodeOperation op, int phase) {
if (!annoRemovedAdded &&
mailbox == null &&
phase == Phases.CONVERSION &&
"true".equals(System.getProperty(GroovyRtConstants.GROOVYC_LEGACY_REMOVE_ANNOTATIONS)) &&
op.getClass().getName().startsWith("org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit$")) {
annoRemovedAdded = true;
super.addPhaseOperation(new PrimaryClassNodeOperation() {
@Override
public void call(final SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
final ClassCodeVisitorSupport annoRemover = new ClassCodeVisitorSupport() {
@Override
protected SourceUnit getSourceUnit() {
return source;
}
@Override
public void visitClass(ClassNode node) {
if (node.isEnum()) {
node.setModifiers(node.getModifiers() & ~Opcodes.ACC_FINAL);
}
super.visitClass(node);
}
@Override
public void visitField(FieldNode fieldNode) {
Expression valueExpr = fieldNode.getInitialValueExpression();
if (valueExpr instanceof ConstantExpression && ClassHelper.STRING_TYPE.equals(valueExpr.getType())) {
fieldNode.setInitialValueExpression(new MethodCallExpression(valueExpr, "toString", new ListExpression()));
}
super.visitField(fieldNode);
}
@Override
public void visitAnnotations(AnnotatedNode node) {
List<AnnotationNode> annotations = node.getAnnotations();
if (!annotations.isEmpty()) {
annotations.clear();
}
super.visitAnnotations(node);
}
};
try {
annoRemover.visitClass(classNode);
}
catch (LinkageError ignored) {
}
}
}, phase);
}
super.addPhaseOperation(op, phase);
}
@Override
public void gotoPhase(int phase) throws CompilationFailedException {
if (phase < Phases.SEMANTIC_ANALYSIS) {
System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovy stub generator: " + getPhaseDescription());
}
else if (phase <= Phases.ALL) {
System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: " + getPhaseDescription());
}
super.gotoPhase(phase);
}
};
unit.setCompilerFactory(new JavaCompilerFactory() {
public JavaCompiler createCompiler(final CompilerConfiguration config) {
return new JavaCompiler() {
public void compile(List<String> files, CompilationUnit cu) {
if (mailbox != null) {
reportCompiledItems(GroovyCompilerWrapper.getStubOutputItems(unit, (File)config.getJointCompilationOptions().get(STUB_DIR)));
System.out.flush();
System.err.flush();
pauseAndWaitForJavac((LinkedBlockingQueue<Object>)mailbox);
wrapper.onContinuation();
}
}
};
}
});
unit.addSources(new String[]{"SomeClass.java"});
return unit;
}
private static void pauseAndWaitForJavac(LinkedBlockingQueue<Object> mailbox) {
LinkedBlockingQueue<String> fromJps = new LinkedBlockingQueue<String>();
mailbox.offer(fromJps); // signal that stubs are generated
while (true) {
try {
Object response = fromJps.poll(1, TimeUnit.MINUTES);
if (GroovyRtConstants.BUILD_ABORTED.equals(response)) {
throw new RuntimeException(GroovyRtConstants.BUILD_ABORTED);
} else if (GroovyRtConstants.JAVAC_COMPLETED.equals(response)) {
return; // stop waiting and continue compiling
} else if (response != null) {
throw new RuntimeException("Unknown response: " + response);
}
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
static GroovyClassLoader buildClassLoaderFor(final CompilerConfiguration compilerConfiguration, final AstAwareResourceLoader resourceLoader) {
final ClassDependencyLoader checkWellFormed = new ClassDependencyLoader() {
@Override
protected void loadClassDependencies(Class aClass) throws ClassNotFoundException {
if (resourceLoader.getSourceFile(aClass.getName()) == null) return;
super.loadClassDependencies(aClass);
}
};
GroovyClassLoader classLoader = AccessController.doPrivileged(new PrivilegedAction<GroovyClassLoader>() {
public GroovyClassLoader run() {
return new GroovyClassLoader(Thread.currentThread().getContextClassLoader(), compilerConfiguration) {
@Override
public Class loadClass(String name, boolean lookupScriptFiles, boolean preferClassOverScript)
throws ClassNotFoundException, CompilationFailedException {
Class aClass;
try {
aClass = super.loadClass(name, lookupScriptFiles, preferClassOverScript);
}
catch (NoClassDefFoundError e) {
throw new ClassNotFoundException(name);
}
catch (LinkageError e) {
throw new RuntimeException("Problem loading class " + name, e);
}
return checkWellFormed.loadDependencies(aClass);
}
};
}
});
classLoader.setResourceLoader(resourceLoader);
return classLoader;
}
}
| 40.045714 | 212 | 0.660008 |
032f0b2183f2e51f24d12ed6c2b62ce7699eca5e | 1,845 | package mod.vemerion.wizardstaff.Helper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceContext;
import net.minecraft.util.math.RayTraceContext.BlockMode;
import net.minecraft.util.math.RayTraceContext.FluidMode;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
public class Helper {
public static Entity findTargetLine(Vector3d start, Vector3d direction, float distance, World world,
LivingEntity caster) {
AxisAlignedBB box = new AxisAlignedBB(start, start).grow(0.25);
for (int i = 0; i < distance * 2; i++) {
for (Entity e : world.getEntitiesInAABBexcluding(caster, box, (e) -> e instanceof LivingEntity)) {
return e;
}
box = box.offset(direction);
}
return null;
}
public static BlockRayTraceResult blockRay(World world, PlayerEntity player, float distance) {
Vector3d direction = Vector3d.fromPitchYaw(player.getPitchYaw());
Vector3d start = player.getPositionVec().add(0, player.getEyeHeight(), 0).add(direction.scale(0.2));
Vector3d stop = start.add(direction.scale(distance));
return world.rayTraceBlocks(new RayTraceContext(start, stop, BlockMode.OUTLINE, FluidMode.NONE, player));
}
public static int color(int r, int g, int b, int a) {
a = (a << 24) & 0xFF000000;
r = (r << 16) & 0x00FF0000;
g = (g << 8) & 0x0000FF00;
b &= 0x000000FF;
return a | r | g | b;
}
public static int red(int color) {
return (color >> 16) & 255;
}
public static int green(int color) {
return (color >> 8) & 255;
}
public static int blue(int color) {
return color & 255;
}
public static int alfa(int color) {
return color >>> 24;
}
}
| 31.271186 | 107 | 0.725203 |
4df9ba14e5d8ec868617a52dfa5acb02d4807bf4 | 1,782 | package org.oreilly.books.chapter3;
import java.util.Arrays;
import java.util.List;
public final class FruitPermit {
public static void main(String[] args) {
List<Apple> apples = Arrays.asList(new Apple(1), new Apple(10));
List<Orange> oranges = Arrays.asList(new Orange(1), new Orange(10));
List<Fruit> fruits = Arrays.<Fruit>asList(new Apple(1), new Orange(10));
assert Comparisons.max4(apples).equals(new Apple(10));
assert Comparisons.max4(oranges).equals(new Orange(10));
assert Comparisons.max4(fruits).equals(new Orange(10)); // ok
System.out.println(Comparisons.max4(apples));
System.out.println(Comparisons.max4(oranges));
System.out.println(Comparisons.max4(fruits));
Apple weeApple = new Apple(1);
Apple bigApple = new Apple(2);
apples = Arrays.asList(weeApple, bigApple);
System.out.println(weeApple.compareTo(bigApple));
System.out.println(Comparisons.max4(apples) == bigApple);
}
static class Fruit implements Comparable<Fruit> {
final String name;
final int size;
public Fruit(String name, int size) {
this.name = name;
this.size = size;
}
public int compareTo(Fruit that) {
return this.size < that.size ? -1 : this.size == that.size ? 0 : 1;
}
public String toString() {
return this.name + "(" + size + ")";
}
@Override
public boolean equals(Object o) {
return (o instanceof Fruit && name.equals(((Fruit) o).name) && size == ((Fruit) o).size);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + Integer.hashCode(size);
return result;
}
}
static class Apple extends Fruit {
public Apple(int size) {
super("Apple", size);
}
}
static class Orange extends Fruit {
public Orange(int size) {
super("Orange", size);
}
}
}
| 26.597015 | 92 | 0.680696 |
e4824963861b2c6b23acdfde912896829b0110b8 | 2,141 | package top.fastsql.datasource;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;
@Deprecated
public class FastDataSource implements DataSource {
private Driver driver;
private String url;
private String username;
private String password;
public FastDataSource(Driver driver, String url, String username, String password) {
this.driver = driver;
this.url = url;
this.username = username;
this.password = password;
}
@Override
public Connection getConnection() {
Properties properties = new Properties();
properties.setProperty("user", username);
properties.setProperty("password", password);
try {
return driver.connect(url, properties);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public Connection getConnection(String username, String password) throws SQLException, UnsupportedOperationException {
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException, UnsupportedOperationException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException, UnsupportedOperationException {
return false;
}
@Override
public PrintWriter getLogWriter() throws SQLException, UnsupportedOperationException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException, UnsupportedOperationException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException, UnsupportedOperationException {
}
@Override
public int getLoginTimeout() throws SQLException, UnsupportedOperationException {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException, UnsupportedOperationException {
return null;
}
}
| 26.7625 | 122 | 0.70341 |
4e56f944547a5893668a4c0bfd21664d92a67c57 | 6,957 | package com.knight.lib.ble.bleControl;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.os.Build;
import com.knight.lib.ble.BleManager;
import com.knight.lib.ble.callback.BleConnectGattCallback;
import com.knight.lib.ble.callback.BleWriteCallback;
import com.knight.lib.ble.exception.ConnectException;
import com.knight.lib.ble.exception.GattActionException;
import com.knight.lib.ble.info.BleConnectState;
import com.knight.lib.ble.info.BleDeviceBean;
import com.knight.lib.ble.utils.BleLg;
import java.lang.reflect.Method;
import java.util.HashMap;
/**
* 作者:HWQ on 2018/3/20 11:06
* 描述:通过BluetoothDevice进行连接断开操作,以及存储蓝牙操作相关回调!
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class BleBluetoothControler {
private BleDeviceBean mBleDeviceBean;
private BleConnectState connectState = BleConnectState.CONNECT_IDLE;
private BleConnectGattCallback bleGattCallback;
private BluetoothGatt bluetoothGatt;
private HashMap<String, BleWriteCallback> bleWriteCallbackHashMap = new HashMap<>();
public BleBluetoothControler(BleDeviceBean bleDeviceBean) {
mBleDeviceBean = bleDeviceBean;
}
/**
* 执行连接操作,保存当前BleGattCallback
*
* @param bleDeviceBean
* @param autoConnect
* @param bleGattCallback 连接回调,用于更新UI
* @return
*/
public BluetoothGatt connect(BleDeviceBean bleDeviceBean, boolean autoConnect,
BleConnectGattCallback bleGattCallback) {
setConnectGattCallback(bleGattCallback);
Context context = BleManager.getInstance().getContext();
BluetoothGatt bluetoothGatt = bleDeviceBean.getDevice().connectGatt(context,
autoConnect,
gattCallback);
if (bluetoothGatt != null) {
if (bleGattCallback != null)
bleGattCallback.onStartConnect();
connectState = BleConnectState.CONNECT_CONNECTING;
}
return bluetoothGatt;
}
public synchronized void setConnectGattCallback(BleConnectGattCallback callback) {
bleGattCallback = callback;
}
public synchronized void removeConnectGattCallback() {
bleGattCallback = null;
}
BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int
newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothGatt.STATE_CONNECTED) {
//连接成功,查找服务
gatt.discoverServices();
} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
closeBluetoothGatt();
BleManager.getInstance().setBleBluetoothControler(null);
if (connectState == BleConnectState.CONNECT_CONNECTING) {
connectState = BleConnectState.CONNECT_FAILURE;
if (bleGattCallback != null) {
bleGattCallback.onConnectFail(new ConnectException(gatt, status));
}
} else if (connectState == BleConnectState.CONNECT_CONNECTED) {
connectState = BleConnectState.CONNECT_DISCONNECT;
if (bleGattCallback != null) {
bleGattCallback.onDisConnected(mBleDeviceBean, gatt, status);
}
}
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
bluetoothGatt = gatt;
connectState = BleConnectState.CONNECT_CONNECTED;
bleGattCallback.onConnectSuccess(mBleDeviceBean, gatt, status);
BleManager.getInstance().setBleBluetoothControler(
BleBluetoothControler.this);
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
String uuid = characteristic.getUuid().toString();
BleWriteCallback bleWriteCallback = bleWriteCallbackHashMap.get(uuid);
if (bleWriteCallback != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
bleWriteCallback.onWriteSuccess(characteristic.getValue());
} else {
bleWriteCallback.onWriteFailure(new GattActionException(status));
}
}
}
};
public synchronized void disconnect(BleDeviceBean bleDevice) {
if (bluetoothGatt != null) {
bluetoothGatt.disconnect();
}
}
private synchronized void closeBluetoothGatt() {
if (bluetoothGatt != null) {
bluetoothGatt.close();
}
}
public void destroy() {
connectState = BleConnectState.CONNECT_IDLE;
if (bluetoothGatt != null) {
bluetoothGatt.disconnect();
}
if (bluetoothGatt != null) {
refreshDeviceCache();
}
if (bluetoothGatt != null) {
bluetoothGatt.close();
}
removeConnectGattCallback();
clearCharacterCallback();
}
public synchronized void clearCharacterCallback() {
if (bleWriteCallbackHashMap != null) {
bleWriteCallbackHashMap.clear();
}
}
private synchronized boolean refreshDeviceCache() {
try {
final Method refresh = BluetoothGatt.class.getMethod("refresh");
if (refresh != null) {
boolean success = (Boolean) refresh.invoke(getBluetoothGatt());
BleLg.d("refreshDeviceCache, is success: " + success);
return success;
}
} catch (Exception e) {
BleLg.d("exception occur while refreshing device: " + e.getMessage());
e.printStackTrace();
}
return false;
}
public BleDeviceBean getDevice() {
return mBleDeviceBean;
}
public BluetoothGatt getBluetoothGatt() {
return bluetoothGatt;
}
public void addWriteCallback(String uuid_write, BleWriteCallback bleWriteCallback) {
bleWriteCallbackHashMap.put(uuid_write, bleWriteCallback);
}
public void removeWriteCallback(String uuid_write) {
bleWriteCallbackHashMap.remove(uuid_write);
}
}
| 34.959799 | 90 | 0.616789 |
fc4a4a7585b63d419d120d44ef1725a1872d2a1c | 2,052 | package org.anddev.andengine.entity.layer.tiled.tmx;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
public class TMXTile
{
int mGlobalTileID;
TextureRegion mTextureRegion;
private final int mTileColumn;
private final int mTileHeight;
private final int mTileRow;
private final int mTileWidth;
public TMXTile(int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5, TextureRegion paramTextureRegion)
{
this.mGlobalTileID = paramInt1;
this.mTileRow = paramInt3;
this.mTileColumn = paramInt2;
this.mTileWidth = paramInt4;
this.mTileHeight = paramInt5;
this.mTextureRegion = paramTextureRegion;
}
public int getGlobalTileID()
{
return this.mGlobalTileID;
}
public TMXProperties<TMXTileProperty> getTMXTileProperties(TMXTiledMap paramTMXTiledMap)
{
return paramTMXTiledMap.getTMXTileProperties(this.mGlobalTileID);
}
public TextureRegion getTextureRegion()
{
return this.mTextureRegion;
}
public int getTileColumn()
{
return this.mTileColumn;
}
public int getTileHeight()
{
return this.mTileHeight;
}
public int getTileRow()
{
return this.mTileRow;
}
public int getTileWidth()
{
return this.mTileWidth;
}
public int getTileX()
{
return this.mTileColumn * this.mTileWidth;
}
public int getTileY()
{
return this.mTileRow * this.mTileHeight;
}
public void setGlobalTileID(TMXTiledMap paramTMXTiledMap, int paramInt)
{
this.mGlobalTileID = paramInt;
this.mTextureRegion = paramTMXTiledMap.getTextureRegionFromGlobalTileID(paramInt);
}
public void setTextureRegion(TextureRegion paramTextureRegion)
{
this.mTextureRegion = paramTextureRegion;
}
}
/* Location: C:\Users\Rodelle\Desktop\Attacknid\Tools\Attacknids-dex2jar.jar
* Qualified Name: org.anddev.andengine.entity.layer.tiled.tmx.TMXTile
* JD-Core Version: 0.7.0.1
*/ | 24.141176 | 126 | 0.692982 |
6fc300b17128038a8746756cee93d37d50b18119 | 5,312 | package de.hpi.is.md.hybrid.impl.preprocessed;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import de.hpi.is.md.hybrid.DictionaryRecords;
import de.hpi.is.md.hybrid.PositionListIndex;
import de.hpi.is.md.relational.Column;
import de.hpi.is.md.relational.InputCloseException;
import de.hpi.is.md.relational.InputOpenException;
import de.hpi.is.md.relational.Relation;
import de.hpi.is.md.relational.RelationalInput;
import de.hpi.is.md.relational.Row;
import de.hpi.is.md.relational.Schema;
import de.hpi.is.md.util.Dictionary;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class CompressorTest {
private static final Column<String> A = Column.of("a", String.class);
private static final Column<Integer> B = Column.of("b", Integer.class);
@Mock
private Relation relation;
@Mock
private RelationalInput input;
@Test
public void testDictionaryA() {
mock();
CompressedRelation compressed = compress();
CompressedColumn<String> column = compressed.getColumn(0);
Dictionary<String> dictionary = column.getDictionary();
assertThat(dictionary.values()).hasSize(3);
assertThat(dictionary.values()).contains("foo");
assertThat(dictionary.values()).contains("bar");
assertThat(dictionary.values()).contains("baz");
assertThat(dictionary.getOrAdd("foo")).isEqualTo(0);
assertThat(dictionary.getOrAdd("bar")).isEqualTo(1);
assertThat(dictionary.getOrAdd("baz")).isEqualTo(2);
}
@Test
public void testDictionaryB() {
mock();
CompressedRelation compressed = compress();
CompressedColumn<Integer> column = compressed.getColumn(1);
Dictionary<Integer> dictionary = column.getDictionary();
assertThat(dictionary.values()).hasSize(2);
assertThat(dictionary.values()).contains(Integer.valueOf(2));
assertThat(dictionary.values()).contains(Integer.valueOf(1));
assertThat(dictionary.getOrAdd(Integer.valueOf(2))).isEqualTo(0);
assertThat(dictionary.getOrAdd(Integer.valueOf(1))).isEqualTo(1);
}
@Test
public void testDictionaryRecords() {
mock();
CompressedRelation compressed = compress();
DictionaryRecords dictionaryRecords = compressed.getDictionaryRecords();
assertThat(dictionaryRecords.getAll()).hasSize(3);
assertThat(dictionaryRecords.get(0).length).isEqualTo(2);
assertThat(dictionaryRecords.get(1)[1]).isNotEqualTo(dictionaryRecords.get(0)[1]);
assertThat(dictionaryRecords.get(1)[1]).isEqualTo(dictionaryRecords.get(2)[1]);
}
@Test
public void testIndexOf() {
mock();
CompressedRelation compressed = compress();
assertThat(compressed.indexOf(A)).isEqualTo(0);
assertThat(compressed.indexOf(B)).isEqualTo(1);
}
@Test(expected = RuntimeException.class)
public void testInputCloseException() throws InputCloseException {
doThrow(InputCloseException.class).when(input).close();
mock();
compress();
fail();
}
@Test(expected = RuntimeException.class)
public void testInputOpenException() throws InputOpenException {
doThrow(InputOpenException.class).when(relation).open();
compress();
fail();
}
@Test
public void testPliA() {
mock();
CompressedRelation compressed = compress();
CompressedColumn<String> column = compressed.getColumn(0);
PositionListIndex pli = column.getPli();
assertThat(pli.get(0)).hasSize(1);
assertThat(pli.get(1)).hasSize(1);
assertThat(pli.get(2)).hasSize(1);
assertThat(pli.get(0)).contains(Integer.valueOf(0));
assertThat(pli.get(1)).contains(Integer.valueOf(1));
assertThat(pli.get(2)).contains(Integer.valueOf(2));
}
@Test
public void testPliB() {
mock();
CompressedRelation compressed = compress();
CompressedColumn<Integer> column = compressed.getColumn(1);
PositionListIndex pli = column.getPli();
assertThat(pli.get(0)).hasSize(1);
assertThat(pli.get(1)).hasSize(2);
assertThat(pli.get(0)).contains(Integer.valueOf(0));
assertThat(pli.get(1)).contains(Integer.valueOf(1));
assertThat(pli.get(1)).contains(Integer.valueOf(2));
}
private CompressedRelation compress() {
return Compressor.builder()
.records(MapDictionaryRecords.builder())
.compress(relation);
}
private void mock() {
Schema schema = Schema.of(Arrays.asList(A, B));
Collection<Row> rows = ImmutableList.<Row>builder()
.add(Row.create(schema, ImmutableMap.of(A, "foo", B, Integer.valueOf(2))))
.add(Row.create(schema, ImmutableMap.of(A, "bar", B, Integer.valueOf(1))))
.add(Row.create(schema, ImmutableMap.of(A, "baz", B, Integer.valueOf(1))))
.build();
mockRelation(schema, rows);
}
private void mockRelation(Schema schema, Iterable<Row> rows) {
try {
when(relation.open()).thenReturn(input);
} catch (InputOpenException e) {
throw new RuntimeException(e);
}
when(input.iterator()).thenReturn(rows.iterator());
doCallRealMethod().when(input).forEach(any());
when(input.getSchema()).thenReturn(schema);
}
} | 34.051282 | 84 | 0.749435 |
e1dba80c747c93c5e25be26af0be0ced9ecd94ac | 11,760 | package com.eiualee.easyvalidate_compiler.processor;
import com.eiualee.easyvalidate_annotations.ValidateCheck;
import com.eiualee.easyvalidate_annotations.ValidateNull;
import com.eiualee.easyvalidate_annotations.ValidateRegular;
import com.eiualee.easyvalidate_compiler.AnnotationProcessor;
import com.eiualee.easyvalidate_compiler.bean.BaseValidateBean;
import com.eiualee.easyvalidate_compiler.bean.ValidateCheckBean;
import com.eiualee.easyvalidate_compiler.bean.ValidateNullBean;
import com.eiualee.easyvalidate_compiler.bean.ValidateRegularBean;
import com.eiualee.easyvalidate_compiler.impl.IProcessor;
import com.eiualee.easyvalidate_compiler.utils.C;
import com.eiualee.easyvalidate_compiler.utils.MapUtils;
import com.eiualee.easyvalidate_compiler.utils.Utils;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.FilerException;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
/**
* Created by liweihua on 2018/12/21.
*/
public class ValidateProcessor implements IProcessor {
AnnotationProcessor annotationProcessor;
@Override
public void process(RoundEnvironment roundEnv, AnnotationProcessor annotationProcessor) {
try {
this.annotationProcessor = annotationProcessor;
//用于缓存所有的Map 的 Key
Map<String, Element> useAnnoClassElementMap = new LinkedHashMap<>();
//根据注解获取所有的数据
Map<String, List<ValidateNullBean>> validateNullBeanMap = MapUtils.getAnnotationDataGroupByClassName(roundEnv, ValidateNull.class, useAnnoClassElementMap);
Map<String, List<ValidateCheckBean>> validateCheckBeanHashMap = MapUtils.getAnnotationDataGroupByClassName(roundEnv, ValidateCheck.class, useAnnoClassElementMap);
Map<String, List<ValidateRegularBean>> validateRegularBeanHashMap = MapUtils.getAnnotationDataGroupByClassName(roundEnv, ValidateRegular.class, useAnnoClassElementMap);
for (Element useAnnoClassElement : useAnnoClassElementMap.values()) {
//com.xxx.xxx.xxx.XXActivity
String useAnnoClassElementStr = useAnnoClassElement.toString();
TypeName ac_fra_typeName = annotationProcessor.getTypeName(useAnnoClassElementStr);
//创建类
TypeSpec.Builder tBuilder = TypeSpec.classBuilder(useAnnoClassElement.getSimpleName().toString() + "_Validate")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addSuperinterface(annotationProcessor.TN_IVALIDATE)
.addJavadoc(" @ 由apt自动生成,请勿编辑\n")
.addField(ac_fra_typeName, "target", Modifier.PRIVATE)
.addField(annotationProcessor.TN_LISTENER, "listener", Modifier.PRIVATE)
.addField(annotationProcessor.TN_VIEW, "sourse", Modifier.PRIVATE);
//创建构造体
MethodSpec constructorBuilder = getConstrutorBuilder(useAnnoClassElement, ac_fra_typeName);
tBuilder.addMethod(constructorBuilder);
//创建isEmptyValidate方法
MethodSpec isEmptyValidate = createValidateMethod(validateNullBeanMap.get(useAnnoClassElementStr), "isEmptyValidate");
tBuilder.addMethod(isEmptyValidate);
//创建isCheckValidate方法
MethodSpec isCheckValidate = createValidateMethod(validateCheckBeanHashMap.get(useAnnoClassElementStr), "isCheckValidate");
tBuilder.addMethod(isCheckValidate);
//创建isRegularValidate方法
MethodSpec isRegularValidate = createValidateMethod(validateRegularBeanHashMap.get(useAnnoClassElementStr), "isRegularValidate");
tBuilder.addMethod(isRegularValidate);
//创建unBind方法
tBuilder.addMethod(createUnBindMethod());
//创建isValidatePass方法
tBuilder.addMethod(createIsValidatePassMethod());
//创建setUnValidateListener方法
tBuilder.addMethod(createSetListener());
JavaFile javaFile = JavaFile.builder(annotationProcessor.mElements.getPackageOf(useAnnoClassElement).toString(), tBuilder.build()).build();
javaFile.writeTo(annotationProcessor.mFiler);
}
} catch (FilerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 创建setListener方法
*
* @return
*/
private MethodSpec createSetListener() {
return MethodSpec.methodBuilder("setUnValidateListener")
.addModifiers(Modifier.FINAL, Modifier.PUBLIC)
.addJavadoc("@ 控件验证不合法监听\n")
.addParameter(annotationProcessor.TN_LISTENER, "listener")
.addStatement("this.$N = $N", "listener", "listener")
.build();
}
/**
* 创建sValidatePassi方法
*
* @return
*/
private MethodSpec createIsValidatePassMethod() {
return MethodSpec.methodBuilder("isValidatePass")
.addAnnotation(ClassName.get(annotationProcessor.mElements.getTypeElement(C.UITHREAD)))
.addModifiers(Modifier.FINAL, Modifier.PUBLIC)
.addParameter(TypeName.INT, "plan")
.returns(TypeName.BOOLEAN)
.addJavadoc("@ 是否验证通过\n")
.addStatement("return isEmptyValidate(plan) && isCheckValidate(plan) && isRegularValidate(plan)")
.build();
}
/**
* 根据类的类型返回不同的构造体
*
* @param key
* @return
*/
private MethodSpec getConstrutorBuilder(Element key, TypeName act_fra_typeName) {
MethodSpec.Builder constructorBuilder = null;
constructorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC)
.addParameter(act_fra_typeName, "target")
.addParameter(annotationProcessor.TN_VIEW, "sourse")
.addStatement("this.$N = $N", "target", "target")
.addStatement("this.$N = $N", "sourse", Utils.isSubtypeOfType(key.asType(), C.ACTIVITY) ? "target.getWindow().getDecorView()" : "sourse");
return constructorBuilder.build();
}
/**
* 创建验证方法
*
* @param tList
* @param methodName
* @param <T>
* @return
*/
private <T extends BaseValidateBean> MethodSpec createValidateMethod(List<T> tList, String methodName) {
MethodSpec.Builder mBuilder = MethodSpec.methodBuilder(methodName)
.addJavadoc("@ 验证方法\n")
.returns(TypeName.BOOLEAN)
.addAnnotation(ClassName.get(annotationProcessor.mElements.getTypeElement(C.UITHREAD)))
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(TypeName.INT, "plan");
if (tList == null || tList.isEmpty()) {
return mBuilder.addStatement("return true").build();
}
//获取该集合中所有要用到的验证计划
Set<Integer> allPlan = getAllPlan(tList);
CodeBlock.Builder blockBuilder = CodeBlock.builder();
//根据计划写不同的代码
for (Integer plan : allPlan) {
blockBuilder.add("\nif(plan == $L){\n", plan);
for (T t : tList) {
//当被注解的元素没有使用该验证计划时,不进行代码注入
if (!t.getPlans().contains(plan)) {
continue;
}
if (t instanceof ValidateCheckBean) {
validateCheckCode((ValidateCheckBean) t, blockBuilder);
} else if (t instanceof ValidateNullBean) {
validateNullCode((ValidateNullBean) t, blockBuilder);
} else if (t instanceof ValidateRegularBean) {
validateRegularCode((ValidateRegularBean) t, blockBuilder);
}
}
blockBuilder.add(" return true;\n}");
}
blockBuilder.add("\nreturn true;\n");
mBuilder.addCode(blockBuilder.build());
return mBuilder.build();
}
/**
* 创建UnBind方法
*
* @return
*/
private MethodSpec createUnBindMethod() {
return MethodSpec.methodBuilder("unBind")
.addAnnotation(ClassName.get(annotationProcessor.mElements.getTypeElement(C.UITHREAD)))
.addJavadoc("@ 解绑\n")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("this.sourse = null")
.addStatement("this.target = null")
.build();
}
/**
* String VALIDATE_REGULAR_CODE = " if (!$T.getText(target.$N != null?target.$N:($T)sourse.findViewById($L)),matches($S)){" +
"\n $T.showShortToast($S);" +
"\n return false;" +
"\n }\n";
*/
/**
* 生成validateRegular代码
*
* @param validateRegularBean
* @param blockBuilder
*/
private void validateRegularCode(ValidateRegularBean validateRegularBean, CodeBlock.Builder blockBuilder) {
blockBuilder.add(
C.VALIDATE_REGULAR_CODE
, annotationProcessor.TN_EASY_VALIDATE
, validateRegularBean.getRegular()
, validateRegularBean.getFieldName()
, validateRegularBean.getFieldName()
, annotationProcessor.getTypeName(validateRegularBean.getElementType())
, validateRegularBean.getId()
, validateRegularBean.getId()
, validateRegularBean.getToast());
}
/**
* 生成validateNull代码
*
* @param validateNullBean
*/
private void validateNullCode(ValidateNullBean validateNullBean, CodeBlock.Builder blockBuilder) {
blockBuilder.add(
C.VALIDATE_NULL_CODE
, annotationProcessor.TN_TEXTUTILS
, validateNullBean.getFieldName()
, validateNullBean.getFieldName()
, annotationProcessor.getTypeName(validateNullBean.getElementType())
, validateNullBean.getId()
, validateNullBean.getId()
, validateNullBean.getToast());
}
/**
* 生成validateCheck代码
*
* @param validateCheckBean
*/
private void validateCheckCode(ValidateCheckBean validateCheckBean, CodeBlock.Builder blockBuilder) {
blockBuilder.add(
C.VALIDATE_CHECK_CODE
, validateCheckBean.getFieldName()
, validateCheckBean.isValidateState() ? "" : "!"
, validateCheckBean.getFieldName()
, validateCheckBean.isValidateState() ? "" : "!"
, annotationProcessor.getTypeName(validateCheckBean.getElementType())
, validateCheckBean.getId()
, validateCheckBean.getId()
, validateCheckBean.getToast());
}
/**
* 获取所有对象的验证计划总集合
*
* @param baseValidateBeans
* @return
*/
private Set<Integer> getAllPlan(List<? extends BaseValidateBean> baseValidateBeans) {
Set<Integer> integerSet = new LinkedHashSet<>();
for (BaseValidateBean validateBean : baseValidateBeans) {
integerSet.addAll(validateBean.getPlans());
}
return integerSet;
}
}
| 40.273973 | 180 | 0.637245 |
2455dd740a73b3e1e31e1d5997d56381fb30f81e | 291 | package tn.insat.rest.services;
import tn.insat.rest.entities.UserTest;
import java.util.List;
/**
* Created by zied on 20/02/2018.
*/
public interface UserTestService {
public List<UserTest> getUserTestsById(Integer userId);
public UserTest addUserTest(UserTest userTest);
}
| 18.1875 | 59 | 0.749141 |
0789e2bed0799d3eb464bc4799994fcdeae86271 | 700 | package demo3.service;
import demo3.dao.UserDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author : CodeWater
* @create :2022-04-05-19:27
* @Function Description :
*/
@Component(value = "userService")
public class UserService {
@Value(value = "abc")//对属性赋值
private String name;
// @Autowired
// @Qualifier( value="userDaoImpl1" )
// private UserDao userDao;
// @Resource//根据类型
@Resource(name = "userDaoImpl1") //根据名称
private UserDao userDao;
public void add() {
System.out.println("service add ...." + name);
userDao.add();
}
}
| 22.580645 | 58 | 0.667143 |
85e4191c921335ea4b214a021ca2bc44d4ac4eeb | 1,899 | package ru.majordomo.hms.personmgr.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
import java.util.Set;
import ru.majordomo.hms.personmgr.model.service.AccountService;
public interface AccountServiceRepository extends MongoRepository<AccountService,String> {
AccountService findOneByPersonalAccountId(String personalAccountId);
AccountService findByPersonalAccountIdAndId(String personalAccountId, String id);
AccountService findOneByPersonalAccountIdAndServiceId(String personalAccountId, String serviceId);
List<AccountService> findByPersonalAccountId(String personalAccountId);
List<AccountService> findByPersonalAccountIdAndEnabled(String personalAccountId, boolean enabled);
Page<AccountService> findByPersonalAccountId(String personalAccountId, Pageable pageable);
List<AccountService> findByPersonalAccountIdAndServiceId(String personalAccountId, String serviceId);
List<AccountService> findByPersonalAccountIdAndServiceIdAndEnabled(String personalAccountId, String serviceId, boolean enabled);
boolean existsByPersonalAccountIdAndServiceIdAndEnabled(String personalAccountId, String serviceId, boolean enabled);
List<AccountService> findByServiceId(String serviceId);
List<AccountService> findByServiceIdAndEnabled(String serviceId, boolean enabled);
void deleteByPersonalAccountId(String personalAccountId);
boolean existsByPersonalAccountIdAndServiceId(String personalAccountId, String serviceId);
void deleteByPersonalAccountIdAndId(String personalAccountId, String id);
void deleteByPersonalAccountIdAndServiceId(String personalAccountId, String serviceId);
List<AccountService> findByPersonalAccountIdAndServiceIdIn(String personalAccountId, Set<String> serviceIds);
} | 65.482759 | 132 | 0.850974 |
6c5b609290bd9ec3d3d9fb41d861cb7576451cfa | 667 | package com.techmonad.payment;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableAutoConfiguration
@EnableDiscoveryClient
@SpringBootApplication
public class PaymentServiceApplication {
public static void main(String[] args) {
// Tell server to look for payment-service.properties or payment-service.yml
//System.setProperty("spring.config.name", "payment-service");
SpringApplication.run(PaymentServiceApplication.class, args);
}
}
| 31.761905 | 78 | 0.833583 |
cc3e9bccc5567f829fcdac03e8d9989e10ea8445 | 3,213 | /*
* 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 Projeto01;
import java.util.ArrayList;
/**
* @author joao
*/
public class Lista {
No ini;
// Criar uma lista encadeada vazia
public Lista() {
this.ini = null;
}
public boolean vazia() {
return ini == null;
}
@Override
public String toString() {
String strLista = "";
No temp = ini;
while (temp != null) {
strLista += temp.getElemento() + " ";
temp = temp.getProx();
}
return strLista;
}
public void insereInicio(String elemento) {
No novo = new No(elemento, ini);
ini = novo;
}
public int buscaPosicaoDoElemento(String x) {
No temp = ini;
int cont = 0;
while (temp != null) {
cont++;
if (temp.getElemento().equals(x)) {
return cont;
}
temp = temp.getProx();
}
cont = 0;
return cont;
}
public String buscaElementoPelaPosicao(int posicao) {
No no = ini;
int cont = 1;
while (no != null) {
if (cont == posicao) {
return no.getElemento();
}
no = no.getProx();
cont++;
}
return null;
}
/**
* Troca a posicao de um elemento da lista para a primeira posicao se ele
* estiver na lista.
*
* @param elemento
* @return posicao - se o elemento estiver na lista; 0 - se nao estiver.
*/
public int trocaParaInicio(String elemento) {
No no = buscaLinear(elemento);
int posicao = buscaPosicaoDoElemento(elemento);
if (no != null) {
if (no != ini) {
ordenar(no);
no.setProx(ini);
ini = no;
}
}
return posicao;
}
public void ordenar(No no) {
No aux = ini;
while (aux != null) {
if (aux.getProx() == no && no.getProx() != null) {
aux.setProx(no.getProx());
return;
}
aux = aux.getProx();
}
}
// public String trocaParaInicio(String elemento) {
// String posicao = "1";
//
// if (no != null) {
// if (no != ini) {
// posicao = String.valueOf(buscaPosicaoDoElemento(elemento));
//
// No aux = no.getProx();
// no.setProx(no.getProx().getProx());
//
// aux.setProx(ini);
// ini = aux;
//
// return posicao;
// } else {
// return posicao;
// }
// }
//
// insereInicio(elemento);
//
// return elemento;
// }
public No buscaLinear(String elemento) {
No no = ini;
while (no != null) {
if (no.getElemento().equals(elemento)) {
return no;
}
no = no.getProx();
}
return null;
}
}
| 21.709459 | 79 | 0.460629 |
90a870396454136132ac18c0cfa7b2a81b70a0c3 | 200 | package com.stardust.easyassess.assessment.services;
import com.stardust.easyassess.assessment.models.ArticleReader;
public interface ArticleReaderService extends EntityService<ArticleReader> {
}
| 22.222222 | 76 | 0.85 |
2379b310faceef315fa8bb5abc4745aefdc73eb4 | 1,393 | /*
* ----------------------------------------
* Jenkins Test Tracker Connection
* ----------------------------------------
* Produced by Dan Grew
* 2017
* ----------------------------------------
*/
package uk.dangrew.jtt.connection.login;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.TextField;
/**
* The {@link TextFieldEventFilter} provides an {@link EventHandler} for filtering button presses
* on a {@link javafx.scene.control.Dialog} by consuming the event if input is invalid.
*/
public class TextFieldEventFilter implements EventHandler< ActionEvent > {
private final Set< TextField > fields;
/**
* Constructs a new {@link TextFieldEventFilter}.
* @param fields the {@link TextField} to validate.
*/
public TextFieldEventFilter( TextField... fields ) {
this.fields = new LinkedHashSet<>( Arrays.asList( fields ) );
}//End Constructor
/**
* {@inheritDoc}
*/
@Override public void handle( ActionEvent event ) {
for ( TextField field : fields ) {
String fieldText = field.getText();
if ( fieldText == null || fieldText.trim().length() == 0 ) {
event.consume();
return;
}
}
}//End Method
}//End Class
| 28.428571 | 97 | 0.58794 |
9e7aea18e3aedef85454b61a01145fcc5ee636cb | 161 | package eu.kerdev.testApp.model;
/**
* Amount type used to define the type of billing
* @author Michal Jendrzejek
*/
public enum AmountType {
NET, BRU
}
| 16.1 | 49 | 0.701863 |
90895d9a40586b294ef59f2e22279f3ce1b15c7b | 1,959 | package org.nodes.random;
import static nl.peterbloem.kit.Series.series;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.nodes.DTGraph;
import org.nodes.Graph;
import org.nodes.Graphs;
import org.nodes.MapUTGraph;
import org.nodes.Node;
import org.nodes.UTGraph;
import nl.peterbloem.kit.Functions;
import nl.peterbloem.kit.Global;
import nl.peterbloem.kit.Series;
public class DBAGenerator
{
private static final String LABEL = "x";
private int initial;
private int attach;
private DTGraph<String, String> graph;
private List<Node<String>> probabilities = new ArrayList<Node<String>>();
private double sum = 0.0;
public DBAGenerator(int initial, int attach)
{
this.initial = initial;
this.attach = attach;
graph = Graphs.dk(initial, LABEL);
for(int i : series(initial))
for(int j : series(initial - 1))
probabilities.add(graph.nodes().get(i));
}
/**
* Add a node to the graph.
*
* Each node is added to m distinct, pre-drawn other nodes, where the
* probability of a node being drawn is proportional to its number of links.
*
* @return The new node added to the graph.
*/
public Node<String> newNode()
{
Node<String> node = graph.add(LABEL);
for(Node<String> neighbor : sample(probabilities, attach))
{
if(Global.random().nextBoolean())
node.connect(neighbor);
else
neighbor.connect(node);
probabilities.add(neighbor);
probabilities.add(node);
}
return node;
}
/**
* Returns k distinct random samples from 'values'
*
* @param values
*/
private static <P> Set<P> sample(List<P> values, int k)
{
Set<P> set = new HashSet<P>();
while (set.size() < k)
set.add(values.get(Global.random().nextInt(values.size())));
return set;
}
public void iterate(int n)
{
for(int i : series(n))
newNode();
}
public DTGraph<String, String> graph()
{
return graph;
}
}
| 20.195876 | 77 | 0.683002 |
142b0a4bb15e851d4becb97f1f4e8e83a177260b | 4,627 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2019 The ZAP Development Team
*
* 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.zaproxy.zap.extension.fuzz.payloads.ui.processors;
import java.nio.charset.Charset;
import javax.swing.GroupLayout;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.parosproxy.paros.Constant;
import org.zaproxy.zap.extension.fuzz.payloads.DefaultPayload;
import org.zaproxy.zap.extension.fuzz.payloads.processor.AbstractStringHashProcessor;
import org.zaproxy.zap.extension.fuzz.payloads.ui.processors.AbstractStringHashProcessorUIPanel.AbstractStringHashProcessorUI;
public abstract class AbstractStringHashProcessorUIPanel<
T1 extends AbstractStringHashProcessor,
T2 extends AbstractStringHashProcessorUI<T1>>
extends AbstractCharsetProcessorUIPanel<DefaultPayload, T1, T2> {
protected static final String UPPER_CASE_FIELD_LABEL =
Constant.messages.getString("fuzz.payload.processor.hash.upperCase.label");
private JLabel upperCaseLabel;
private JCheckBox upperCaseCheckBox;
public AbstractStringHashProcessorUIPanel() {}
protected JLabel getUpperCaseLabel() {
if (upperCaseLabel == null) {
upperCaseLabel = new JLabel(UPPER_CASE_FIELD_LABEL);
upperCaseLabel.setLabelFor(getUpperCaseCheckBox());
}
return upperCaseLabel;
}
protected JCheckBox getUpperCaseCheckBox() {
if (upperCaseCheckBox == null) {
upperCaseCheckBox = new JCheckBox();
}
return upperCaseCheckBox;
}
@Override
public void clear() {
super.clear();
getUpperCaseCheckBox().setSelected(false);
}
@Override
public void setPayloadProcessorUI(T2 payloadProcessorUI) {
super.setPayloadProcessorUI(payloadProcessorUI);
getUpperCaseCheckBox().setSelected(payloadProcessorUI.isUpperCase());
}
@Override
protected JPanel createDefaultFieldsPanel() {
JPanel fieldsPanel = new JPanel();
GroupLayout layout = new GroupLayout(fieldsPanel);
fieldsPanel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(
layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(getCharsetLabel())
.addComponent(getUpperCaseLabel()))
.addGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(getCharsetComboBox())
.addComponent(getUpperCaseCheckBox())));
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(
layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(getCharsetLabel())
.addComponent(getCharsetComboBox()))
.addGroup(
layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(getUpperCaseLabel())
.addComponent(getUpperCaseCheckBox())));
return fieldsPanel;
}
public abstract static class AbstractStringHashProcessorUI<
T extends AbstractStringHashProcessor>
extends AbstractCharsetProcessorUI<DefaultPayload, T> {
private final boolean upperCase;
public AbstractStringHashProcessorUI(Charset charset, boolean upperCase) {
super(charset);
this.upperCase = upperCase;
}
public boolean isUpperCase() {
return upperCase;
}
}
}
| 38.239669 | 126 | 0.641452 |
a3b7f9270827d3aef2cb3ed339ebc9b9c7eb63f0 | 9,484 | /*
* Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.pinpoint.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/ExportJobResource" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ExportJobResource implements Serializable, Cloneable, StructuredPojo {
/**
* The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access to the Amazon S3 location that
* endpoints will be exported to.
*/
private String roleArn;
/**
* A URL that points to the location within an Amazon S3 bucket that will receive the export. The location is
* typically a folder with multiple files. The URL should follow this format: s3://bucket-name/folder-name/
*
* Amazon Pinpoint will export endpoints to this location.
*/
private String s3UrlPrefix;
/** The ID of the segment to export endpoints from. If not present, all endpoints are exported. */
private String segmentId;
/**
* The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access to the Amazon S3 location that
* endpoints will be exported to.
*
* @param roleArn
* The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access to the Amazon S3 location
* that endpoints will be exported to.
*/
public void setRoleArn(String roleArn) {
this.roleArn = roleArn;
}
/**
* The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access to the Amazon S3 location that
* endpoints will be exported to.
*
* @return The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access to the Amazon S3
* location that endpoints will be exported to.
*/
public String getRoleArn() {
return this.roleArn;
}
/**
* The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access to the Amazon S3 location that
* endpoints will be exported to.
*
* @param roleArn
* The Amazon Resource Name (ARN) of an IAM role that grants Amazon Pinpoint access to the Amazon S3 location
* that endpoints will be exported to.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ExportJobResource withRoleArn(String roleArn) {
setRoleArn(roleArn);
return this;
}
/**
* A URL that points to the location within an Amazon S3 bucket that will receive the export. The location is
* typically a folder with multiple files. The URL should follow this format: s3://bucket-name/folder-name/
*
* Amazon Pinpoint will export endpoints to this location.
*
* @param s3UrlPrefix
* A URL that points to the location within an Amazon S3 bucket that will receive the export. The location is
* typically a folder with multiple files. The URL should follow this format: s3://bucket-name/folder-name/
*
* Amazon Pinpoint will export endpoints to this location.
*/
public void setS3UrlPrefix(String s3UrlPrefix) {
this.s3UrlPrefix = s3UrlPrefix;
}
/**
* A URL that points to the location within an Amazon S3 bucket that will receive the export. The location is
* typically a folder with multiple files. The URL should follow this format: s3://bucket-name/folder-name/
*
* Amazon Pinpoint will export endpoints to this location.
*
* @return A URL that points to the location within an Amazon S3 bucket that will receive the export. The location
* is typically a folder with multiple files. The URL should follow this format:
* s3://bucket-name/folder-name/
*
* Amazon Pinpoint will export endpoints to this location.
*/
public String getS3UrlPrefix() {
return this.s3UrlPrefix;
}
/**
* A URL that points to the location within an Amazon S3 bucket that will receive the export. The location is
* typically a folder with multiple files. The URL should follow this format: s3://bucket-name/folder-name/
*
* Amazon Pinpoint will export endpoints to this location.
*
* @param s3UrlPrefix
* A URL that points to the location within an Amazon S3 bucket that will receive the export. The location is
* typically a folder with multiple files. The URL should follow this format: s3://bucket-name/folder-name/
*
* Amazon Pinpoint will export endpoints to this location.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ExportJobResource withS3UrlPrefix(String s3UrlPrefix) {
setS3UrlPrefix(s3UrlPrefix);
return this;
}
/**
* The ID of the segment to export endpoints from. If not present, all endpoints are exported.
*
* @param segmentId
* The ID of the segment to export endpoints from. If not present, all endpoints are exported.
*/
public void setSegmentId(String segmentId) {
this.segmentId = segmentId;
}
/**
* The ID of the segment to export endpoints from. If not present, all endpoints are exported.
*
* @return The ID of the segment to export endpoints from. If not present, all endpoints are exported.
*/
public String getSegmentId() {
return this.segmentId;
}
/**
* The ID of the segment to export endpoints from. If not present, all endpoints are exported.
*
* @param segmentId
* The ID of the segment to export endpoints from. If not present, all endpoints are exported.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ExportJobResource withSegmentId(String segmentId) {
setSegmentId(segmentId);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRoleArn() != null)
sb.append("RoleArn: ").append(getRoleArn()).append(",");
if (getS3UrlPrefix() != null)
sb.append("S3UrlPrefix: ").append(getS3UrlPrefix()).append(",");
if (getSegmentId() != null)
sb.append("SegmentId: ").append(getSegmentId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ExportJobResource == false)
return false;
ExportJobResource other = (ExportJobResource) obj;
if (other.getRoleArn() == null ^ this.getRoleArn() == null)
return false;
if (other.getRoleArn() != null && other.getRoleArn().equals(this.getRoleArn()) == false)
return false;
if (other.getS3UrlPrefix() == null ^ this.getS3UrlPrefix() == null)
return false;
if (other.getS3UrlPrefix() != null && other.getS3UrlPrefix().equals(this.getS3UrlPrefix()) == false)
return false;
if (other.getSegmentId() == null ^ this.getSegmentId() == null)
return false;
if (other.getSegmentId() != null && other.getSegmentId().equals(this.getSegmentId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRoleArn() == null) ? 0 : getRoleArn().hashCode());
hashCode = prime * hashCode + ((getS3UrlPrefix() == null) ? 0 : getS3UrlPrefix().hashCode());
hashCode = prime * hashCode + ((getSegmentId() == null) ? 0 : getSegmentId().hashCode());
return hashCode;
}
@Override
public ExportJobResource clone() {
try {
return (ExportJobResource) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.pinpoint.model.transform.ExportJobResourceMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| 39.190083 | 137 | 0.654154 |
f14d15b0408f8713019348b73cbc7afda0b78859 | 2,144 | /**
* Implementation of a Binomial Tree
*
* Lily Xu
* January 2017
*/
public class BinomialTree {
private Integer key;
private BinomialTree parent = null;
private BinomialTree child = null;
private BinomialTree left = null;
private BinomialTree right = null;
private int degree;
/**
* BinomialTree constructor
*/
public BinomialTree(Integer key) {
this.key = key;
this.degree = 0;
this.left = this;
this.right = this;
}
/**
* Add right sibling
*/
public void addRight(BinomialTree tree) {
tree.setLeft(this);
tree.setRight(this.right);
this.right.setLeft(tree);
this.setRight(tree);
}
/**
* Add child to tree
*/
public void addChild(BinomialTree tree) {
if (this.child == null) {
this.child = tree;
} else {
this.child.addRight(tree);
}
tree.setParent(this);
this.degree++;
}
/**
* Remove tree from left/right connections
*
* Returns true if successfully removed
* false if it was not linked to anything
*/
public boolean remove() {
// no other trees
if (this.right == this && this.left == this) {
return false;
} else {
this.left.setRight(this.right);
this.right.setLeft(this.left);
return true;
}
}
public String toString() {
return "key: " + key + ", degree: " + degree;
}
// ---------------------------------------------
// getters and setters
public void setKey(Integer key) {
this.key = key;
}
public void setParent(BinomialTree tree) {
this.parent = tree;
}
public void setChild(BinomialTree tree) {
this.child = tree;
}
public void setRight(BinomialTree tree) {
this.right = tree;
}
public void setLeft(BinomialTree tree) {
this.left = tree;
}
public void setDegree(int degree) {
this.degree = degree;
}
public BinomialTree getParent() {
return this.parent;
}
public BinomialTree getChild() {
return this.child;
}
public BinomialTree getLeft() {
return this.left;
}
public BinomialTree getRight() {
return this.right;
}
public Integer getKey() {
return this.key;
}
public int getDegree() {
return this.degree;
}
}
| 16.366412 | 50 | 0.628731 |
b0dbfdf56bc19ce1287b66ebf0b03cde07d50802 | 20,733 | /*******************************************************************************
* Copyright (C) 2018-2019 Arpit Shah and Artos Contributors
*
* 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 artos.dashboard.utils;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
/**
*
*
*
*/
public class Transform {
static final String HEXES = "0123456789ABCDEF";
static final ByteOrder BYTE_ORDER_DEFAULT = ByteOrder.LITTLE_ENDIAN;
// ===================================================================
// Bytes related manipulation
// ===================================================================
/**
* concatenates multiple byte arrays.
*
* @param arrays = byte arrays
* @return concatenated byte array
*/
public byte[] concat(byte[]... arrays) {
int totalLength = 0;
for (byte[] array : arrays) {
totalLength += array.length;
}
byte[] result = new byte[totalLength];
int offset = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
/**
* concatenate chain of single byte in order it was provided in.
*
* @param data = byte(s) in sequence
* @return concatenated byte array
*/
@SuppressWarnings("unused")
public byte[] concat(byte... data) {
int totalLength = 0;
for (byte currentByte : data) {
totalLength += 1;
}
byte[] result = new byte[totalLength];
int offset = 0;
for (byte currentByte : data) {
result[offset] = currentByte;
offset++;
}
return result;
}
/**
* concatenates byte array with subsequent single byte in order it was provided in.
*
* @param byteArray = first byte array
* @param rest = following byte array
* @return = concatenated byte array
*/
@SuppressWarnings("unused")
public byte[] concat(byte[] byteArray, byte... rest) {
int totalLength = byteArray.length;
for (byte currentByte : rest) {
totalLength += 1;
}
byte[] result = Arrays.copyOf(byteArray, totalLength);
int offset = byteArray.length;
for (byte currentByte : rest) {
result[offset] = currentByte;
offset++;
}
return result;
}
/**
* concatenates byte with subsequent byte arrays in order it was provided in.
*
* @param data = first byte
* @param rest = following byte array
* @return = concatenated byte array
*/
public byte[] concat(byte data, byte[]... rest) {
int totalLength = 1;
for (byte[] array : rest) {
totalLength += array.length;
}
byte[] result = new byte[totalLength];
result[0] = data;
int offset = 1;
for (byte[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
/**
* Converts Byte to Hex String
*
* <PRE>
* Example:
* Sample : bytesToHexString((byte)0xFF);
* Result : FF
* </PRE>
*
* @param data = data to be converted
* @return Hex formatted string
*/
public String bytesToHexString(byte data) {
return bytesToHexString(data, false);
}
/**
* Converts Bytes to Hex String
*
* <PRE>
* Example:
* Sample : bytesToHexString(new byte[]{0x01, 0x02, 0xFF});
* Result : 0102FF
* </PRE>
*
* @param data = data to be converted
* @return Hex formatted string
*/
public String bytesToHexString(byte[] data) {
return bytesToHexString(data, false);
}
/**
* Converts Bytes to Hex String
*
* <PRE>
* Example:
* Sample : bytesToHexString(new byte[]{0x01, 0x02, 0xFF}, true);
* Result : [3][01 02 FF]
* Sample : bytesToHexString(new byte[]{0x01, 0x02, 0xFF}, false);
* Result : 0102FF
* </PRE>
*
* @param data = data to be converted
* @param bDisplaySize = true/false
* @return Hex formatted string
*/
public String bytesToHexString(byte[] data, boolean bDisplaySize) {
if (null == data) {
throw new NullPointerException();
}
StringBuilder hex = new StringBuilder();
if (bDisplaySize) {
hex.append("[" + data.length + "][");
}
int count = 1;
for (byte b : data) {
hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
if (bDisplaySize && count < data.length) {
hex.append(" ");
}
count++;
}
if (bDisplaySize) {
hex.append("]");
}
return hex.toString();
}
/**
* Converts Byte to Hex String
*
* <PRE>
* Example:
* Sample : bytesToHexString((byte)0xFF, true);
* Result : [1][FF]
* Sample : bytesToHexString((byte)0xFF, false);
* Result : FF
* </PRE>
*
* @param data = data to be converted
* @param bDisplaySize = true/false
* @return Hex formatted string
*/
public String bytesToHexString(byte data, boolean bDisplaySize) {
return bytesToHexString(new byte[] { data }, bDisplaySize);
}
/**
* <PRE>
* Sample : bytesToAscii(new byte[]{(byte)0x54,(byte)0x45,(byte)0x53,(byte)0x54});
* Answer : TEST
* </PRE>
*
* @param data = data to be converted
* @return = Ascii formatted String
* @throws UnsupportedEncodingException Exception is thrown if invalid input is provided
*/
public String bytesToAscii(byte[] data) throws UnsupportedEncodingException {
return new String(data, "UTF-8");
}
/**
* <PRE>
* Sample : bytesToAscii((byte)0x54);
* Answer : T
* </PRE>
*
* @param data = data to be converted
* @return = Ascii formatted String
* @throws Exception = Exception is returned if invalid input data is provided
*/
public String bytesToAscii(byte data) throws Exception {
return bytesToAscii(new byte[] { data });
}
/**
*
* @param byteArray Reads the first eight bytes, composing them into a long value according to the byte order
* @return long value
*/
public long bytesToLong(byte[] byteArray) {
return bytesToLong(byteArray, BYTE_ORDER_DEFAULT);
}
/**
* <pre>
* Sample : bytesToLong(new byte[]{0D, E0, B6, B3, A7, 63, FF, FF}, ByteOrder.BIG_ENDIAN);
* Answer : 999999999999999999
* </pre>
*
* @param bytes = data to be converted
* @param bo byte order before converting it to long
* @return = long formatted data
*/
public long bytesToLong(byte[] bytes, ByteOrder bo) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.order(bo);
return buffer.getLong();
}
/**
* <pre>
* Sample : bytesToDecimals(new byte[]{00, 00, 00, 03});
* Answer : 3
* </pre>
*
* @param bytes = data to be converted
* @return = long formatted data
*/
public long bytesToDecimals(byte[] bytes) {
return bytesToDecimals(bytes, ByteOrder.BIG_ENDIAN);
}
/**
* <pre>
* Sample : bytesToDecimals(new byte[]{00, 00, 00, 03}, ByteOrder.BIG_ENDIAN);
* Sample : bytesToDecimals(new byte[]{03, 00, 00, 00}, ByteOrder.LITTLE_ENDIAN);
* Answer : 3
* </pre>
*
* @param bytes = data to be converted
* @param bo byte order before converting it to long
* @return = long formatted data
*/
public long bytesToDecimals(byte[] bytes, ByteOrder bo) {
int size = 8;
byte[] temp = new byte[size];
Arrays.fill(temp, (byte) 0x00);
if (bo == ByteOrder.BIG_ENDIAN) {
for (int i = bytes.length - 1; i >= 0; i--) {
temp[size - 1] = bytes[i];
size--;
}
} else {
for (int i = 0; i < bytes.length; i++) {
temp[i] = bytes[i];
}
}
return bytesToLong(temp, bo);
}
/**
* <pre>
* Sample : bytesToInteger(new byte[]{00, 00, 00, 03}, ByteOrder.BIG_ENDIAN);
* Answer : 3
* </pre>
*
* @param bytes = data to be converted
* @param bo byte order before converting it to long
* @return = integer formatted data
*/
public int bytesToInteger(byte[] bytes, ByteOrder bo) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.order(bo);
return buffer.getInt();
}
/**
* @deprecated we recommend to use {@link #bytesToShort(byte[], ByteOrder)} instead
* @param bytes Byte array
* @param bo Byte order
* @return Integer value
*/
@Deprecated
public int bytes2ToInt(byte[] bytes, ByteOrder bo) {
return bytesToShort(bytes, bo);
}
/**
*
* @param bytes Byte array
* @param bo Byte order
* @return Short value
*/
public short bytesToShort(byte[] bytes, ByteOrder bo) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.order(bo);
return buffer.getShort();
}
/**
* Generates requested number of random bytes. Uses SecureRandom function
*
* @param numberOfBytes Number of bytes
* @return random number byte array
*/
public byte[] generateRandomBytes(int numberOfBytes) {
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[numberOfBytes];
random.nextBytes(bytes);
return bytes;
}
/**
* Reverse order of bytes
*
* @param data Byte array
* @return reversed byte array
*/
public byte[] bytesReverseOrder(byte[] data) {
byte[] reverseData = new byte[data.length];
int j = data.length - 1;
for (int i = 0; i < data.length; i++) {
reverseData[j] = data[i];
j--;
}
return reverseData;
}
/**
*
* @param list List of byte
* @return byte array
*/
public byte[] listToByteArray(List<Byte> list) {
byte[] byteArray = new byte[list.size()];
for (int i = 0; i < list.size(); i++) {
byteArray[i] = list.get(i).byteValue();
}
return byteArray;
}
// ===================================================================
// Bits related manipulation
// ===================================================================
/**
* Returns Low Nibble of the byte.
*
* <PRE>
* Sample : getLowNibble((byte)0xFF)
* Answer : 0xF0
* </PRE>
*
* @param data Byte value
* @return Low Nibble in byte format
*/
public byte getLowNibble(byte data) {
byte lowNibble = (byte) (data & 0x0F);
return lowNibble;
}
/**
* Returns High Nibble of the byte.
*
* <PRE>
* Sample : getLowNibble((byte)0xFF)
* Answer : 0x0F
* </PRE>
*
* @param data Byte Value
* @return High Nibble in byte format
*/
public byte getHighNibble(byte data) {
byte lowNibble = (byte) ((data >> 4) & 0x0F);
return lowNibble;
}
/**
* Sets Particular bit of the byte to high
*
* @param data Byte Value
* @param pos Bit position
* @return Byte with set bit
*/
public byte setBitOfTheByte(byte data, int pos) {
return (byte) (data | (1 << pos));
}
/**
* Sets Particular bit of the byte to low
*
* @param data Byte Value
* @param pos Bit Position
* @return Byte with cleated bit
*/
public byte clearBitOfTheByte(byte data, int pos) {
return (byte) (data & ~(1 << pos));
}
/**
* Toggles particular bit of the byte
*
* @param data Byte value
* @param pos Bit position
* @return Byte with toogled bit
*/
public byte toogleBitOfTheByte(byte data, int pos) {
return (byte) (data ^ (1 << pos));
}
/**
* Returns particular bit of the byte
*
* @param data Byte value
* @param pos Bit Position
* @return Value of the Bit (1 or 0)
*/
public int getBitOfTheByte(byte data, int pos) {
return 0 != (data & (0x01 << pos)) ? 1 : 0;
}
public boolean isBitSet(byte data, int pos) {
if (0 != getBitOfTheByte(data, pos)) {
return true;
}
return false;
}
// ===================================================================
// String related manipulation
// ===================================================================
public byte[] strToByteArray(String str) {
return str.getBytes();
}
public byte strHexToByte(String strHex) {
if (strHex.length() != 2) {
throw new IllegalArgumentException("Input string must only contain 2 char");
}
return (strHexToByteArray(strHex)[0]);
}
public byte[] strHexToByteArray(String strHex) {
return strHexToByteArray(strHex, true);
}
public byte[] strHexToByteArray(String strHex, boolean removeWhiteSpaceChar) {
String s = strHex;
if (removeWhiteSpaceChar) {
s = strHex.replaceAll("\\s", "");
}
if ((s.length() % 2) != 0) {
throw new IllegalArgumentException("Input string must contain an even number of characters");
}
byte data[] = new byte[s.length() / 2];
for (int i = 0; i < s.length(); i += 2) {
data[i / 2] = (Integer.decode("0x" + s.charAt(i) + s.charAt(i + 1))).byteValue();
}
return data;
}
public byte[] strAsciiToByteArray(String strAscii) {
return strAscii.getBytes();
}
public int strToInt(String string) {
return Integer.parseInt(string);
}
/**
* Converts String Hex to ASCII
*
* @param strHex Hex formatter string
* @return ASCII String
* @throws UnsupportedEncodingException Exception is thrown if invalid input is provided
*/
public String strHexToAscii(String strHex) throws UnsupportedEncodingException {
if (strHex == null || strHex.length() % 2 != 0) {
throw new RuntimeException("Invalid data, null or odd length");
}
int len = strHex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(strHex.charAt(i), 16) << 4) + Character.digit(strHex.charAt(i + 1), 16));
}
return bytesToAscii(data);
}
/**
*
* @param asciiValue ASCII string
* @return Hex String
*/
public String asciiToHexString(String asciiValue) {
String result = "";
byte[] asciiArray = asciiValue.getBytes();
for (byte s : asciiArray) {
result += String.format("%02x", s);
}
return result;
}
public String strEscapeForXML(String input) {
StringBuilder builder = new StringBuilder();
for (int index = 0; index < input.length(); index++) {
char chr = input.charAt(index);
if (chr == '<') {
builder.append("<");
} else if (chr == '>') {
builder.append(">");
} else if (chr == '&') {
builder.append("&");
} else if (chr == '\'') {
builder.append("'");
} else if (chr == '"') {
builder.append(""");
} else {
builder.append(chr);
}
}
return builder.toString();
}
// ===================================================================
// Long related manipulation
// ===================================================================
public byte[] longTo8Bytes(long x, ByteOrder bo) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.order(bo);
buffer.putLong(x);
return buffer.array();
}
// ===================================================================
// Integer related manipulation
// ===================================================================
public boolean isInteger(String str) {
try {
Integer.parseInt(str);
} catch (NumberFormatException e) {
return false;
}
return true;
}
public byte[] intToByteArray(int x, ByteOrder bo) {
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.order(bo);
buffer.putInt(x);
return buffer.array();
}
public byte[] intToByteArray(int x) {
return intToByteArray(x, BYTE_ORDER_DEFAULT);
}
public byte intToByte(int x) {
return (byte) x;
}
public String intToString(int x) {
return Integer.toString(x);
}
/**
* Returns fix length string regardless of integer value
*
* @param nNumber Integer value
* @param nFixLenght String length
* @return Fix length string
*/
public String intToFixLengthString(int nNumber, int nFixLenght) {
String numberAsString = String.format("%0" + nFixLenght + "d", nNumber);
return numberAsString;
}
// ===================================================================
// Boolean related manipulation
// ===================================================================
/**
*
* @param b Boolean value
* @return integer representation of boolean value
*/
public int booleanToInt(boolean b) {
return b ? 1 : 0;
}
public String booleanToStr(boolean b) {
return b ? "1" : "0";
}
public String booleanToStringBoolean(boolean b) {
return String.valueOf(b);
}
public boolean stringToBoolean(String str) throws Exception {
if (str.trim().equals("1") || str.trim().toLowerCase().equals("true")) {
return true;
} else if (str.trim().equals("0") || str.trim().toLowerCase().equals("false")) {
return false;
}
throw new Exception("INVALID INPUT");
}
// *******************************************************************************************
// Time related manipulation
// *******************************************************************************************
/**
* MilliSecondsToFormattedDate("dd-MM-yyyy hh:mm", System.milliseconds())
*
* @param dateFormat the pattern describing the date and time format
* @param timeInMilliseconds EPoch time value
* @return date formatter with given pattern
*/
public String MilliSecondsToFormattedDate(String dateFormat, long timeInMilliseconds) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeInMilliseconds);
return simpleDateFormat.format(calendar.getTime());
}
public long getCurrentEPOCHTime() throws Exception {
Date date = new Date();
return getEPOCHTime(date);
}
public long getEPOCHTime(Date date) throws Exception {
return date.getTime() / 1000;
}
@SuppressWarnings("deprecation")
public long getEPOCHTime(String timeddMMyyyyHHmmss) throws Exception {
// String str = "Jun 13 2003 23:11:52.454";
SimpleDateFormat df = new SimpleDateFormat("ddMMyyyyHHmmss");
Date date = df.parse(timeddMMyyyyHHmmss);
// EPOCH returns time in milliseconds so divide by 1000
// System.out.println("EPOCHTime :" +
// ((date.getTime()-date.getTimezoneOffset()) / 1000));
return ((date.getTime() - date.getTimezoneOffset()) / 1000);
}
public Calendar getDateFromEPOCHTime(long epochTime) throws Exception {
Date date = new Date(epochTime);
SimpleDateFormat format = new SimpleDateFormat("dd MM yyyy HH:mm:ss.SSS");
String formattedDate = format.format(date);
System.out.println("date :" + formattedDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
public String getCurrentTimeZone() {
TimeZone tz = Calendar.getInstance().getTimeZone();
return tz.getID();
}
// ===================================================================
// Other manipulation
// ===================================================================
/**
* Generate Random number between provided high and low value
*
* @param low random number low boundary
* @param high random number high boundary
* @return random integer value between high and low boundary
*/
public int randInt(int low, int high) {
SecureRandom r = new SecureRandom();
int R = r.nextInt(high - low) + low;
return R;
}
/**
* Generate Random long number
*
* @return random long value
*/
public long randLong() {
SecureRandom r = new SecureRandom();
long R = r.nextLong();
return R;
}
/**
* Generate Random char array
*
* @param length Char array length
* @return random char array
*/
public char[] randChar(int length) {
SecureRandom r = new SecureRandom();
char[] chars = new char[length];
for (int i = 0; i < length; i++) {
chars[i] = (char) (r.nextInt(26) + 'a');
}
return chars;
}
/**
* Generate Random char String
*
* @param length String length
* @return random character string
*/
public String randString(int length) {
return String.valueOf(randChar(length));
}
/**
* Generate Random byte array
*
* @param length Byte array length
* @return random value byte array
*/
@Deprecated
public byte[] randBytes(int length) {
byte[] b = new byte[length];
SecureRandom r = new SecureRandom();
r.nextBytes(b);
return b;
}
}
| 25.981203 | 115 | 0.617036 |
38c20fe753d13ff517dfe8907f9560fbf67a120e | 805 | package com.elegion.tracktor.ui.results;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import com.elegion.tracktor.data.IRepository;
import com.elegion.tracktor.data.model.Track;
import java.util.List;
/**
* @author Azret Magometov
*/
public class ResultsViewModel extends ViewModel {
private IRepository mRepository;
private MutableLiveData<List<Track>> mTracks = new MutableLiveData<>();
public ResultsViewModel(IRepository repository) {
mRepository = repository;
}
public void loadTracks() {
if (mTracks.getValue() == null || mTracks.getValue().isEmpty()) {
mTracks.postValue(mRepository.getAll());
}
}
public MutableLiveData<List<Track>> getTracks() {
return mTracks;
}
}
| 23.676471 | 75 | 0.701863 |
93067b4477965a638b119cf622db436bfdc352d5 | 1,092 | /**
* Baidu.com,Inc.
* Copyright (c) 2000-2013 All Rights Reserved.
*/
package com.baidu.hsb.parser.ast.stmt.dal;
import com.baidu.hsb.parser.ast.stmt.SQLStatement;
import com.baidu.hsb.parser.visitor.SQLASTVisitor;
/**
* @author [email protected]
*/
public class DALSetNamesStatement implements SQLStatement {
private final String charsetName;
private final String collationName;
public DALSetNamesStatement() {
this.charsetName = null;
this.collationName = null;
}
public DALSetNamesStatement(String charsetName, String collationName) {
if (charsetName == null) throw new IllegalArgumentException("charsetName is null");
this.charsetName = charsetName;
this.collationName = collationName;
}
public boolean isDefault() {
return charsetName == null;
}
public String getCharsetName() {
return charsetName;
}
public String getCollationName() {
return collationName;
}
@Override
public void accept(SQLASTVisitor visitor) {
visitor.visit(this);
}
}
| 24.266667 | 91 | 0.681319 |
de251dd1a5546f0edeea765ce859aa3a19c455e0 | 2,368 | package org.appfuse.webapp.action;
import org.appfuse.model.User;
import org.appfuse.webapp.util.RequestUtil;
import org.springframework.mail.MailException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
* Managed Bean to send password hints to registered users.
*
* <p>
* <a href="PasswordHint.java.html"><i>View Source</i></a>
* </p>
*
* @author <a href="mailto:[email protected]">Matt Raible</a>
*/
public class PasswordHint extends BasePage {
private String username;
public void setUsername(String username) {
this.username = username;
}
public String execute() {
getFacesContext().getViewRoot().setViewId("/passwordHint.xhtml");
// ensure that the username has been sent
if (username == null || "".equals(username)) {
log.warn("Username not specified, notifying user that it's a required field.");
addError("errors.required", getText("user.username"));
return null;
} else if (username.endsWith(".xhtml")) {
username = username.substring(0, username.indexOf(".xhtml"));
}
if (log.isDebugEnabled()) {
log.debug("Processing Password Hint...");
}
// look up the user's information
try {
User user = userManager.getUserByUsername(username);
StringBuilder msg = new StringBuilder();
msg.append("Your password hint is: ").append(user.getPasswordHint());
msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(getRequest()));
message.setTo(user.getEmail());
String subject = '[' + getText("webapp.name") + "] " + getText("user.passwordHint");
message.setSubject(subject);
message.setText(msg.toString());
mailEngine.send(message);
addMessage("login.passwordHint.sent",
new Object[] { username, user.getEmail() });
} catch (UsernameNotFoundException e) {
log.warn(e.getMessage());
// If exception is expected do not rethrow
addError("login.passwordHint.error", username);
} catch (MailException me) {
addError(me.getCause().getLocalizedMessage());
}
return "success";
}
}
| 34.318841 | 96 | 0.601774 |
78e192283f6131300b869a6798335a9d9441376e | 2,647 | package com.example.eqdietmobile;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// Objects declarations
private EditText jEditText1;
private EditText jEditText2;
private TextView jTextView1;
// Variables declarations
short food;
int kcal;
long finalkcal;
long quantity;
String dish;
String grams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Makes the objects usable
jEditText1 = findViewById(R.id.editText1);
jEditText2 = findViewById(R.id.editText2);
jTextView1 = findViewById(R.id.textView2);
}
public void Eaten(){
switch(food){
case 1: //Bread
kcal = 265;
finalkcal = kcal * quantity / 100;
jTextView1.setText("You have eaten " + finalkcal + " kilocalories");
break;
case 2: //Chocolate
kcal = 546;
finalkcal = kcal * quantity / 100;
jTextView1.setText("You have eaten " + finalkcal + " kilocalories");
break;
case 3: //Milk
kcal = 42;
finalkcal = kcal * quantity / 100;
jTextView1.setText("You have eaten " + finalkcal + " kilocalories");
break;
}
}
public void scanFood(View scFood) {
try{
dish = jEditText1.getText().toString().toLowerCase();
grams = jEditText2.getText().toString();
quantity = Long.parseLong(grams);
if("bread".equals(dish)){
food = 1;
Eaten();
} else if("chocolate".equals(dish)){
food = 2;
Eaten();
} else if("milk".equals(dish)){
food = 3;
Eaten();
} else {
jTextView1.setText("The specified food does not actually exist");
}
} catch(NumberFormatException nex){
if("what's eqdiet's website?".equals(dish) || "what is eqdiet's website?".equals(dish)) {
jTextView1.setText("It's: eqdiet.weebly.com");
} else {
jTextView1.setText("Error:\nThe quantity you specified\nisn't a number");
}
}
}
} | 31.511905 | 102 | 0.533056 |
5cde39c2d5306699f1b2c31a1214505f3a6572eb | 1,935 | package com.flyingsoftgames.googleplayquery;
import com.flyingsoftgames.googleplayquery.QueryReceiver;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import android.content.Intent;
import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import org.json.JSONArray;
import org.json.JSONException;
public class GooglePlayQuery extends CordovaPlugin {
public static CallbackContext queryCallback = null;
public static CordovaInterface cordova = null;
public static String referrer_uri = "";
public static Intent QueryReceiverCachedIntent = null;
@Override public void initialize (CordovaInterface initCordova, CordovaWebView webView) {
// Create a static cordova reference so that QueryReceiver can access it.
cordova = initCordova;
// Enable the broadcast receiver in case it isn't enabled.
Activity activity = cordova.getActivity ();
ComponentName receiver = new ComponentName (activity, QueryReceiver.class);
PackageManager pm = activity.getPackageManager ();
pm.setComponentEnabledSetting (receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
// If the QueryReceiver's onReceive already ran, run the cached data.
if (QueryReceiver.cachedIntent != null) {QueryReceiver.runCachedOnReceive (QueryReceiver.cachedIntent);}
super.initialize (cordova, webView);
}
public boolean execute (String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
if ("getURI".equals(action)) {
if (referrer_uri != "") {
callbackContext.sendPluginResult (new PluginResult (PluginResult.Status.OK, referrer_uri));
referrer_uri = "";
return true;
}
this.queryCallback = callbackContext;
}
return true;
}
} | 37.211538 | 121 | 0.791214 |
40d23d2cffc96d9fb394ab865304ecfd8b1d6caa | 1,442 | package com.lykke.tests.api.service.campaigns.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.UpperCamelCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.lykke.api.testing.annotations.NetClassName;
import com.lykke.api.testing.annotations.PublicApi;
import lombok.Builder;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonNaming(UpperCamelCaseStrategy.class)
@PublicApi
@NetClassName("CampaignCreateModel")
public class Campaign extends CampaignBaseModel {
private String createdBy;
private ConditionCreateModel[] conditions;
private EarnRule[] contents;
@Builder(builderMethodName = "campaignBuilder")
public Campaign(String name, String description, String reward, RewardType rewardType, String approximateAward,
String amountInTokens, float amountInCurrency, boolean usePartnerCurrencyRate, String fromDate,
String toDate, int completionCount, int order, String createdBy, ConditionCreateModel[] conditions,
EarnRule[] contents) {
super(name, description, reward, rewardType, approximateAward, amountInTokens, amountInCurrency,
usePartnerCurrencyRate, fromDate, toDate, completionCount, order);
this.createdBy = createdBy;
this.conditions = conditions;
this.contents = contents;
}
}
| 42.411765 | 115 | 0.776006 |
e614bea42e4781a26a1951c9710c9148bf6e16cf | 1,141 | /**
* Copyright 2014 Heroic Efforts LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Disclaimer: gswitchblade is in no way affiliated
* with Razer and/or any of its employees and/or licensors.
* Heroic Efforts LLC does not take responsibility for any harm caused, direct
* or indirect, to any Razer peripherals via the use of gswitchblade.
*
* "Razer" is a trademark of Razer USA Ltd.
*/
package net.heroicefforts.gswitchblade;
import java.awt.Graphics2D;
import java.io.InputStream;
public interface InputStreamWidget {
public void render(InputStream page, Graphics2D graphics);
}
| 36.806452 | 79 | 0.736196 |
807dfa1380794e7071790816f4d3ea0b07d1e104 | 1,461 | /**
* %SVN.HEADER%
*/
package net.sf.javaml.classification;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import net.sf.javaml.classification.evaluation.CrossValidation;
import net.sf.javaml.classification.tree.RandomTree;
import net.sf.javaml.core.Dataset;
import net.sf.javaml.core.DefaultDataset;
import net.sf.javaml.core.DenseInstance;
import net.sf.javaml.tools.data.FileHandler;
import org.junit.Assert;
import org.junit.Test;
public class TestRandomTree {
@Test
public void testRFDestructiveConstruction() {
// Show that a data set can be modified during training
Dataset data = new DefaultDataset();
data.add(new DenseInstance(new double[] { 1, 2 }, "hallo"));
data.add(new DenseInstance(new double[] { 4, 2 }, "hallo"));
data.add(new DenseInstance(new double[] { 1, 1 }, "hallo"));
System.out.println("Loader: " + data.classes());
RandomTree rt = new RandomTree(1, new Random());
rt.buildClassifier(data);
Assert.assertEquals(0, data.size());
}
@Test
public void testRT() {
try {
Dataset data = FileHandler.loadDataset(new File(
"devtools/data/colon.csv.gz"), 0, ",");
System.out.println("Loader: " + data.classes());
RandomTree knn = new RandomTree(5, new Random());
CrossValidation cv = new CrossValidation(knn);
System.out.println("Java-ML-0:"
+ cv.crossValidation(data, 5, new Random(10)));
} catch (IOException e) {
Assert.assertTrue(false);
}
}
}
| 27.055556 | 63 | 0.706366 |
d414d3e7abe7da33fab74794496e655f09da9fc0 | 5,780 | /*
* 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.carbondata.core.carbon.datastore.impl.btree;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.carbondata.core.carbon.datastore.BtreeBuilder;
import org.apache.carbondata.core.carbon.datastore.IndexKey;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.util.CarbonProperties;
/**
* Abstract Btree based builder
*/
public abstract class AbstractBTreeBuilder implements BtreeBuilder {
/**
* default Number of keys per page
*/
private static final int DEFAULT_NUMBER_OF_ENTRIES_NONLEAF = 32;
/**
* Maximum number of entries in intermediate nodes
*/
protected int maxNumberOfEntriesInNonLeafNodes;
/**
* Number of leaf nodes
*/
protected int nLeaf;
/**
* root node of a btree
*/
protected BTreeNode root;
public AbstractBTreeBuilder() {
maxNumberOfEntriesInNonLeafNodes = Integer.parseInt(CarbonProperties.getInstance()
.getProperty("com.huawei.datastore.internalnodesize",
DEFAULT_NUMBER_OF_ENTRIES_NONLEAF + ""));
}
/**
* Below method is to build the intermediate node of the btree
*
* @param curNode current node
* @param childNodeGroups children group which will have all the children for
* particular intermediate node
* @param currentGroup current group
* @param interNSKeyList list if keys
* @param numberOfInternalNode number of internal node
*/
protected void addIntermediateNode(BTreeNode curNode, List<BTreeNode[]> childNodeGroups,
BTreeNode[] currentGroup, List<List<IndexKey>> interNSKeyList, int numberOfInternalNode) {
int groupCounter;
// Build internal nodes level by level. Each upper node can have
// upperMaxEntry keys and upperMaxEntry+1 children
int remainder;
int nHigh = numberOfInternalNode;
boolean bRootBuilt = false;
remainder = nLeaf % (maxNumberOfEntriesInNonLeafNodes);
List<IndexKey> interNSKeys = null;
while (nHigh > 1 || !bRootBuilt) {
List<BTreeNode[]> internalNodeGroups =
new ArrayList<BTreeNode[]>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
List<List<IndexKey>> interNSKeyTmpList =
new ArrayList<List<IndexKey>>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
numberOfInternalNode = 0;
for (int i = 0; i < nHigh; i++) {
// Create a new internal node
curNode = new BTreeNonLeafNode();
// Allocate a new node group if current node group is full
groupCounter = i % (maxNumberOfEntriesInNonLeafNodes);
if (groupCounter == 0) {
// Create new node group
currentGroup = new BTreeNonLeafNode[maxNumberOfEntriesInNonLeafNodes];
internalNodeGroups.add(currentGroup);
numberOfInternalNode++;
interNSKeys = new ArrayList<IndexKey>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
interNSKeyTmpList.add(interNSKeys);
}
// Add the new internal node to current group
if (null != currentGroup) {
currentGroup[groupCounter] = curNode;
}
int nNodes;
if (i == nHigh - 1 && remainder != 0) {
nNodes = remainder;
} else {
nNodes = maxNumberOfEntriesInNonLeafNodes;
}
// Point the internal node to its children node group
curNode.setChildren(childNodeGroups.get(i));
// Fill the internal node with keys based on its child nodes
for (int j = 0; j < nNodes; j++) {
curNode.setKey(interNSKeyList.get(i).get(j));
if (j == 0 && null != interNSKeys) {
interNSKeys.add(interNSKeyList.get(i).get(j));
}
}
}
// If nHigh is 1, we have the root node
if (nHigh == 1) {
bRootBuilt = true;
}
remainder = nHigh % (maxNumberOfEntriesInNonLeafNodes);
nHigh = numberOfInternalNode;
childNodeGroups = internalNodeGroups;
interNSKeyList = interNSKeyTmpList;
}
root = curNode;
}
/**
* Below method is to convert the start key
* into fixed and variable length key.
* data format<lenght><fixed length key><length><variable length key>
*
* @param startKey
* @return Index key
*/
protected IndexKey convertStartKeyToNodeEntry(byte[] startKey) {
ByteBuffer buffer = ByteBuffer.wrap(startKey);
buffer.rewind();
int dictonaryKeySize = buffer.getInt();
int nonDictonaryKeySize = buffer.getInt();
byte[] dictionaryKey = new byte[dictonaryKeySize];
buffer.get(dictionaryKey);
byte[] nonDictionaryKey = new byte[nonDictonaryKeySize];
buffer.get(nonDictionaryKey);
IndexKey entry = new IndexKey(dictionaryKey, nonDictionaryKey);
return entry;
}
/**
* Below method will be used to get the first data block
* in Btree case it will be root node
*/
@Override public BTreeNode get() {
return root;
}
}
| 34.819277 | 96 | 0.681661 |
192923b5c3f635d9bc7866df37eff116d320be37 | 1,259 | package com.web.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the cards database table.
*
*/
@Entity
@Table(name="cards")
@NamedQuery(name="Card.findAll", query="SELECT c FROM Card c")
public class Card implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="card_id", unique=true, nullable=false)
private String cardId;
@Column(name="card_name", length=45)
private String cardName;
@Column(length=45)
private String image;
private Character suit;
private Integer number;
public Card() {
}
public String getCardId() {
return this.cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public String getCardName() {
return this.cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
public String getImage() {
return this.image;
}
public void setImage(String image) {
this.image = image;
}
public Character getSuit() {
return suit;
}
public void setSuit(Character suit) {
this.suit = suit;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
} | 16.786667 | 62 | 0.710087 |
6b9e7247d52467e31071659dbf4559cf4b7f852f | 2,671 | /**
*
* Copyright 2017 Florian Erhard
*
* 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 gedi.remote.codec;
import java.util.logging.Level;
import java.util.logging.Logger;
import gedi.util.FileUtils;
import gedi.util.io.randomaccess.serialization.BinarySerializable;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* Encoded as follows:
* int (total size in bytes)
* int (length of classname)
* byte[] (classname)
* buffer data
* @author erhard
*
*/
public class NumberEncoder extends MessageToByteEncoder<Number> {
private static final Logger log = Logger.getLogger( NumberEncoder.class.getName() );
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
log.log(Level.SEVERE, "NumberEncoder caught exception!", cause);
}
public NumberEncoder() {
super(Number.class);
}
@Override
protected void encode(ChannelHandlerContext ctx, Number msg,
ByteBuf out) throws Exception {
if (msg instanceof Byte) {
out.writeInt(Integer.BYTES+1+Byte.BYTES);
out.writeInt(1);
out.writeByte('B');
out.writeByte(msg.byteValue());
}
else if (msg instanceof Short) {
out.writeInt(Integer.BYTES+1+Short.BYTES);
out.writeInt(1);
out.writeByte('S');
out.writeShort(msg.shortValue());
}
else if (msg instanceof Integer) {
out.writeInt(Integer.BYTES+1+Integer.BYTES);
out.writeInt(1);
out.writeByte('I');
out.writeInt(msg.intValue());
}
else if (msg instanceof Long) {
out.writeInt(Integer.BYTES+1+Long.BYTES);
out.writeInt(1);
out.writeByte('L');
out.writeLong(msg.longValue());
}
else if (msg instanceof Float) {
out.writeInt(Integer.BYTES+1+Float.BYTES);
out.writeInt(1);
out.writeByte('F');
out.writeFloat(msg.floatValue());
}
else if (msg instanceof Double) {
out.writeInt(Integer.BYTES+1+Double.BYTES);
out.writeInt(1);
out.writeByte('D');
out.writeDouble(msg.doubleValue());
}
else
throw new RuntimeException("Could not encode number "+msg.getClass().getName());
}
}
| 27.536082 | 85 | 0.708723 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.