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 |
|---|---|---|---|---|---|
abe95e4f304c5fe3df7f04b087c929a5ca09bc7a | 16,708 | package uk.gov.eastlothian.gowalk.ui;
import android.app.ActionBar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import uk.gov.eastlothian.gowalk.R;
import uk.gov.eastlothian.gowalk.data.WalksContract;
// TODO: This class needs refactored
// - There are to many places where the time gets set etc.
// - The image saving could be moved out to it's own class.
public class NewLogEntryActivity extends MainMenuActivity {
NewLogEntryFragment newLogEntryFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_log_entry);
if (savedInstanceState == null) {
newLogEntryFragment = new NewLogEntryFragment();
getFragmentManager().beginTransaction()
.add(R.id.container, newLogEntryFragment)
.commit();
}
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class NewLogEntryFragment extends Fragment {
private static String LOG_TAG = NewLogEntryActivity.class.getSimpleName();
// view
Button locationButton;
Button dateButton;
Button timeButton;
Spinner weatherSpinner;
ImageView imageView;
// data // TODO: This might not be a good default location (current location)
LatLng location = new LatLng(55.9561054, -2.7770153);
int year, month, day; // date
int hour, minute; // time
public NewLogEntryFragment() {
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == LocationPickerActivity.LOCATION_RESULT) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
double lat = data.getDoubleExtra("lat", 0.0);
double lng = data.getDoubleExtra("lng", 0.0);
location = new LatLng(lat, lng);
locationButton.setText("(" + lat + ", " + lng + ")");
}
} else if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
// Bundle extras = data.getExtras();
// Bitmap imageBitmap = (Bitmap) extras.get("data");
// imageView.setImageBitmap(imageBitmap);
galleryAddPic(); // add the current photo to the media gallery
setPic(); // set the image view to show a scaled version of the image
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new_log_entry, container, false);
// set the title and image to the correct value for this animal
String wildlifeName = getActivity().getIntent().getStringExtra("wildlife_name");
TextView nameView = (TextView) rootView.findViewById(R.id.new_log_name);
nameView.setText(wildlifeName);
int wildlifeImageId = getActivity().getIntent().getIntExtra("wildlife_image_res_id", -1);
if (wildlifeImageId != -1) {
imageView = (ImageView) rootView.findViewById(R.id.new_log_wildlife_image_view);
imageView.setImageResource(wildlifeImageId);
}
// set up pick location button
locationButton = (Button) rootView.findViewById(R.id.new_log_location_of_sighting_button);
locationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), LocationPickerActivity.class);
startActivityForResult(intent, LocationPickerActivity.LOCATION_RESULT);
}
});
// set up date button
dateButton = (Button) rootView.findViewById(R.id.new_log_select_date_button);
dateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDatePickerDialog(view);
}
});
setDateToToday();
// set up time button
timeButton = (Button) rootView.findViewById(R.id.new_log_time_button);
timeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showTimePickerDialog(view);
}
});
setTimeToToday();
// set up weather spinner
weatherSpinner = (Spinner) rootView.findViewById(R.id.new_log_weather_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.weather_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weatherSpinner.setAdapter(adapter);
// set up the log this button
Button logButton = (Button) rootView.findViewById(R.id.new_log_button);
logButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// add the log to the database
insertLogEntry();
Toast toast = Toast.makeText(getActivity(), "Sighting logged", Toast.LENGTH_SHORT);
toast.show();
// go to the log book activity
Intent intent = new Intent(getActivity(), LogBookActivity.class);
startActivity(intent);
}
});
Button cameraButton = (Button) rootView.findViewById(R.id.new_log_camera_button);
cameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
return rootView;
}
// Camera and image saving
static final int REQUEST_TAKE_PHOTO = 2;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.d(LOG_TAG, "Error occurred while creating the File: " + ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
String mCurrentPhotoPath = "";
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
String imageFileName = "WILDLIFE_JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
private void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
}
// update the database
private void insertLogEntry() {
ContentValues values = new ContentValues();
// wildlife id
long wildlifeId = getActivity().getIntent().getLongExtra("wildlife_id", -1);
values.put(WalksContract.LogEntry.COLUMN_WILDLIFE_KEY, wildlifeId);
// date time
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day, hour, minute);
SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = iso8601Format.format(calendar.getTime());
values.put(WalksContract.LogEntry.COLUMN_DATATIME, dateTime);
// location
values.put(WalksContract.LogEntry.COLUMN_LAT, location.latitude);
values.put(WalksContract.LogEntry.COLUMN_LNG, location.longitude);
// weather
values.put(WalksContract.LogEntry.COLUMN_WEATHER,
weatherSpinner.getSelectedItem().toString());
// image TODO: The image will need to be set to whatever later.
String imageName = getActivity().getIntent().getStringExtra("wildlife_image_name");
if (mCurrentPhotoPath.isEmpty()) mCurrentPhotoPath = imageName;
values.put(WalksContract.LogEntry.COLUMN_IMAGE, mCurrentPhotoPath);
getActivity().getContentResolver().insert(WalksContract.LogEntry.CONTENT_URI, values);
}
// date
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.setNewLogEntryFragment(this);
newFragment.show(((FragmentActivity)getActivity()).getSupportFragmentManager(), "datePicker");
}
public void setDate(int year, int month, int day) {
// set the date
this.year = year;
this.month = month;
this.day = day;
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day, hour, minute); // dd/MM/yyyy
SimpleDateFormat iso8601Format = new SimpleDateFormat("dd/MM/yyyy");
String dateTime = iso8601Format.format(calendar.getTime());
// update the view - note: month is zero indexed
String label = dateTime;
dateButton.setText(label);
}
void setDateToToday() {
final Calendar c = Calendar.getInstance();
setDate(c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
// time
public void showTimePickerDialog(View v) {
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.setNewLogEntryFragment(this);
newFragment.show(((FragmentActivity)getActivity()).getSupportFragmentManager(), "timePicker");
}
public void setTime(int hour, int minute) {
this.hour = hour;
this.minute = minute;
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day, hour, minute); // dd/MM/yyyy
SimpleDateFormat iso8601Format = new SimpleDateFormat("HH:mm");
String dateTime = iso8601Format.format(calendar.getTime());
timeButton.setText(dateTime);
}
void setTimeToToday() {
final Calendar c = Calendar.getInstance();
setTime(c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE));
}
public int getHour() {
return hour;
}
public int getMinute() {
return minute;
}
}
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
NewLogEntryFragment newLogEntryFragment;
int year, month, day;
// config methods
public void setNewLogEntryFragment(NewLogEntryFragment newLogEntryFragment) {
this.newLogEntryFragment = newLogEntryFragment;
year = newLogEntryFragment.getYear();
month = newLogEntryFragment.getMonth();
day = newLogEntryFragment.getDay();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
newLogEntryFragment.setDate(year, month, day);
}
}
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
NewLogEntryFragment newLogEntryFragment;
int hour, minute;
public void setNewLogEntryFragment(NewLogEntryFragment newLogEntryFragment) {
this.newLogEntryFragment = newLogEntryFragment;
hour = newLogEntryFragment.getHour();
minute = newLogEntryFragment.getMinute();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
newLogEntryFragment.setTime(hourOfDay, minute);
}
}
}
| 39.780952 | 106 | 0.613299 |
dc1aa2f62f658829fef2989a44312228ec296ad4 | 5,714 | /**
* Project: DomainNameProfiler
* Copyright (c) 2017 University of Murcia
*
* @author Mattia Zago - mattia.zago@um.es
*/
package es.um.dga.features.nlp.utils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
/**
* Static helper class for String-related algorithms.
*/
public class StringHelper {
/**
* Dictionary Vowels.
*/
public static final String VOWELS = "aeiou".toLowerCase();
/**
* Dictionary Consonants.
*/
public static final String CONSONANTS = "bcdfghjklmnpqrstvwxyz".toLowerCase();
/**
* Dictionary Letters.
*/
public static final String LETTERS = "abcdefghijklmnopqrstuvwxyz".toLowerCase();
/**
* Dictionary Digits.
*/
public static final String DIGITS = "0123456789";
/**
* Dictionary Symbols.
*/
public static final String SYMBOLS = "-.";
/**
* Common accepted characters in DNS names. Also accents are supported, but not as a standard.
*/
public static final String ALPHABET = "-0123456789abcdefghijklmnopqrstuvwxyz".toLowerCase();
/**
* Longest common substring ('O(mn)' implementation).
*
* @param first First Word.
* @param second Second Word.
*
* @return Length of the longest common substring.
*
* @see <a href="https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Java">WikiBooks Implementation
* </a>
*/
public static int longestCommonSubstring(String first, String second) {
int maxLen = 0;
int fl = first.length();
int sl = second.length();
int[][] table = new int[fl + 1][sl + 1];
for (int i = 1; i <= fl; i++) {
for (int j = 1; j <= sl; j++) {
if (Character.toLowerCase(first.charAt(i - 1)) == Character.toLowerCase(second.charAt(j - 1))) {
table[i][j] = table[i - 1][j - 1] + 1;
if (table[i][j] > maxLen)
maxLen = table[i][j];
}
}
}
return maxLen;
}
/**
* Longest consecutive substring in the alphabet.
* Overload with string param.
*
* @param text Text where to search the longest consecutive substring.
* @param alphabet Alphabet to search in the test provided.
*
* @return Size of the longest consecutive substring.
*
* @see es.um.dga.features.nlp.utils.StringHelper#longestConsecutiveSubstringInAlphabet(char[], String)
*/
public static int longestConsecutiveSubstringInAlphabet(String text, String alphabet) {
return longestConsecutiveSubstringInAlphabet(text.toCharArray(), alphabet);
}
/**
* Longest consecutive substring in the alphabet.
*
* @param text Text where to search the longest consecutive substring.
* @param alphabet Alphabet to search in the test provided.
*
* @return Size of the longest consecutive substring.
*/
public static int longestConsecutiveSubstringInAlphabet(char[] text, String alphabet) {
int longest = 0;
int candidateLength = 0;
for (char c : text) {
Character C = Character.toLowerCase(c);
if (alphabet.indexOf(C) >= 0) {
++candidateLength;
}
else {
if (longest < candidateLength) {
longest = candidateLength;
}
candidateLength = 0;
}
}
if (longest < candidateLength) {
longest = candidateLength;
}
return longest;
}
/**
* Get the ratio of vowels w.r.t. the text passed as param.
*
* @param text Text to be analysed.
*
* @return Ratio vowels/text.
*/
public static Double getRatioVowelsChars(String text) {
return getRatioOfSymbolsOccurrence(text, VOWELS);
}
/**
* Get the ratio of consonants w.r.t. the text passed as param.
*
* @param text Text to be analysed.
*
* @return Ratio consonants/text.
*/
public static Double getRatioConsonantsChars(String text) {
return getRatioOfSymbolsOccurrence(text, CONSONANTS);
}
/**
* Get the ratio of letters w.r.t. the text passed as param.
*
* @param text Text to be analysed.
*
* @return Ratio letters/text.
*/
public static Double getRatioLettersChars(String text) {
return getRatioOfSymbolsOccurrence(text, LETTERS);
}
/**
* Get the ratio of numbers w.r.t. the text passed as param.
*
* @param text Text to be analysed.
*
* @return Ratio numbers/text.
*/
public static Double getRatioNumericChars(String text) {
return getRatioOfSymbolsOccurrence(text, DIGITS);
}
/**
* Get the ratio of symbols w.r.t. the text passed as param.
*
* @param text Text to be analysed.
*
* @return Ratio symbols/text.
*/
public static Double getRatioSymbolChars(String text) {
return getRatioOfSymbolsOccurrence(text, SYMBOLS);
}
@NotNull private static Double getRatioOfSymbolsOccurrence(String text, String symbols) {
try {
double counter = 0;
for (Character character : text.toCharArray()) {
if (StringUtils.containsIgnoreCase(symbols, character.toString())) {
++counter;
}
}
return counter / text.length();
}
catch (ArithmeticException ex) {
return Double.NaN;
}
}
}
| 29.91623 | 139 | 0.584704 |
1b4d0fe33d279bdb0009ed5738021ce6e852ec30 | 2,436 | /**
* Copyright 2013 deib-polimi
* Contact: deib-polimi <marco.miglierina@polimi.it>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.polimi.modaclouds.cpimlibrary.entitymng.migration.hegira;
import it.polimi.modaclouds.cpimlibrary.CloudMetadata;
import it.polimi.modaclouds.cpimlibrary.exception.MigrationException;
import it.polimi.modaclouds.cpimlibrary.mffactory.MF;
import lombok.extern.slf4j.Slf4j;
/**
* @author Fabio Arcidiacono.
*/
@Slf4j
public class HegiraConnector {
private static HegiraConnector instance = null;
private ZKAdapter zkClient = null;
private HegiraConnector() {
CloudMetadata cloudMetadata = MF.getFactory().getCloudMetadata();
String type = cloudMetadata.getZooKeeperType();
if (type.equalsIgnoreCase("thread")) {
log.info("Instantiating THREAD type ZKClient");
zkClient = new ZKThread(cloudMetadata.getZookeeperConnectionString());
} else if (type.equalsIgnoreCase("http")) {
log.info("Instantiating HTTP type ZKClient");
zkClient = new ZKHttp(cloudMetadata.getZookeeperConnectionString());
} else {
throw new MigrationException("Unrecognized type '" + type + "' for ZooKeeper client");
}
}
public static HegiraConnector getInstance() {
if (instance == null) {
instance = new HegiraConnector();
}
return instance;
}
public int[] assignSeqNrRange(String tableName, int offset) throws Exception {
return zkClient.assignSeqNrRange(tableName, offset);
}
public int assignSeqNr(String tableName) throws Exception {
return zkClient.assignSeqNr(tableName);
}
public void setSynchronizing(boolean status) {
zkClient.setSynchronizing(status);
}
public boolean isSynchronizing() {
return zkClient.isSynchronizing();
}
}
| 34.8 | 98 | 0.692939 |
3825c7ddcc5df8465634a43ac61939ac641ed667 | 2,822 | package com.unascribed.lanthanoid.block;
import java.util.Random;
import com.unascribed.lanthanoid.effect.EntityRifleFX;
import com.unascribed.lanthanoid.item.rifle.PrimaryMode;
import com.unascribed.lanthanoid.Lanthanoid;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.init.Blocks;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockTechnical extends Block {
public IIcon glyphs;
public BlockTechnical() {
super(Material.circuits);
setTickRandomly(true);
}
@Override
public boolean isAir(IBlockAccess world, int x, int y, int z) {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public int getRenderType() {
return Lanthanoid.proxy.getTechnicalRenderType();
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_) {
return null;
}
@Override
public boolean isReplaceable(IBlockAccess world, int x, int y, int z) {
return true;
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean isCollidable() {
return false;
}
@Override
public void dropBlockAsItemWithChance(World p_149690_1_, int p_149690_2_, int p_149690_3_, int p_149690_4_, int p_149690_5_, float p_149690_6_, int p_149690_7_) {
}
@Override
@SideOnly(Side.CLIENT)
public void randomDisplayTick(World world, int x, int y, int z, Random rand) {
int meta = world.getBlockMetadata(x, y, z);
if (meta == 0) {
PrimaryMode mode = PrimaryMode.LIGHT;
float r = ((mode.color >> 16)&0xFF)/255f;
float g = ((mode.color >> 8)&0xFF)/255f;
float b = (mode.color&0xFF)/255f;
for (int i = 0; i < 2; i++) {
EntityRifleFX fx = new EntityRifleFX(Minecraft.getMinecraft().theWorld, (x+0.5)+(rand.nextDouble()-0.5), (y+0.5)+(rand.nextDouble()-0.5), (z+0.5)+(rand.nextDouble()-0.5), 1.0f, 0, 0, 0);
fx.motionX = fx.motionY = fx.motionZ = 0;
fx.setRBGColorF(r, g, b);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
}
}
}
@Override
public int getLightValue(IBlockAccess world, int x, int y, int z) {
int meta = world.getBlockMetadata(x, y, z);
return meta == 0 ? 10 : meta == 1 ? 12 : 0;
}
@Override
public void updateTick(World world, int x, int y, int z, Random rand) {
int meta = world.getBlockMetadata(x, y, z);
if (meta == 0) {
world.setBlock(x, y, z, Blocks.air, 0, 2);
}
}
@Override
public void registerIcons(IIconRegister reg) {
glyphs = reg.registerIcon("lanthanoid:glyphs");
}
}
| 27.666667 | 190 | 0.720411 |
6a16696ef0cbb0075726b76409aa4d343986484d | 9,160 | package org.sunbird.notification.email;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.sunbird.notification.beans.Constants;
import org.sunbird.notification.beans.EmailConfig;
import org.sunbird.notification.utils.Util;
/**
* this api is used to sending mail.
*
* @author Manzarul.Haque
*/
public class Email {
private static Logger logger = LogManager.getLogger(Email.class);
private static Properties props = null;
private String host;
private String port;
private String userName;
private String password;
private String fromEmail;
private Session session;
public Email() {
init();
initProps();
}
public Email(EmailConfig config) {
this.fromEmail =
StringUtils.isNotBlank(config.getFromEmail())
? config.getFromEmail()
: Util.readValue(Constants.EMAIL_SERVER_FROM);
this.userName =
StringUtils.isNotBlank(config.getUserName())
? config.getUserName()
: Util.readValue(Constants.EMAIL_SERVER_USERNAME);
this.password =
StringUtils.isNotBlank(config.getPassword())
? config.getPassword()
: Util.readValue(Constants.EMAIL_SERVER_PASSWORD);
this.host =
StringUtils.isNotBlank(config.getHost())
? config.getHost()
: Util.readValue(Constants.EMAIL_SERVER_HOST);
this.port =
StringUtils.isNotBlank(config.getPort())
? config.getPort()
: Util.readValue(Constants.EMAIL_SERVER_PORT);
initProps();
}
private boolean init() {
boolean response = true;
host = Util.readValue(Constants.EMAIL_SERVER_HOST);
port = Util.readValue(Constants.EMAIL_SERVER_PORT);
userName = Util.readValue(Constants.EMAIL_SERVER_USERNAME);
password = Util.readValue(Constants.EMAIL_SERVER_PASSWORD);
fromEmail = Util.readValue(Constants.EMAIL_SERVER_FROM);
if (StringUtils.isBlank(host)
|| StringUtils.isBlank(port)
|| StringUtils.isBlank(userName)
|| StringUtils.isBlank(password)
|| StringUtils.isBlank(fromEmail)) {
logger.info(
"Email setting value is not provided by Env variable=="
+ host
+ " "
+ port
+ " "
+ fromEmail);
response = false;
} else {
logger.info("All email properties are set correctly.");
}
return response;
}
private Session getSession() {
if (session == null) {
session = Session.getInstance(props, new GMailAuthenticator(userName, password));
}
return session;
}
private void initProps() {
props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", port);
}
/**
* This method will send email to provided email list.
*
* @param emailList List of recipient
* @param body email body
* @param subject Subject of email
*/
public boolean sendMail(List<String> emailList, String subject, String body) {
return sendMail(emailList, subject, body, null);
}
/**
* Send email (with Cc) using.
*
* @param emailList List of recipient emails
* @param subject email subject
* @param body email body
* @param ccEmailList List of Cc emails
* @return boolean
*/
public boolean sendMail(
List<String> emailList, String subject, String body, List<String> ccEmailList) {
boolean response = true;
try {
Session session = getSession();
MimeMessage message = new MimeMessage(session);
addRecipient(message, Message.RecipientType.TO, emailList);
addRecipient(message, Message.RecipientType.CC, ccEmailList);
setMessageAttribute(message, fromEmail, subject, body);
response = sendEmail(session, message);
} catch (Exception e) {
response = false;
logger.error("Exception occured during email sending " + e, e);
}
return response;
}
/**
* Send email (with attachment) and given body.
*
* @param emailList List of recipient emails
* @param emailBody Text of email body
* @param subject Subject of email
* @param filePath Path of attachment file
*/
public void sendAttachment(
List<String> emailList, String emailBody, String subject, String filePath) {
try {
Session session = getSession();
MimeMessage message = new MimeMessage(session);
addRecipient(message, Message.RecipientType.TO, emailList);
message.setSubject(subject);
Multipart multipart = createMultipartData(emailBody, filePath);
setMessageAttribute(message, fromEmail, subject, multipart);
sendEmail(session, message);
} catch (Exception e) {
logger.error("Exception occured during email sending " + e, e);
}
}
/**
* This method will send email with bcc.
*
* @param fromEmail fromEmail which will come in to.
* @param subject email subject
* @param body email body
* @param bccList recipient bcc list
* @return boolean
*/
public boolean sendEmail(String fromEmail, String subject, String body, List<String> bccList) {
boolean sentStatus = true;
try {
Session session = getSession();
MimeMessage message = new MimeMessage(session);
addRecipient(message, Message.RecipientType.BCC, bccList);
setMessageAttribute(message, fromEmail, subject, body);
sentStatus = sendEmail(session, message);
} catch (Exception e) {
sentStatus = false;
logger.error("SendMail:sendMail: Exception occurred with message = " + e.getMessage(), e);
}
return sentStatus;
}
private Multipart createMultipartData(String emailBody, String filePath)
throws AddressException, MessagingException {
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(emailBody, "text/html; charset=utf-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
DataSource source = new FileDataSource(filePath);
messageBodyPart = null;
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filePath);
multipart.addBodyPart(messageBodyPart);
return multipart;
}
private void addRecipient(MimeMessage message, RecipientType type, List<String> recipient)
throws AddressException, MessagingException {
if (CollectionUtils.isEmpty(recipient)) {
logger.info("Recipient list is empty or null ");
return;
}
for (String email : recipient) {
message.addRecipient(type, new InternetAddress(email));
}
}
private void setMessageAttribute(
MimeMessage message, String fromEmail, String subject, String body)
throws AddressException, MessagingException {
message.setFrom(new InternetAddress(fromEmail));
message.setSubject(subject, "utf-8");
message.setContent(body, "text/html; charset=utf-8");
}
private void setMessageAttribute(
MimeMessage message, String fromEmail, String subject, Multipart multipart)
throws AddressException, MessagingException {
message.setFrom(new InternetAddress(fromEmail));
message.setSubject(subject, "utf-8");
message.setContent(multipart, "text/html; charset=utf-8");
}
private boolean sendEmail(Session session, MimeMessage message) {
Transport transport = null;
boolean response = true;
try {
transport = session.getTransport("smtp");
transport.connect(host, userName, password);
transport.sendMessage(message, message.getAllRecipients());
} catch (Exception e) {
logger.error("SendMail:sendMail: Exception occurred with message = " + e.getMessage(), e);
response = false;
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
logger.error(e.toString(), e);
}
}
}
return response;
}
public String getHost() {
return host;
}
public String getPort() {
return port;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public String getFromEmail() {
return fromEmail;
}
}
| 32.367491 | 97 | 0.688319 |
ace97a6a44c65c0f755eb92a5fda3d2b47ddf68a | 2,896 | /*******************************************************************************
* Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.helper;
/**
* <p>
* <b>Purpose</b>: Extension to the existing conversion manager to support the
* EJB 3.0 spec.
* <p>
* <b>Responsibilities</b>:
* <ul>
* <li> Allow a null value default to be read into primitives. With the current
* conversion manager, setting a null into a primitive causes and exception.
* This conversion manager was added to avoid that exception and therefore, add
* support for schemas that were built before the object model was mapped
* (using a primitive). Therefore, EclipseLink will not change the null column value
* in the database through this conversion. The value on the database will only
* be changed if the user actually sets a new primitive value.
* <li> Allows users to define their own set of default null values to be used
* in the conversion.
* </ul>
*
* @author Guy Pelletier
* @since TopLink 10.1.4 RI
*/
public class JPAConversionManager extends ConversionManager {
public JPAConversionManager() {
super();
}
/**
* INTERNAL:
*/
@Override
public Object getDefaultNullValue(Class theClass) {
Object defaultNullValue = null;
if (this.defaultNullValues != null){
defaultNullValue = getDefaultNullValues().get(theClass);
}
if (defaultNullValue == null && theClass.isPrimitive()) {
if(Double.TYPE.equals(theClass)){
return Double.valueOf(0D);
} else if(Long.TYPE.equals(theClass)) {
return Long.valueOf(0L);
} else if(Character.TYPE.equals(theClass)){
return Character.valueOf('\u0000');
} else if(Float.TYPE.equals(theClass)){
return Float.valueOf(0F);
} else if(Short.TYPE.equals(theClass)){
return Short.valueOf((short)0);
} else if(Byte.TYPE.equals(theClass)){
return Byte.valueOf((byte)0);
} else if(Boolean.TYPE.equals(theClass)){
return Boolean.FALSE;
} else {
return 0;
}
} else {
return defaultNullValue;
}
}
}
| 39.671233 | 87 | 0.61326 |
2f3497162232040f1dd4dfb9207d768ed285f047 | 386 | package com.haskforce.parsing.srcExtsDatatypes;
/**
* data Bracket l
* = ExpBracket l (Exp l) -- ^ expression bracket: @[| ... |]@
* | PatBracket l (Pat l) -- ^ pattern bracket: @[p| ... |]@
* | TypeBracket l (Type l) -- ^ type bracket: @[t| ... |]@
* | DeclBracket l [Decl l] -- ^ declaration bracket: @[d| ... |]@
*/
public class BracketTopType {
}
| 32.166667 | 72 | 0.533679 |
0e570b57509526095397c62d65fc8f47da4a9da1 | 2,282 | package makereadcount;
public class ReadArguments
{
static String inputFileName;
static String tag;
static int maxSize;
static byte minBaseQual;
static int minMappingQual;
static double minBalanceEValue;
ReadArguments(final String[] args) {
ReadArguments.inputFileName = args[args.length - 1];
ReadArguments.tag = ReadArguments.inputFileName.replaceFirst(".*\\/", "").replaceFirst(".bam", "").replaceFirst(".sam", "");
for (int iArg = 0; iArg < args.length - 1; ++iArg) {
if (args[iArg].startsWith("-")) {
if (args[iArg].equals("-N")) {
ReadArguments.maxSize = Integer.parseInt(args[iArg + 1]);
}
else if (args[iArg].equals("-minMappingQual")) {
ReadArguments.minMappingQual = Integer.parseInt(args[iArg + 1]);
}
else if (args[iArg].equals("-minBaseQual")) {
ReadArguments.minBaseQual = (byte)Integer.parseInt(args[iArg + 1]);
}
else if (args[iArg].equals("-minBalanceEValue")) {
ReadArguments.minBalanceEValue = Double.parseDouble(args[iArg + 1]);
}
}
}
}
public static int getMinMappingQual() {
return ReadArguments.minMappingQual;
}
public static double getMinBalanceEValue() {
return ReadArguments.minBalanceEValue;
}
public static byte getMinBaseQual() {
return ReadArguments.minBaseQual;
}
public static int getMaxSize() {
return ReadArguments.maxSize;
}
public static String getInputFileName() {
return ReadArguments.inputFileName;
}
public static String getLogFileName() {
return invokedynamic(makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;, ReadArguments.tag);
}
public static String getOutputFileName() {
return invokedynamic(makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;, ReadArguments.tag);
}
static {
ReadArguments.maxSize = 300000;
ReadArguments.minBaseQual = 30;
ReadArguments.minMappingQual = 10;
ReadArguments.minBalanceEValue = 0.1;
}
}
| 33.558824 | 132 | 0.600351 |
582a0b1672b7a96c4a01285c917e73775d8586e6 | 1,223 | package com.coderZsq._12_session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
// 输出收件箱界面
@WebServlet("/session/get")
public class GetServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
// String username = "";
// ===================================
// 获取Session对象
HttpSession session = req.getSession();
// 获取Session中存储的数据
// username = (String) session.getAttribute("currentName");
User user = (User) session.getAttribute("USER_IN_SESSION");
// ===================================
out.println("欢迎: " + user.getUsername() + "<br>");
out.println("泉哥, 我也要请你吃饭!");
}
}
| 35.970588 | 115 | 0.658217 |
12efb1e91497777cce79887cb600ece6c6255afb | 1,089 | package com.devsimple.leader_group;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.devsimple.leader_group.entity.User;
import com.devsimple.leader_group.service.UserDAOService;
import com.devsimple.leader_group.util.SequenceGenerator;
@Component
public class UserDaoServicecommandLineRunner implements CommandLineRunner {
private static final Logger log = LoggerFactory
.getLogger(UserDaoServicecommandLineRunner.class);
@Autowired
private UserDAOService userDaoService;
@Override
public void run(String... args) throws Exception {
User user = new User();
SequenceGenerator squ = new SequenceGenerator();
String id = "" + squ.nextId();
user.setId(id);
user.setFullname("Tai");
user.setEmail("taint@gmail.com");
user.setLang("vi");
user.setUsername("taint");
user.setPassword("123456");
user.setStatus(1);
userDaoService.insert(user);
log.info(user.toString());
}
}
| 27.923077 | 75 | 0.783287 |
7d6af827c8253e64b726a69f8130d9410b7f2f02 | 59 | package tk.dntree.service;
public interface Iservice {
}
| 9.833333 | 27 | 0.762712 |
3dabc1bae2a56e5f37f9e4d8bf56fe274f311cb1 | 461 | package fi.joniaromaa.parinacorelibrary.bukkit.nms.handlers;
import java.util.Map;
import java.util.UUID;
import com.comphenix.protocol.events.PacketEvent;
import fi.joniaromaa.parinacorelibrary.bukkit.ParinaCoreBukkitPlugin;
import fi.joniaromaa.parinacorelibrary.bukkit.nick.NickEntry;
public interface NmsHandlerNick
{
public void handleDeadmau5(ParinaCoreBukkitPlugin plugin, Map<UUID, Map<Integer, NickEntry>> nickEntryByEntity, PacketEvent event);
}
| 30.733333 | 132 | 0.841649 |
207c1d39e072408cebd5eea4075ce3261483d1b4 | 4,793 | package com.nd.pluto.writter.compile.visitor;
import com.llmofang.objectweb.asm.*;
import com.newrelic.agent.compile.InstrumentationContext;
import com.newrelic.agent.compile.Log;
import java.text.MessageFormat;
public class PrefilterClassVisitor
implements ClassVisitor {
private static final String TRACE_ANNOTATION_CLASSPATH = "Lcom/newrelic/agent/android/instrumentation/Trace;";
private static final String SKIP_TRACE_ANNOTATION_CLASSPATH = "Lcom/newrelic/agent/android/instrumentation/SkipTrace;";
private final InstrumentationContext context;
private final Log log;
public PrefilterClassVisitor(InstrumentationContext context, Log log) {
this.context = context;
this.log = log;
}
public void visit(int version, int access, String name, String sig, String superName, String[] interfaces) {
this.context.setClassName(name);
this.context.setSuperClassName(superName);
}
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
if (Annotations.isNewRelicAnnotation(desc)) {
this.log.info(MessageFormat.format("[{0}] class has New Relic tag: {1}", new Object[]{this.context.getClassName(), desc}));
this.context.addTag(desc);
}
return null;
}
public void visitAttribute(Attribute arg0) {
}
public void visitEnd() {
}
public FieldVisitor visitField(int access, String name, String desc, String sig, Object value) {
return null;
}
public void visitInnerClass(String arg0, String arg1, String arg2, int arg3) {
}
public MethodVisitor visitMethod(int access, final String name, final String desc, String signature, String[] exceptions) {
MethodVisitor methodVisitor = new MethodVisitor() {
public AnnotationVisitor visitAnnotationDefault() {
return null;
}
public AnnotationVisitor visitAnnotation(String annotationDesc, boolean visible) {
if (annotationDesc.equals("Lcom/newrelic/agent/android/instrumentation/Trace;")) {
PrefilterClassVisitor.this.context.addTracedMethod(name, desc);
return new TraceAnnotationVisitor(name, PrefilterClassVisitor.this.context);
}
if (annotationDesc.equals("Lcom/newrelic/agent/android/instrumentation/SkipTrace;")) {
PrefilterClassVisitor.this.context.addSkippedMethod(name, desc);
return null;
}
return null;
}
public AnnotationVisitor visitParameterAnnotation(int i, String s, boolean b) {
return null;
}
public void visitAttribute(Attribute attribute) {
}
public void visitCode() {
}
public void visitFrame(int i, int i2, Object[] objects, int i3, Object[] objects2) {
}
public void visitInsn(int i) {
}
public void visitIntInsn(int i, int i2) {
}
public void visitVarInsn(int i, int i2) {
}
public void visitTypeInsn(int i, String s) {
}
public void visitFieldInsn(int i, String s, String s2, String s3) {
}
public void visitMethodInsn(int i, String s, String s2, String s3) {
}
public void visitJumpInsn(int i, Label label) {
}
public void visitLabel(Label label) {
}
public void visitLdcInsn(Object o) {
}
public void visitIincInsn(int i, int i2) {
}
public void visitTableSwitchInsn(int i, int i2, Label label, Label[] labels) {
}
public void visitLookupSwitchInsn(Label label, int[] ints, Label[] labels) {
}
public void visitMultiANewArrayInsn(String s, int i) {
}
public void visitTryCatchBlock(Label label, Label label2, Label label3, String s) {
}
public void visitLocalVariable(String s, String s2, String s3, Label label, Label label2, int i) {
}
public void visitLineNumber(int i, Label label) {
}
public void visitMaxs(int i, int i2) {
}
public void visitEnd() {
}
};
return methodVisitor;
}
public void visitOuterClass(String arg0, String arg1, String arg2) {
}
public void visitSource(String arg0, String arg1) {
}
}
/* Location: /home/cw/class-rewriter/class-rewriter-4.120.0.jar
* Qualified Name: com.newrelic.agent.compile.visitor.PrefilterClassVisitor
* JD-Core Version: 0.6.2
*/ | 32.828767 | 135 | 0.611517 |
85b525585e3e1be0c92bdfe6a112f885f5430749 | 1,497 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/metastore/v1alpha/metastore.proto
package com.google.cloud.metastore.v1alpha;
public interface MaintenanceWindowOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.cloud.metastore.v1alpha.MaintenanceWindow)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The hour of day (0-23) when the window starts.
* </pre>
*
* <code>.google.protobuf.Int32Value hour_of_day = 1;</code>
* @return Whether the hourOfDay field is set.
*/
boolean hasHourOfDay();
/**
* <pre>
* The hour of day (0-23) when the window starts.
* </pre>
*
* <code>.google.protobuf.Int32Value hour_of_day = 1;</code>
* @return The hourOfDay.
*/
com.google.protobuf.Int32Value getHourOfDay();
/**
* <pre>
* The hour of day (0-23) when the window starts.
* </pre>
*
* <code>.google.protobuf.Int32Value hour_of_day = 1;</code>
*/
com.google.protobuf.Int32ValueOrBuilder getHourOfDayOrBuilder();
/**
* <pre>
* The day of week, when the window starts.
* </pre>
*
* <code>.google.type.DayOfWeek day_of_week = 2;</code>
* @return The enum numeric value on the wire for dayOfWeek.
*/
int getDayOfWeekValue();
/**
* <pre>
* The day of week, when the window starts.
* </pre>
*
* <code>.google.type.DayOfWeek day_of_week = 2;</code>
* @return The dayOfWeek.
*/
com.google.type.DayOfWeek getDayOfWeek();
}
| 26.732143 | 99 | 0.656647 |
159bef0788070151098821f093bda1c321ddce21 | 1,091 | package com.example.chessApp.cylinder;
import java.util.ArrayList;
public class RookCylinder extends PieceCylinder {
boolean hasMoved = false;
ArrayList<int[]> possibleMoves;
public RookCylinder(String name, boolean color, int x, int y){
super("r",color,x,y);
}
public boolean isLegitMove(int newx, int newy){
//ensure not trying to move off the board or to the same square
if (newx < 0 || newx > 7 || (newx == row && newy == col)){
return false;
}
//moving vertically
if (newy-col == 0){
return true;
}
//moving horizontally
else if(newx-row == 0){
return true;
}
return false;
}
public void moved(){
hasMoved = true;
}
//return all possible moves for this piece given its current position
//does NOT take into account current board position
public ArrayList<int[]> getPossibleMoves(){
ArrayList<int[]> possibleMoves = new ArrayList<int[]>();
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
if (this.isLegitMove(i,j)){
int[] pair = {i,j};
possibleMoves.add(pair);
}
}
}
return possibleMoves;
}
}
| 22.265306 | 70 | 0.648029 |
a547c2a8ce0337531a5f785e3dbc687b38f67450 | 1,450 | /*
* Copyright 2016 LinkedIn Corp.
*
* 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 common;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestUtil {
private static final Logger logger = LoggerFactory.getLogger(TestUtil.class);
// private on purpose
private TestUtil() {}
public static Properties loadProperties(String filePath)
throws IOException {
Properties properties = new Properties();
InputStream inputStream = TestUtil.class.getClassLoader().getResourceAsStream(filePath);
if (inputStream == null) {
logger.info("Configuation file not present in classpath. File: " + filePath);
throw new RuntimeException("Unable to read " + filePath);
}
properties.load(inputStream);
logger.info("Configuation file loaded. File: " + filePath);
return properties;
}
}
| 30.851064 | 92 | 0.735862 |
b3e4c1e0ac186ea18d97af1deaffe72f61f390b2 | 2,858 | /*
Copyright 2021 Adobe. All rights reserved.
This file is licensed 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
package com.adobe.s3fs.filesystemcheck.mapreduce;
import org.apache.hadoop.fs.Path;
import org.junit.Assert;
import org.junit.Test;
public class ParentShuffleCacheTest {
@Test
public void testCacheWithOneElementAndSamePath() {
ParentShuffleCache parentShuffleCache = new ParentShuffleCache(1);
Path path = new Path("ks://bucket/dir1/dir2/dir3/dir4/file");
Path parentPath = path.getParent();
// Element not present
Assert.assertTrue(parentShuffleCache.shuffleParent(parentPath));
// Element present
Assert.assertFalse(parentShuffleCache.shuffleParent(parentPath));
}
@Test
public void testCacheWithOneElementAndDifferentPaths() {
ParentShuffleCache parentShuffleCache = new ParentShuffleCache(1);
Path path = new Path("ks://bucket/dir1/dir2/dir3/dir4/file");
Path parentPath = path.getParent();
while (!parentPath.isRoot()) {
// Element not present
Assert.assertTrue(parentShuffleCache.shuffleParent(parentPath));
// Element present
Assert.assertFalse(parentShuffleCache.shuffleParent(parentPath));
parentPath = parentPath.getParent();
}
}
@Test
public void testCacheWithTwoElements() {
ParentShuffleCache parentShuffleCache = new ParentShuffleCache(2);
Path path1 = new Path("ks://bucket/dir1/dir2/dir3/dir4");
Path path2 = new Path("ks://bucket/dir1/dir2/dir3");
Path path3 = new Path("ks://bucket/dir1/dir2");
Path path4 = new Path("ks://bucket/dir1");
// Nothing present
Assert.assertTrue(parentShuffleCache.shuffleParent(path1));
Assert.assertTrue(parentShuffleCache.shuffleParent(path2));
// Path1 is retouched and becomes the newest element
Assert.assertFalse(parentShuffleCache.shuffleParent(path1));
// Path3 not present; will evict path2 (oldest element)
Assert.assertTrue(parentShuffleCache.shuffleParent(path3));
// Path1 still present (retouched and it becomes newest element)
Assert.assertFalse(parentShuffleCache.shuffleParent(path1));
// Path4 not present; will evict path3 (oldest element)
Assert.assertTrue(parentShuffleCache.shuffleParent(path4));
Assert.assertFalse(parentShuffleCache.hasParent(path2));
Assert.assertFalse(parentShuffleCache.hasParent(path3));
}
}
| 38.621622 | 86 | 0.751225 |
848652ac028e8697b4a32a54a418fab5f71ecccc | 34,935 | /*
* 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.nifi.processors.standard;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.behavior.DynamicProperty;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.InputRequirement.Requirement;
import org.apache.nifi.annotation.behavior.SupportsBatching;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.ValidationContext;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.logging.ProcessorLog;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.ssl.SSLContextService;
import org.apache.nifi.ssl.SSLContextService.ClientAuth;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
@SupportsBatching
@Tags({"http", "https", "rest", "client"})
@InputRequirement(Requirement.INPUT_REQUIRED)
@CapabilityDescription("An HTTP client processor which converts FlowFile attributes to HTTP headers, with configurable HTTP method, url, etc.")
@WritesAttributes({
@WritesAttribute(attribute = "invokehttp.status.code", description = "The status code that is returned"),
@WritesAttribute(attribute = "invokehttp.status.message", description = "The status message that is returned"),
@WritesAttribute(attribute = "invokehttp.response.body", description = "The response body"),
@WritesAttribute(attribute = "invokehttp.request.url", description = "The request URL"),
@WritesAttribute(attribute = "invokehttp.tx.id", description = "The transaction ID that is returned after reading the response"),
@WritesAttribute(attribute = "invokehttp.remote.dn", description = "The DN of the remote server")})
@DynamicProperty(name = "Trusted Hostname", value = "A hostname", description = "Bypass the normal truststore hostname verifier to allow the specified (single) remote hostname as trusted "
+ "Enabling this property has MITM security implications, use wisely. Only valid with SSL (HTTPS) connections.")
public final class InvokeHTTP extends AbstractProcessor {
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
return Config.PROPERTIES;
}
@Override
protected PropertyDescriptor getSupportedDynamicPropertyDescriptor(String propertyDescriptorName) {
if (Config.PROP_TRUSTED_HOSTNAME.getName().equalsIgnoreCase(propertyDescriptorName)) {
return Config.PROP_TRUSTED_HOSTNAME;
}
return super.getSupportedDynamicPropertyDescriptor(propertyDescriptorName);
}
@Override
public Set<Relationship> getRelationships() {
return Config.RELATIONSHIPS;
}
private volatile Pattern attributesToSend = null;
@Override
public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
final String trimmedValue = StringUtils.trimToEmpty(newValue);
// compile the attributes-to-send filter pattern
if (Config.PROP_ATTRIBUTES_TO_SEND.getName().equalsIgnoreCase(descriptor.getName())) {
if (newValue.isEmpty()) {
attributesToSend = null;
} else {
attributesToSend = Pattern.compile(trimmedValue);
}
}
}
@Override
protected Collection<ValidationResult> customValidate(final ValidationContext validationContext) {
final List<ValidationResult> results = new ArrayList<>(1);
final boolean proxyHostSet = validationContext.getProperty(Config.PROP_PROXY_HOST).isSet();
final boolean proxyPortSet = validationContext.getProperty(Config.PROP_PROXY_PORT).isSet();
if ((proxyHostSet && !proxyPortSet) || (!proxyHostSet && proxyPortSet)) {
results.add(new ValidationResult.Builder().subject("Proxy Host and Port").valid(false).explanation("If Proxy Host or Proxy Port is set, both must be set").build());
}
return results;
}
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
final FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
final SSLContextService sslService = context.getProperty(Config.PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
final SSLContext sslContext = sslService == null ? null : sslService.createSSLContext(ClientAuth.NONE);
Transaction transaction = new Transaction(getLogger(), sslContext, attributesToSend, context, session, flowFile);
transaction.process();
}
/**
* Stores properties, relationships, configuration values, hard coded strings, magic numbers, etc.
*/
public interface Config {
// flowfile attribute keys returned after reading the response
String STATUS_CODE = "invokehttp.status.code";
String STATUS_MESSAGE = "invokehttp.status.message";
String RESPONSE_BODY = "invokehttp.response.body";
String REQUEST_URL = "invokehttp.request.url";
String TRANSACTION_ID = "invokehttp.tx.id";
String REMOTE_DN = "invokehttp.remote.dn";
// Set of flowfile attributes which we generally always ignore during
// processing, including when converting http headers, copying attributes, etc.
// This set includes our strings defined above as well as some standard flowfile
// attributes.
public static final Set<String> IGNORED_ATTRIBUTES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
STATUS_CODE, STATUS_MESSAGE, RESPONSE_BODY, REQUEST_URL, TRANSACTION_ID, REMOTE_DN,
"uuid", "filename", "path")));
// properties
public static final PropertyDescriptor PROP_METHOD = new PropertyDescriptor.Builder()
.name("HTTP Method")
.description("HTTP request method (GET, POST, PUT, DELETE, HEAD, OPTIONS).")
.required(true)
.defaultValue("GET")
.expressionLanguageSupported(true)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor PROP_URL = new PropertyDescriptor.Builder()
.name("Remote URL")
.description("Remote URL which will be connected to, including scheme, host, port, path.")
.required(true)
.expressionLanguageSupported(true)
.addValidator(StandardValidators.URL_VALIDATOR)
.build();
public static final PropertyDescriptor PROP_CONNECT_TIMEOUT = new PropertyDescriptor.Builder()
.name("Connection Timeout")
.description("Max wait time for connection to remote service.")
.required(true)
.defaultValue("5 secs")
.addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
.build();
public static final PropertyDescriptor PROP_READ_TIMEOUT = new PropertyDescriptor.Builder()
.name("Read Timeout")
.description("Max wait time for response from remote service.")
.required(true)
.defaultValue("15 secs")
.addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
.build();
public static final PropertyDescriptor PROP_DATE_HEADER = new PropertyDescriptor.Builder()
.name("Include Date Header")
.description("Include an RFC-2616 Date header in the request.")
.required(true)
.defaultValue("True")
.allowableValues("True", "False")
.addValidator(StandardValidators.BOOLEAN_VALIDATOR)
.build();
public static final PropertyDescriptor PROP_FOLLOW_REDIRECTS = new PropertyDescriptor.Builder()
.name("Follow Redirects")
.description("Follow HTTP redirects issued by remote server.")
.required(true)
.defaultValue("True")
.allowableValues("True", "False")
.addValidator(StandardValidators.BOOLEAN_VALIDATOR)
.build();
public static final PropertyDescriptor PROP_ATTRIBUTES_TO_SEND = new PropertyDescriptor.Builder()
.name("Attributes to Send")
.description("Regular expression that defines which attributes to send as HTTP headers in the request. "
+ "If not defined, no attributes are sent as headers.")
.required(false)
.addValidator(StandardValidators.REGULAR_EXPRESSION_VALIDATOR)
.build();
public static final PropertyDescriptor PROP_SSL_CONTEXT_SERVICE = new PropertyDescriptor.Builder()
.name("SSL Context Service")
.description("The SSL Context Service used to provide client certificate information for TLS/SSL (https) connections.")
.required(false)
.identifiesControllerService(SSLContextService.class)
.build();
public static final PropertyDescriptor PROP_PROXY_HOST = new PropertyDescriptor.Builder()
.name("Proxy Host")
.description("The fully qualified hostname or IP address of the proxy server")
.required(false)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor PROP_PROXY_PORT = new PropertyDescriptor.Builder()
.name("Proxy Port")
.description("The port of the proxy server")
.required(false)
.addValidator(StandardValidators.PORT_VALIDATOR)
.build();
// Per RFC 7235, 2617, and 2616.
// basic-credentials = base64-user-pass
// base64-user-pass = userid ":" password
// userid = *<TEXT excluding ":">
// password = *TEXT
//
// OCTET = <any 8-bit sequence of data>
// CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
// LWS = [CRLF] 1*( SP | HT )
// TEXT = <any OCTET except CTLs but including LWS>
//
// Per RFC 7230, username & password in URL are now disallowed in HTTP and HTTPS URIs.
public static final PropertyDescriptor PROP_BASIC_AUTH_USERNAME = new PropertyDescriptor.Builder()
.name("Basic Authentication Username")
.displayName("Basic Authentication Username")
.description("The username to be used by the client to authenticate against the Remote URL. Cannot include control characters (0-31), ':', or DEL (127).")
.required(false)
.addValidator(StandardValidators.createRegexMatchingValidator(Pattern.compile("^[\\x20-\\x39\\x3b-\\x7e\\x80-\\xff]+$")))
.build();
public static final PropertyDescriptor PROP_BASIC_AUTH_PASSWORD = new PropertyDescriptor.Builder()
.name("Basic Authentication Password")
.displayName("Basic Authentication Password")
.description("The password to be used by the client to authenticate against the Remote URL.")
.required(false)
.sensitive(true)
.addValidator(StandardValidators.createRegexMatchingValidator(Pattern.compile("^[\\x20-\\x7e\\x80-\\xff]+$")))
.build();
public static final List<PropertyDescriptor> PROPERTIES = Collections.unmodifiableList(Arrays.asList(
PROP_METHOD,
PROP_URL,
PROP_SSL_CONTEXT_SERVICE,
PROP_CONNECT_TIMEOUT,
PROP_READ_TIMEOUT,
PROP_DATE_HEADER,
PROP_FOLLOW_REDIRECTS,
PROP_ATTRIBUTES_TO_SEND,
PROP_BASIC_AUTH_USERNAME,
PROP_BASIC_AUTH_PASSWORD,
PROP_PROXY_HOST,
PROP_PROXY_PORT));
// property to allow the hostname verifier to be overridden
// this is a "hidden" property - it's configured using a dynamic user property
public static final PropertyDescriptor PROP_TRUSTED_HOSTNAME = new PropertyDescriptor.Builder()
.name("Trusted Hostname")
.description("Bypass the normal truststore hostname verifier to allow the specified (single) remote hostname as trusted "
+ "Enabling this property has MITM security implications, use wisely. Only valid with SSL (HTTPS) connections.")
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.dynamic(true)
.build();
// relationships
public static final Relationship REL_SUCCESS_REQ = new Relationship.Builder()
.name("Original")
.description("Original FlowFile will be routed upon success (2xx status codes).")
.build();
public static final Relationship REL_SUCCESS_RESP = new Relationship.Builder()
.name("Response")
.description("Response FlowFile will be routed upon success (2xx status codes).")
.build();
public static final Relationship REL_RETRY = new Relationship.Builder()
.name("Retry")
.description("FlowFile will be routed on any status code that can be retried (5xx status codes).")
.build();
public static final Relationship REL_NO_RETRY = new Relationship.Builder()
.name("No Retry")
.description("FlowFile will be routed on any status code that should NOT be retried (1xx, 3xx, 4xx status codes).")
.build();
public static final Relationship REL_FAILURE = new Relationship.Builder()
.name("Failure")
.description("FlowFile will be routed on any type of connection failure, timeout or general exception.")
.build();
public static final Set<Relationship> RELATIONSHIPS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
REL_SUCCESS_REQ, REL_SUCCESS_RESP, REL_RETRY, REL_NO_RETRY, REL_FAILURE)));
}
/**
* A single invocation of an HTTP request/response from the InvokeHTTP processor. This class encapsulates the entirety of the flowfile processing.
* <p>
* This class is not thread safe and is created new for every flowfile processed.
*/
private static class Transaction implements Config {
/**
* Pattern used to compute RFC 2616 Dates (#sec3.3.1). This format is used by the HTTP Date header and is optionally sent by the processor. This date is effectively an RFC 822/1123 date
* string, but HTTP requires it to be in GMT (preferring the literal 'GMT' string).
*/
private static final String rfc1123 = "EEE, dd MMM yyyy HH:mm:ss 'GMT'";
private static final DateTimeFormatter dateFormat = DateTimeFormat.forPattern(rfc1123).withLocale(Locale.US).withZoneUTC();
/**
* Every request/response cycle from this client has a unique transaction id which will be stored as a flowfile attribute. This generator is used to create the id.
*/
private static final AtomicLong txIdGenerator = new AtomicLong();
private static final Charset utf8 = Charset.forName("UTF-8");
private final ProcessorLog logger;
private final SSLContext sslContext;
private final Pattern attributesToSend;
private final ProcessContext context;
private final ProcessSession session;
private final long txId = txIdGenerator.incrementAndGet();
private final long startNanos = System.nanoTime();
private FlowFile request;
private FlowFile response;
private HttpURLConnection conn;
private int statusCode;
private String statusMessage;
public Transaction(
final ProcessorLog logger,
final SSLContext sslContext,
final Pattern attributesToSend,
final ProcessContext context,
final ProcessSession session,
final FlowFile request) {
this.logger = logger;
this.sslContext = sslContext;
this.attributesToSend = attributesToSend;
this.context = context;
this.session = session;
this.request = request;
}
public void process() {
try {
openConnection();
sendRequest();
readResponse();
transfer();
} catch (final Exception e) {
// log exception
logger.error("Routing to {} due to exception: {}", new Object[] {REL_FAILURE.getName(), e}, e);
// penalize
request = session.penalize(request);
// transfer original to failure
session.transfer(request, REL_FAILURE);
// cleanup response flowfile, if applicable
try {
if (response != null) {
session.remove(response);
}
} catch (final Exception e1) {
logger.error("Could not cleanup response flowfile due to exception: {}", new Object[] {e1}, e1);
}
}
}
private void openConnection() throws IOException {
// read the url property from the context
final String urlstr = trimToEmpty(context.getProperty(PROP_URL).evaluateAttributeExpressions(request).getValue());
final URL url = new URL(urlstr);
final String authuser = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_USERNAME).getValue());
final String authpass = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_PASSWORD).getValue());
String authstrencoded = null;
if (!authuser.isEmpty()) {
String authstr = authuser + ":" + authpass;
byte[] bytestrencoded = Base64.encodeBase64(authstr.getBytes(StandardCharsets.UTF_8));
authstrencoded = new String(bytestrencoded, StandardCharsets.UTF_8);
}
// create the connection
final String proxyHost = context.getProperty(PROP_PROXY_HOST).getValue();
final Integer proxyPort = context.getProperty(PROP_PROXY_PORT).asInteger();
if (proxyHost == null || proxyPort == null) {
conn = (HttpURLConnection) url.openConnection();
} else {
final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
conn = (HttpURLConnection) url.openConnection(proxy);
}
if (authstrencoded != null) {
conn.setRequestProperty("Authorization", "Basic " + authstrencoded);
}
// set the request method
String method = trimToEmpty(context.getProperty(PROP_METHOD).evaluateAttributeExpressions(request).getValue()).toUpperCase();
conn.setRequestMethod(method);
// set timeouts
conn.setConnectTimeout(context.getProperty(PROP_CONNECT_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
conn.setReadTimeout(context.getProperty(PROP_READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
// set whether to follow redirects
conn.setInstanceFollowRedirects(context.getProperty(PROP_FOLLOW_REDIRECTS).asBoolean());
// special handling for https
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection sconn = (HttpsURLConnection) conn;
// check if the ssl context is set
if (sslContext != null) {
sconn.setSSLSocketFactory(sslContext.getSocketFactory());
}
// check the trusted hostname property and override the HostnameVerifier
String trustedHostname = trimToEmpty(context.getProperty(PROP_TRUSTED_HOSTNAME).getValue());
if (!trustedHostname.isEmpty()) {
sconn.setHostnameVerifier(new OverrideHostnameVerifier(trustedHostname, sconn.getHostnameVerifier()));
}
}
}
private void sendRequest() throws IOException {
// set the http request properties using flowfile attribute values
setRequestProperties();
// log request
logRequest();
// we only stream data for POST and PUT requests
String method = conn.getRequestMethod().toUpperCase();
if ("POST".equals(method) || "PUT".equals(method)) {
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(request.getSize());
// write the flowfile contents to the output stream
try (OutputStream os = new BufferedOutputStream(conn.getOutputStream())) {
session.exportTo(request, os);
}
// emit provenance event
session.getProvenanceReporter().send(request, conn.getURL().toExternalForm());
}
}
private void readResponse() throws IOException {
// output the raw response headers (DEBUG level only)
logResponse();
// store the status code and message
statusCode = conn.getResponseCode();
statusMessage = conn.getResponseMessage();
// always write the status attributes to the request flowfile
request = writeStatusAttributes(request);
// read from the appropriate input stream
try (InputStream is = getResponseStream()) {
// if not successful, store the response body into a flowfile attribute
if (!isSuccess()) {
String body = trimToEmpty(toString(is, utf8));
request = session.putAttribute(request, RESPONSE_BODY, body);
}
// if successful, store the response body as the flowfile payload
// we include additional flowfile attributes including the reponse headers
// and the status codes.
if (isSuccess()) {
// clone the flowfile to capture the response
response = session.create(request);
// write the status attributes
response = writeStatusAttributes(response);
// write the response headers as attributes
// this will overwrite any existing flowfile attributes
response = session.putAllAttributes(response, convertAttributesFromHeaders());
// transfer the message body to the payload
// can potentially be null in edge cases
if (is != null) {
response = session.importFrom(is, response);
// emit provenance event
final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
session.getProvenanceReporter().fetch(response, conn.getURL().toExternalForm(), millis);
}
}
}
}
private void transfer() throws IOException {
// check if we should penalize the request
if (!isSuccess()) {
request = session.penalize(request);
}
// log the status codes from the response
logger.info("Request to {} returned status code {} for {}",
new Object[] {conn.getURL().toExternalForm(), statusCode, request});
// transfer to the correct relationship
// 2xx -> SUCCESS
if (isSuccess()) {
// we have two flowfiles to transfer
session.transfer(request, REL_SUCCESS_REQ);
session.transfer(response, REL_SUCCESS_RESP);
// 5xx -> RETRY
} else if (statusCode / 100 == 5) {
session.transfer(request, REL_RETRY);
// 1xx, 3xx, 4xx -> NO RETRY
} else {
session.transfer(request, REL_NO_RETRY);
}
}
private void setRequestProperties() {
// check if we should send the a Date header with the request
if (context.getProperty(PROP_DATE_HEADER).asBoolean()) {
conn.setRequestProperty("Date", getDateValue());
}
// iterate through the flowfile attributes, adding any attribute that
// matches the attributes-to-send pattern. if the pattern is not set
// (it's an optional property), ignore that attribute entirely
if (attributesToSend != null) {
Map<String, String> attributes = request.getAttributes();
Matcher m = attributesToSend.matcher("");
for (Map.Entry<String, String> entry : attributes.entrySet()) {
String key = trimToEmpty(entry.getKey());
String val = trimToEmpty(entry.getValue());
// don't include any of the ignored attributes
if (IGNORED_ATTRIBUTES.contains(key)) {
continue;
}
// check if our attribute key matches the pattern
// if so, include in the request as a header
m.reset(key);
if (m.matches()) {
conn.setRequestProperty(key, val);
}
}
}
}
/**
* Returns a Map of flowfile attributes from the response http headers. Multivalue headers are naively converted to comma separated strings.
*/
private Map<String, String> convertAttributesFromHeaders() throws IOException {
// create a new hashmap to store the values from the connection
Map<String, String> map = new HashMap<>();
for (Map.Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
String key = entry.getKey();
if (key == null) {
continue;
}
List<String> values = entry.getValue();
// we ignore any headers with no actual values (rare)
if (values == null || values.isEmpty()) {
continue;
}
// create a comma separated string from the values, this is stored in the map
String value = csv(values);
// put the csv into the map
map.put(key, value);
}
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection sconn = (HttpsURLConnection) conn;
// this should seemingly not be required, but somehow the state of the jdk client is messed up
// when retrieving SSL certificate related information if connect() has not been called previously.
sconn.connect();
map.put(REMOTE_DN, sconn.getPeerPrincipal().getName());
}
return map;
}
private boolean isSuccess() throws IOException {
if (statusCode == 0) {
throw new IllegalStateException("Status code unknown, connection hasn't been attempted.");
}
return statusCode / 100 == 2;
}
private void logRequest() {
logger.debug("\nRequest to remote service:\n\t{}\n{}",
new Object[] {conn.getURL().toExternalForm(), getLogString(conn.getRequestProperties())});
}
private void logResponse() {
logger.debug("\nResponse from remote service:\n\t{}\n{}",
new Object[] {conn.getURL().toExternalForm(), getLogString(conn.getHeaderFields())});
}
private String getLogString(Map<String, List<String>> map) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
if (list.isEmpty()) {
continue;
}
sb.append("\t");
sb.append(entry.getKey());
sb.append(": ");
if (list.size() == 1) {
sb.append(list.get(0));
} else {
sb.append(list.toString());
}
sb.append("\n");
}
return sb.toString();
}
/**
* Convert a collection of string values into a overly simple comma separated string.
*
* Does not handle the case where the value contains the delimiter. i.e. if a value contains a comma, this method does nothing to try and escape or quote the value, in traditional csv style.
*/
private String csv(Collection<String> values) {
if (values == null || values.isEmpty()) {
return "";
}
if (values.size() == 1) {
return values.iterator().next();
}
StringBuilder sb = new StringBuilder();
for (String value : values) {
value = value.trim();
if (value.isEmpty()) {
continue;
}
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(value);
}
return sb.toString().trim();
}
/**
* Return the current datetime as an RFC 1123 formatted string in the GMT tz.
*/
private String getDateValue() {
return dateFormat.print(System.currentTimeMillis());
}
/**
* Returns a string from the input stream using the specified character encoding.
*/
private String toString(InputStream is, Charset charset) throws IOException {
if (is == null) {
return "";
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int len;
while ((len = is.read(buf)) != -1) {
out.write(buf, 0, len);
}
return new String(out.toByteArray(), charset);
}
/**
* Returns the input stream to use for reading from the remote server. We're either going to want the inputstream or errorstream, effectively depending on the status code.
* <p>
* This method can return null if there is no inputstream to read from. For example, if the remote server did not send a message body. eg. 204 No Content or 304 Not Modified
*/
private InputStream getResponseStream() {
try {
InputStream is = conn.getErrorStream();
if (is == null) {
is = conn.getInputStream();
}
return new BufferedInputStream(is);
} catch (IOException e) {
logger.warn("Response stream threw an exception: {}", new Object[] {e}, e);
return null;
}
}
/**
* Writes the status attributes onto the flowfile, returning the flowfile that was updated.
*/
private FlowFile writeStatusAttributes(FlowFile flowfile) {
flowfile = session.putAttribute(flowfile, STATUS_CODE, String.valueOf(statusCode));
flowfile = session.putAttribute(flowfile, STATUS_MESSAGE, statusMessage);
flowfile = session.putAttribute(flowfile, REQUEST_URL, conn.getURL().toExternalForm());
flowfile = session.putAttribute(flowfile, TRANSACTION_ID, Long.toString(txId));
return flowfile;
}
/**
*
*/
private static class OverrideHostnameVerifier implements HostnameVerifier {
private final String trustedHostname;
private final HostnameVerifier delegate;
private OverrideHostnameVerifier(String trustedHostname, HostnameVerifier delegate) {
this.trustedHostname = trustedHostname;
this.delegate = delegate;
}
@Override
public boolean verify(String hostname, SSLSession session) {
if (trustedHostname.equalsIgnoreCase(hostname)) {
return true;
}
return delegate.verify(hostname, session);
}
}
}
}
| 44.054224 | 198 | 0.623386 |
a021b4afc3dc1cc17b166ba2f13a84188d2761bf | 474 | package io.gen.study;
public class MulOptVisitor extends AbstractNodeVisitor{
@Override
public void visit(MulOpt node) {
int left = Integer.parseInt(node.getLeft());
int right = Integer.parseInt(node.getRight());
if ("*".equals(node.getOp())) {
System.out.println("multiply res = " + left * right);
}
if ("/".equals(node.getOp())) {
System.out.println("div res= " + left / right);
}
}
}
| 26.333333 | 65 | 0.567511 |
5e602abbf5a5e8c7ab1b617cab6772b5536697af | 6,989 | package xyz.e3ndr.jeofetch;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.fusesource.jansi.AnsiConsole;
import jline.internal.Ansi;
import xyz.e3ndr.consoleutil.ConsoleUtil;
import xyz.e3ndr.consoleutil.ansi.ConsoleAttribute;
import xyz.e3ndr.consoleutil.ansi.ConsoleColor;
import xyz.e3ndr.jeofetch.types.AsciiArt;
import xyz.e3ndr.jeofetch.types.CpuInfo;
import xyz.e3ndr.jeofetch.types.SystemInfo;
public class Jeofetch {
public static final int MAX_TABLE_WIDTH = 50;
public static final int MAX_HEIGHT = 20;
public static final SystemInfo osInfo = SystemUtils.getSystemInfo();
public static final CpuInfo cpuInfo = SystemUtils.getCpuInfo();
public static AsciiArt art;
public static String USERNAME;
public static String HOSTNAME;
static {
USERNAME = System.getProperty("user.name", "user");
try {
HOSTNAME = SystemUtils.getSystemHandler().getHostname();
} catch (UnknownHostException e) {
HOSTNAME = "localhost";
}
}
public static void print(Bootstrap config) throws InterruptedException, IOException {
try {
ConsoleUtil.clearConsole();
} catch (IOException ignored) {} ;
if (config.isHideSensitive()) {
USERNAME = "user";
HOSTNAME = "localhost";
}
if (!config.isNoArt()) {
art = OperatingSystems.getArtForSystem(config.getForced());
// if (!art.isValid()) {
// System.err.println("Invalid art.");
// System.exit(1);
// }
}
if (!config.isNoColor()) {
AnsiConsole.out.print(ConsoleAttribute.RESET.getAnsi());
}
char[][] display = getTable(!config.isNoColor(), config);
// Resize the array for the picture.
if (config.isNoArt()) {
// Draw the result.
for (char[] line : display) {
// Save some cpu.
if (config.isNoColor()) {
System.out.println(Ansi.stripAnsi(new String(line)));
} else {
ConsoleUtil.out.println(line);
}
}
} else {
char[][] artDisplay = art.draw(!config.isNoColor());
StringBuilder mergedDisplay = new StringBuilder();
for (int i = 0; i < MAX_HEIGHT; i++) {
String displayLine = (i < display.length) ? new String(display[i]) : "";
int nonColoredLength = Ansi.stripAnsi(displayLine).length();
if (nonColoredLength > MAX_TABLE_WIDTH) {
displayLine = displayLine.substring(0, MAX_TABLE_WIDTH);
} else if (nonColoredLength < MAX_TABLE_WIDTH) {
int remaining = MAX_TABLE_WIDTH - nonColoredLength;
displayLine = displayLine + explode(remaining);
}
mergedDisplay
.append(displayLine)
.append(artDisplay[i])
.append("\n");
}
if (config.isNoColor()) {
System.out.println(Ansi.stripAnsi(mergedDisplay.toString()));
} else {
ConsoleUtil.out.println(mergedDisplay);
}
}
System.out.println();
}
private static char[][] getTable(boolean enableColor, Bootstrap config) {
List<String> table = new LinkedList<>(
Arrays.asList(
String.format("\033[39m%s%s%s@%s%s", art.getThemeColor().getForeground(), USERNAME, "\033[39m", art.getThemeColor().getForeground(), HOSTNAME),
String.format("-------+-----------------------"),
String.format("OS | %s", osInfo.getOs()),
String.format("Kernel | %s", osInfo.getKernel()),
String.format("CPU | %s (%d) @ %.2fGHz", cpuInfo.getModel(), cpuInfo.getCoreCount(), cpuInfo.getClockSpeed())
)
);
if (config.getForced() != null) {
table.add(
String.format("Art | %s%s%s", ConsoleAttribute.BOLD.getAnsi(), art.getName(), ConsoleAttribute.RESET.getAnsi())
);
}
if (enableColor) {
// Spacer
table.add("");
table.add("");
// Color table
table.add("");
table.add("");
// Make the table colorful.
for (int i = 0; i < table.size(); i++) {
String[] line = table.get(i).split("\\|");
if (line.length > 1) {
table.set(i, String.format("%s%s%s|%s", art.getThemeColor().getForeground(), line[0], "\033[39m", line[1]));
}
// Reset the color at the end of the line.
table.set(i, table.get(i) + "\033[39m");
}
// Generate the color table.
ConsoleColor[] darkColors = {
ConsoleColor.BLACK,
ConsoleColor.RED,
ConsoleColor.GREEN,
ConsoleColor.YELLOW,
ConsoleColor.BLUE,
ConsoleColor.MAGENTA,
ConsoleColor.CYAN,
ConsoleColor.GRAY
};
ConsoleColor[] lightColors = {
ConsoleColor.DARK_GRAY,
ConsoleColor.LIGHT_RED,
ConsoleColor.LIGHT_GREEN,
ConsoleColor.LIGHT_YELLOW,
ConsoleColor.LIGHT_BLUE,
ConsoleColor.LIGHT_MAGENTA,
ConsoleColor.LIGHT_CYAN,
ConsoleColor.WHITE
};
StringBuilder darkColorsDisplay = new StringBuilder();
StringBuilder lightColorsDisplay = new StringBuilder();
for (ConsoleColor color : darkColors) {
darkColorsDisplay.append(color.getBackground()).append(" ");
}
for (ConsoleColor color : lightColors) {
lightColorsDisplay.append(color.getBackground()).append(" ");
}
darkColorsDisplay.append("\033[49m");
lightColorsDisplay.append("\033[49m");
// TODO Fix light color palette
table.set(table.size() - 2, darkColorsDisplay.toString());
table.set(table.size() - 1, lightColorsDisplay.toString());
}
char[][] tableChars = new char[table.size()][];
for (int i = 0; i < tableChars.length; i++) {
tableChars[i] = table.get(i).toCharArray();
}
return tableChars;
}
public static String explode(int length) {
char[] chars = new char[length];
for (int i = 0; i < chars.length; i++) {
chars[i] = ' ';
}
return new String(chars);
}
}
| 33.600962 | 159 | 0.53155 |
3b00cbc5f0450c50cfbc82c92fb1326fa0922749 | 1,193 | /**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2021 Ruhr University Bochum, Paderborn University, Hackmanit GmbH
*
* Licensed under Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package de.rub.nds.tlsattacker.attacks.padding;
import de.rub.nds.tlsattacker.attacks.padding.vector.PaddingVector;
import de.rub.nds.tlsattacker.core.constants.CipherSuite;
import de.rub.nds.tlsattacker.core.constants.ProtocolVersion;
import java.util.List;
/**
*
*
*/
public abstract class PaddingVectorGenerator {
/**
*
* @param suite
* @param version
* @return
*/
public abstract List<PaddingVector> getVectors(CipherSuite suite, ProtocolVersion version);
/**
* Creates an array of (padding+1) padding bytes.
*
* Example for padding 03: [03 03 03 03]
*
* @param padding
* @return
*/
protected final byte[] createPaddingBytes(int padding) {
byte[] paddingBytes = new byte[padding + 1];
for (int i = 0; i < paddingBytes.length; i++) {
paddingBytes[i] = (byte) padding;
}
return paddingBytes;
}
}
| 25.382979 | 95 | 0.658843 |
8684d927862ac434383700183ce518b4749e49f5 | 712 | package com.synopsys.integration.detectable.detectables.rubygems.gemspec;
public class GemspecParseDetectableOptions {
final boolean includeRuntimeDependencies;
final boolean includeDevelopmentDependencies;
public GemspecParseDetectableOptions(boolean includeRuntimeDependencies, boolean includeDevelopmentDependencies) {
this.includeRuntimeDependencies = includeRuntimeDependencies;
this.includeDevelopmentDependencies = includeDevelopmentDependencies;
}
public boolean shouldIncludeRuntimeDependencies() {
return includeRuntimeDependencies;
}
public boolean shouldIncludeDevelopmentDependencies() {
return includeDevelopmentDependencies;
}
}
| 35.6 | 118 | 0.803371 |
c20fa14a51ac452449ee148924894a949739545e | 1,531 | package io.github.spafka.leetcode.editor.cn;
//存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。
//
// 返回同样按升序排列的结果链表。
//
//
//
// 示例 1:
//
//
//输入:head = [1,2,3,3,4,4,5]
//输出:[1,2,5]
//
//
// 示例 2:
//
//
//输入:head = [1,1,1,2,3]
//输出:[2,3]
//
//
//
//
// 提示:
//
//
// 链表中节点数目在范围 [0, 300] 内
// -100 <= Node.val <= 100
// 题目数据保证链表已经按升序排列
//
// Related Topics 链表
// 👍 640 👎 0
import io.github.spafka.leetcode.editor.cn.io.github.spafka.common.ListNode;
/**
* 2021-06-19 23:41:18
*/
public class RemoveDuplicatesFromSortedListIi {
public static void main(String[] args) {
Solution solution = new RemoveDuplicatesFromSortedListIi().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(0, head);
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
if (cur.next.val == cur.next.next.val) {
int x = cur.next.val;
while (cur.next != null && cur.next.val == x) {
cur.next = cur.next.next;
}
} else {
cur = cur.next;
}
}
return dummy.next;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | 21.263889 | 82 | 0.5258 |
29573dade6b2e6982c7d1d24a30f11a47b5e1362 | 3,071 | /**
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.sakaiproject.nakamura.templates.velocity;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.log.LogChute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A proxy class from velocity to slf4j logging.
*/
public class VelocityLogger implements LogChute {
private Logger logger;
/**
* @param class1
*/
public VelocityLogger(Class<?> toLogClass) {
logger = LoggerFactory.getLogger(toLogClass);
}
/**
* {@inheritDoc}
*
* @see org.apache.velocity.runtime.log.LogChute#init(org.apache.velocity.runtime.RuntimeServices)
*/
public void init(RuntimeServices arg0) throws Exception {
}
/**
* {@inheritDoc}
*
* @see org.apache.velocity.runtime.log.LogChute#isLevelEnabled(int)
*/
public boolean isLevelEnabled(int level) {
switch (level) {
case LogChute.DEBUG_ID:
return logger.isDebugEnabled();
case LogChute.ERROR_ID:
return logger.isErrorEnabled();
case LogChute.INFO_ID:
return logger.isInfoEnabled();
case LogChute.TRACE_ID:
return logger.isTraceEnabled();
case LogChute.WARN_ID:
return logger.isWarnEnabled();
}
return false;
}
/**
* {@inheritDoc}
*
* @see org.apache.velocity.runtime.log.LogChute#log(int, String)
*/
public void log(int level, String msg) {
switch (level) {
case LogChute.DEBUG_ID:
logger.debug(msg);
break;
case LogChute.ERROR_ID:
logger.error(msg);
break;
case LogChute.INFO_ID:
logger.info(msg);
break;
case LogChute.TRACE_ID:
logger.trace(msg);
break;
case LogChute.WARN_ID:
logger.warn(msg);
break;
}
}
/**
* {@inheritDoc}
*
* @see org.apache.velocity.runtime.log.LogChute#log(int, String,
* Throwable)
*/
public void log(int level, String msg, Throwable t) {
switch (level) {
case LogChute.DEBUG_ID:
logger.debug(msg, t);
break;
case LogChute.ERROR_ID:
logger.error(msg, t);
break;
case LogChute.INFO_ID:
logger.info(msg, t);
break;
case LogChute.TRACE_ID:
logger.trace(msg, t);
break;
case LogChute.WARN_ID:
logger.warn(msg, t);
break;
}
}
}
| 25.591667 | 100 | 0.668838 |
6cb9d2da1213ee6f39ce8feb8db2702051236a77 | 9,627 | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import java.io.File;
import java.io.StringReader;
import java.lang.IllegalArgumentException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.io.pem.PemReader;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.amazonaws.encryptionsdk.internal.Utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory;
@RunWith(Parameterized.class)
public class XCompatDecryptTest {
private static final String STATIC_XCOMPAT_NAME = "static-aws-xcompat";
private static final String AES_GCM = "AES/GCM/NoPadding";
private static final byte XCOMPAT_MESSAGE_VERSION = 1;
private String plaintextFileName;
private String ciphertextFileName;
private MasterKeyProvider masterKeyProvider;
public XCompatDecryptTest(
String plaintextFileName,
String ciphertextFileName,
MasterKeyProvider masterKeyProvider
) throws Exception {
this.plaintextFileName = plaintextFileName;
this.ciphertextFileName = ciphertextFileName;
this.masterKeyProvider = masterKeyProvider;
}
@Parameters(name="{index}: testDecryptFromFile({0}, {1}, {2})")
public static Collection<Object[]> data() throws Exception{
String baseDirName;
baseDirName = System.getProperty("staticCompatibilityResourcesDir");
if (baseDirName == null) {
baseDirName =
XCompatDecryptTest.class.getProtectionDomain().getCodeSource().getLocation().getPath() +
"aws_encryption_sdk_resources";
}
List<Object[]> testCases_ = new ArrayList<Object[]>();
String ciphertextManifestName = StringUtils.join(
new String[]{
baseDirName,
"manifests",
"ciphertext.manifest"
},
File.separator
);
File ciphertextManifestFile = new File(ciphertextManifestName);
if (!ciphertextManifestFile.exists()) {
return Collections.emptySet();
}
ObjectMapper ciphertextManifestMapper = new ObjectMapper();
Map<String, Object> ciphertextManifest = ciphertextManifestMapper.readValue(
ciphertextManifestFile,
new TypeReference<Map<String, Object>>(){}
);
HashMap<String, HashMap<String, byte[]>> staticKeyMap = new HashMap<String, HashMap<String, byte[]>>();
Map<String, Object> testKeys = (Map<String, Object>)ciphertextManifest.get("test_keys");
for (Map.Entry<String, Object> keyType : testKeys.entrySet()) {
Map<String, Object> keys = (Map<String, Object>)keyType.getValue();
HashMap<String, byte[]> thisKeyType = new HashMap<String, byte[]>();
for (Map.Entry<String, Object> key : keys.entrySet()) {
Map<String, Object> thisKey = (Map<String, Object>)key.getValue();
String keyRaw = new String(
StringUtils.join(
(List<String>)thisKey.get("key"),
(String)thisKey.getOrDefault("line_separator", "")
).getBytes(),
StandardCharsets.UTF_8
);
byte[] keyBytes;
switch ((String)thisKey.get("encoding")) {
case "base64":
keyBytes = Utils.decodeBase64String(keyRaw);
break;
case "pem":
PemReader pemReader = new PemReader(new StringReader(keyRaw));
keyBytes = pemReader.readPemObject().getContent();
break;
case "raw":
default:
keyBytes = keyRaw.getBytes();
}
thisKeyType.put((String)key.getKey(), keyBytes);
}
staticKeyMap.put((String)keyType.getKey(), thisKeyType);
}
final KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");
List<Map<String, Object>> testCases = (List<Map<String, Object>>)ciphertextManifest.get("test_cases");
for (Map<String, Object> testCase : testCases) {
Map<String, String> plaintext = (Map<String, String>)testCase.get("plaintext");
Map<String, String> ciphertext = (Map<String, String>)testCase.get("ciphertext");
short algId = (short) Integer.parseInt((String)testCase.get("algorithm"), 16);
CryptoAlgorithm encryptionAlgorithm = CryptoAlgorithm.deserialize(XCOMPAT_MESSAGE_VERSION, algId);
List<Map<String, Object>> masterKeys = (List<Map<String, Object>>)testCase.get("master_keys");
List<JceMasterKey> allMasterKeys = new ArrayList<JceMasterKey>();
for (Map<String, Object> aMasterKey : masterKeys) {
String providerId = (String)aMasterKey.get("provider_id");
if (providerId.equals(STATIC_XCOMPAT_NAME) && (boolean)aMasterKey.get("decryptable")) {
String paddingAlgorithm = (String)aMasterKey.getOrDefault("padding_algorithm", "");
String paddingHash = (String)aMasterKey.getOrDefault("padding_hash", "");
Integer keyBits = (Integer)aMasterKey.getOrDefault(
"key_bits",
encryptionAlgorithm.getDataKeyLength() * 8
);
String keyId =
(String)aMasterKey.get("encryption_algorithm") + "." +
keyBits.toString() + "." +
paddingAlgorithm + "." +
paddingHash;
String encAlg = (String)aMasterKey.get("encryption_algorithm");
switch (encAlg.toUpperCase()) {
case "RSA":
String cipherBase = "RSA/ECB/";
String cipherName;
switch (paddingAlgorithm) {
case "OAEP-MGF1":
cipherName = cipherBase + "OAEPWith" + paddingHash + "AndMGF1Padding";
break;
case "PKCS1":
cipherName = cipherBase + paddingAlgorithm + "Padding";
break;
default:
throw new IllegalArgumentException("Unknown padding algorithm: " + paddingAlgorithm);
}
PrivateKey privKey = rsaKeyFactory.generatePrivate(new PKCS8EncodedKeySpec(staticKeyMap.get("RSA").get(keyBits.toString())));
allMasterKeys.add(JceMasterKey.getInstance(
null,
privKey,
STATIC_XCOMPAT_NAME,
keyId,
cipherName
));
break;
case "AES":
SecretKeySpec spec = new SecretKeySpec(
staticKeyMap.get("AES").get(keyBits.toString()),
0,
encryptionAlgorithm.getDataKeyLength(),
encryptionAlgorithm.getDataKeyAlgo()
);
allMasterKeys.add(JceMasterKey.getInstance(spec, STATIC_XCOMPAT_NAME, keyId, AES_GCM));
break;
default:
throw new IllegalArgumentException("Unknown encryption algorithm: " + encAlg.toUpperCase());
}
}
}
if (allMasterKeys.size() > 0) {
final MasterKeyProvider<?> provider = MultipleProviderFactory.buildMultiProvider(allMasterKeys);
testCases_.add(new Object[]{
baseDirName + File.separator + plaintext.get("filename"),
baseDirName + File.separator + ciphertext.get("filename"),
provider
});
}
}
return testCases_;
}
@Test
public void testDecryptFromFile() throws Exception {
AwsCrypto crypto = AwsCrypto.standard();
byte ciphertextBytes[] = Files.readAllBytes(Paths.get(ciphertextFileName));
byte plaintextBytes[] = Files.readAllBytes(Paths.get(plaintextFileName));
final CryptoResult decryptResult = crypto.decryptData(
masterKeyProvider,
ciphertextBytes
);
assertArrayEquals(plaintextBytes, (byte[])decryptResult.getResult());
}
}
| 44.364055 | 153 | 0.572868 |
240e583219d597a69a03a889b7a3b82487bfbbbe | 762 | package LeetCode.src.Explore.Interview.GoogleInterview.TreesAndGraphs.ClosestBinarySearchTreeValue.Java;
public class Solution {
public static void main(String[] args) {
int[] values = {
4,
2, 5,
1, 3, -1, -1};
TreeNode root = TreeNode.fromArray(values);
double target = 3.714286;
System.out.println(closestValue(root, target));
}
public static int closestValue(TreeNode root, double target) {
int ret = root.val;
while(root != null){
if(Math.abs(target - root.val) < Math.abs(target - ret)) {
ret = root.val;
}
root = root.val > target? root.left: root.right;
}
return ret;
}
} | 31.75 | 104 | 0.551181 |
f90aa7efba65806e249bc2bd72afb565def2a916 | 1,666 | package com.davigotxi.ohalodics.service;
import com.davigotxi.ohalodics.model.AnnotatedText.Annotation;
import com.davigotxi.ohalodics.model.AnnotatedText.Annotation.Index;
import org.ahocorasick.trie.Emit;
import org.ahocorasick.trie.Trie;
import java.util.*;
/**
* Finds matches based on the Aho-Corasick algorithm. This implementation matches only full words
*/
public class AhoCorasickTextFinder implements TextFinder {
/**
* {@inheritDoc}
* @param targetText
* @param entries
* @param caseSensitive
* @return
*/
@Override
public Collection<Annotation> findMatches(String targetText, List<String> entries, boolean caseSensitive) {
var trie = buildTrie(entries, caseSensitive);
Collection<Emit> matches = trie.parseText(targetText);
return createAnnotationsFrom(matches);
}
private Trie buildTrie(List<String> entries, boolean caseSensitive) {
var trieBuilder = Trie.builder().onlyWholeWords();
if (!caseSensitive) {
trieBuilder.ignoreCase();
}
entries.stream().forEach(trieBuilder::addKeyword);
return trieBuilder.build();
}
private Collection<Annotation> createAnnotationsFrom(Collection<Emit> matches) {
Map<String, Annotation> annotationsLookup = new HashMap<>();
matches.stream().forEach(m -> {
var keyword = m.getKeyword();
var annotation = annotationsLookup.computeIfAbsent(keyword, k -> new Annotation(k, new ArrayList<>()));
annotation.getIndexes().add(new Index(m.getStart(), m.getEnd() + 1));
});
return annotationsLookup.values();
}
}
| 33.32 | 115 | 0.680072 |
af059570e510d89ab8c2b3255b8f4d7db5ba3711 | 1,662 | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.egeria.connectors.ibm.ia.clientlibrary.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class VirtualColumn extends Column {
@JacksonXmlProperty(localName = "Concatenation")
private Concatenation concatenation;
@JacksonXmlProperty(localName = "DataRuleExpression")
private String dataRuleExpression;
@JacksonXmlProperty(localName = "SQLExpression")
private SQLExpression sqlExpression;
public Concatenation getConcatenation() { return concatenation; }
public void setConcatenation(Concatenation concatenation) { this.concatenation = concatenation; }
public String getDataRuleExpression() { return dataRuleExpression; }
public void setDataRuleExpression(String dataRuleExpression) { this.dataRuleExpression = dataRuleExpression; }
public SQLExpression getSqlExpression() { return sqlExpression; }
public void setSqlExpression(SQLExpression sqlExpression) { this.sqlExpression = sqlExpression; }
@Override
public String toString() {
String parent = super.toString();
return parent.substring(0, parent.length() - 2)
+ ", \"Concatenation\": " + (concatenation == null ? "{}" : concatenation.toString())
+ ", \"DataRuleExpression\": \"" + dataRuleExpression
+ "\", \"SQLExpression\": " + (sqlExpression == null ? "{}" : sqlExpression.toString())
+ " }";
}
}
| 44.918919 | 114 | 0.717208 |
1f4d72cbd0488bf7f22b805c9cff9a56bee5f7fb | 771 | package com.example.rentalcarsrestapi.controllers;
import com.example.rentalcarsrestapi.model.User;
import com.example.rentalcarsrestapi.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/users")
public List<User> showAllUsers() {
return userService.showAllUsers();
}
}
| 32.125 | 64 | 0.796368 |
0a17a3a9c079f4f690b62ea9734fc1a107e0bb8c | 4,853 | package org.redisson;
import java.util.BitSet;
import org.redisson.api.RBitSet;
import org.redisson.api.RFuture;
import com.newrelic.api.agent.weaver.MatchType;
import com.newrelic.api.agent.weaver.Weave;
import com.newrelic.api.agent.weaver.Weaver;
import com.nr.instrumentation.redisson.Utils;
@Weave(type=MatchType.BaseClass)
public abstract class RedissonBitSet implements RBitSet {
public RFuture<Boolean> getAsync(long bitIndex) {
if(!Utils.operationIsSet()) {
Utils.setOperation("GET");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> setAsync(long bitIndex, boolean value) {
if(!Utils.operationIsSet()) {
Utils.setOperation("SET");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<byte[]> toByteArrayAsync() {
if(!Utils.operationIsSet()) {
Utils.setOperation("toByteArray");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Long> lengthAsync() {
if(!Utils.operationIsSet()) {
Utils.setOperation("LENGTH");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> setAsync(long fromIndex, long toIndex, boolean value) {
if(!Utils.operationIsSet()) {
Utils.setOperation("SET");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> clearAsync(long fromIndex, long toIndex) {
if(!Utils.operationIsSet()) {
Utils.setOperation("CLEAR");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> setAsync(BitSet bs) {
if(!Utils.operationIsSet()) {
Utils.setOperation("GET");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> notAsync() {
if(!Utils.operationIsSet()) {
Utils.setOperation("NOT");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> setAsync(long fromIndex, long toIndex) {
if(!Utils.operationIsSet()) {
Utils.setOperation("SET");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Integer> sizeAsync() {
if(!Utils.operationIsSet()) {
Utils.setOperation("SIZE");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Long> cardinalityAsync() {
if(!Utils.operationIsSet()) {
Utils.setOperation("CARDINALITY");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> clearAsync(long bitIndex) {
if(!Utils.operationIsSet()) {
Utils.setOperation("CLEAR");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> clearAsync() {
if(!Utils.operationIsSet()) {
Utils.setOperation("CLEAR");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> orAsync(String... bitSetNames) {
if(!Utils.operationIsSet()) {
Utils.setOperation("OR");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> andAsync(String... bitSetNames) {
if(!Utils.operationIsSet()) {
Utils.setOperation("AND");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
public RFuture<Void> xorAsync(String... bitSetNames) {
if(!Utils.operationIsSet()) {
Utils.setOperation("XOR");
}
if(!Utils.typeSet()) {
Utils.setType(this);
}
if(!Utils.objectNameSet()) {
Utils.setObjectName(getName());
}
return Weaver.callOriginal();
}
}
| 20.136929 | 77 | 0.661034 |
880358c110d33998b434ffdb37793264da51d942 | 813 | package io.mappingdsl.core.tests.fixtures;
import io.mappingdsl.core.tests.fixtures.common.NamedObject;
import io.mappingdsl.core.tests.fixtures.common.timezone.TimeZone;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@NoArgsConstructor
public class CountryDto extends NamedObject {
@Getter
@Setter
private SettlementDto capital;
@Getter
@Setter
private List<? extends SettlementDto> biggestCities;
@Getter
@Setter
private Number population;
@Getter
@Setter
private CharSequence[] nationalLanguages;
@Getter
@Setter
private Iterable<String> nationalCurrencies;
@Getter
@Setter
private List<TimeZone> timeZones;
public CountryDto(String name) {
super(name);
}
}
| 18.906977 | 66 | 0.723247 |
a112453c8c28cbf5731d8dd04e64c926eea08781 | 2,598 | package net.dougteam.doug.client.utility.utilities;
import java.util.HashMap;
import com.darkmagician6.eventapi.EventTarget;
import org.lwjgl.glfw.GLFW;
// import org.lwjgl.util.vector.Matrix3f;
// import org.lwjgl.util.vector.Vector2f;
// import org.lwjgl.util.vector.Vector3f;
import net.dougteam.doug.client.utility.Utility;
import net.dougteam.doug.events.TickEvent;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ingame.GenericContainerScreen;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.item.Items;
import net.minecraft.network.packet.c2s.play.ClickSlotC2SPacket;
import net.minecraft.screen.slot.Slot;
import net.minecraft.screen.slot.SlotActionType;
public class AutoLoot extends Utility {
public AutoLoot() {
super("AutoLoot", GLFW.GLFW_KEY_GRAVE_ACCENT, Category.Player);
}
@Override
public void onDisable() {
// TODO Auto-generated method stub
super.onDisable();
}
@Override
public Boolean enabled() {
// TODO Auto-generated method stub
return super.enabled();
}
@EventTarget
public void tick(TickEvent te) {
MinecraftClient mc = MinecraftClient.getInstance();
if (mc.currentScreen instanceof GenericContainerScreen) {
GenericContainerScreen gcs = (GenericContainerScreen) mc.currentScreen;
for (Slot s : gcs.getScreenHandler().slots) {
System.out.println(s.id);
if(mc.player.age % 10 == s.id % 10) {
if (s.id <= 27) {
if (s.getStack().getItem().isDamageable() || s.getStack().getItem().isFood()
|| s.getStack().getItem() == Items.GOLDEN_APPLE || s.getStack().getItem() == Items.BEEF) {
mc.getNetworkHandler().sendPacket(new ClickSlotC2SPacket(gcs.getScreenHandler().syncId, s.id, 1,
SlotActionType.QUICK_MOVE, s.getStack(), (short) s.id));
}
}
}
}
// mc.currentScreen.onClose();
}
}
}
/*
* abstract private static bool CalcAngle(Vec3 source, Vec3 target, out Vec2
* viewAngles) { Vec2 angles;
*
* Vec3 delta = source - target; float hyp = Vec3.Distance(source, target);
* angles.X = (float)(Math.Atan(delta.Z / hyp) * 180.0f / Math.PI); angles.Y =
* (float)(Math.Atan(delta.Y / delta.X) * 180.0f / Math.PI);
*
* if (delta.X >= 0.0f) angles.Y += 180.0f;
*
* viewAngles = angles;
*
* return true; }
*/ | 32.886076 | 124 | 0.626251 |
cd0131598f966a075f81896daa282209db96c8ed | 4,909 | /**
*
*/
package repast.simphony.statecharts.handlers;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Status;
import repast.simphony.eclipse.util.DirectoryCleaner;
import repast.simphony.statecharts.generator.CodeGenerator;
import repast.simphony.statecharts.generator.CodeGeneratorConstants;
import repast.simphony.statecharts.generator.OrphanFilter;
import repast.simphony.statecharts.part.StatechartDiagramEditorPlugin;
import repast.simphony.statecharts.svg.SVGExporter;
/**
* @author Nick Collier
*/
public class StatechartBuilder extends IncrementalProjectBuilder {
public static final String STATECHART_EXTENSION = "rsc";
public static final String STATECHART_BUILDER = StatechartDiagramEditorPlugin.ID + ".builder";
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IncrementalProjectBuilder#build(int,
* java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
protected IProject[] build(int kind, Map<String, String> args, IProgressMonitor monitor)
throws CoreException {
try {
if (kind == IncrementalProjectBuilder.FULL_BUILD) {
fullBuild(monitor);
} else {
IResourceDelta delta = getDelta(getProject());
if (delta == null) {
fullBuild(monitor);
} else {
incrementalBuild(delta, monitor);
}
}
} catch (CoreException ex) {
throw new CoreException(new Status(IResourceStatus.BUILD_FAILED,
StatechartDiagramEditorPlugin.ID, ex.getLocalizedMessage(), ex));
}
return null;
}
private void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor)
throws CoreException {
delta.accept(new Visitor(getProject(), monitor));
}
private void fullBuild(IProgressMonitor monitor) throws CoreException {
FullBuildVisitor visitor = new FullBuildVisitor(getProject(), monitor);
getProject().accept(visitor);
visitor.removeOrphans();
getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
private static class FullBuildVisitor implements IResourceVisitor {
IProgressMonitor monitor;
IProject project;
CodeGenerator generator;
public FullBuildVisitor(IProject project, IProgressMonitor monitor) {
this.monitor = monitor;
this.project = project;
generator = new CodeGenerator();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IResourceVisitor#visit(org.eclipse.core
* .resources.IResource)
*/
@Override
public boolean visit(IResource resource) throws CoreException {
IPath path = resource.getRawLocation();
if (path != null && path.getFileExtension() != null
&& path.getFileExtension().equals(STATECHART_EXTENSION)) {
IPath srcPath = generator.run(project, path, monitor);
if (srcPath != null) {
new SVGExporter().run(path, srcPath, monitor);
project.getFolder(srcPath.lastSegment()).refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
}
return true;
}
public void removeOrphans() {
OrphanFilter filter = new OrphanFilter(generator.getGeneratorRecord());
DirectoryCleaner cleaner = new DirectoryCleaner(filter);
String rootPath = project.getLocation().append(CodeGeneratorConstants.SRC_GEN).toFile().getAbsolutePath();
cleaner.run(rootPath);
}
}
private static class Visitor implements IResourceDeltaVisitor {
IProgressMonitor monitor;
IProject project;
public Visitor(IProject project, IProgressMonitor monitor) {
this.monitor = monitor;
this.project = project;
}
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
IPath path = delta.getResource().getRawLocation();
// System.out.println("statechart builder running: " + delta);
if ((delta.getKind() == IResourceDelta.CHANGED || delta.getKind() == IResourceDelta.ADDED)
&& path != null && path.getFileExtension() != null
&& path.getFileExtension().equals(STATECHART_EXTENSION)) {
// create svg file here
IPath srcPath = new CodeGenerator().run(project, path, monitor);
if (srcPath != null) {
new SVGExporter().run(path, srcPath, monitor);
project.getFolder(srcPath.lastSegment()).refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
}
return true;
}
}
}
| 34.570423 | 112 | 0.710532 |
666f17816adc6d3ece5ad01a4044fe489926baca | 1,812 | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package io.github.mmm.ui.api.datatype.media;
import io.github.mmm.ui.api.attribute.AttributeReadLanguage;
import io.github.mmm.ui.api.attribute.AttributeReadUrl;
import io.github.mmm.ui.api.widget.AbstractUiWidget;
/**
* Datatype representing a track of a {@link UiMedia}. It {@link #getUrl() points} to metadata (e.g. captions).
*
* @since 1.0.0
*/
public final class UiMediaTrack implements AttributeReadUrl, AttributeReadLanguage {
/** Supported {@link #getKind() kind} {@value}. */
public static final String KIND_CAPTIONS = "captions";
private final String source;
private final String kind;
private final String language;
private final String label;
/**
* The constructor.
*
* @param source the {@link #getUrl() source}.
* @param kind the {@link #getKind() kind}.
* @param language the {@link #getLanguage() language}.
* @param label the {@link #getLabel() label}.
*/
public UiMediaTrack(String source, String kind, String language, String label) {
super();
if (AbstractUiWidget.isEmpty(source)) {
throw new IllegalArgumentException("source=" + source);
}
this.source = source;
this.kind = kind;
this.language = language;
this.label = label;
}
@Override
public String getUrl() {
return this.source;
}
/**
* @return the kind of this track (e.g. {@link #KIND_CAPTIONS captions}).
*/
public String getKind() {
return this.kind;
}
@Override
public String getLanguage() {
return this.language;
}
/**
* @return the label with the text displayed to the end-user to choose this track.
*/
public String getLabel() {
return this.label;
}
}
| 23.842105 | 111 | 0.672737 |
a8584b818522f50203ddb7c2b7eacec9e0fe7482 | 2,715 | package at.ac.htl.leonding.workloads.user;
import at.ac.htl.leonding.workloads.playlist.Playlist;
import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "\"User\"")
public class User extends PanacheEntityBase {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public String username, name, lastname, email, password;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
public List<Playlist> playlistList = new ArrayList<>();
public static User create(String username, String name, String lastname, String email, String password) {
var newUser = new User();
newUser.setName(name);
newUser.setLastname(lastname);
newUser.setUsername(username);
newUser.setEmail(email);
newUser.setPassword(password);
return newUser;
}
public Playlist addPlaylist(String name, long id) {
Playlist playlistnew = new Playlist();
playlistnew.setName(name);
//playlistnew.setId(id);
playlistnew.setUser(this);
System.out.println("hilfe");
// System.out.println(this.name + "test");
this.playlistList.add(playlistnew);
return playlistnew;
//playlist.setUser(this);
//playlist.setUser(this);
}
public User(String username, String name, String lastname, String email, String password) {
this.username = username;
this.name = name;
this.lastname = lastname;
this.email = email;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Playlist> getPlaylistList() {
return playlistList;
}
public void setPlaylistList(List<Playlist> playlistList) {
this.playlistList = playlistList;
}
}
| 23.008475 | 109 | 0.628361 |
be92bdf09c730fb841e8795e01fab3bd287fe834 | 985 |
import java.util.*;
public class father extends parent_unit
{
//A father. Can be matched with one mother and have one child. Fathers pass down their class and and skill options
//to their child. Unlike mothers, children are not assigned to father.
//object chrom in main_code is the only father that does have a child assigned to them.
static ArrayList<father> all_fathers=new ArrayList<father>();
//Initiates father()
//Takes as peramaters: a String refering to what this father will be called, an array of class_units that this father
//has access to, and a list of ints, refering to what this father's stat modifiers are (how they will differ from others
//when assigned a class.)
public father(String name, unit_class[] classes_availible, int[] stat_modifier)
{
super(name, false, classes_availible, stat_modifier);
matched_with=null;
all_fathers.add(this);
}
}
| 36.481481 | 125 | 0.686294 |
c28d8edef3f7ff8a9d87955972a872072619f57b | 1,728 | package help.mygod.query.repository;
import java.util.Optional;
import javax.persistence.EntityManager;
import org.springframework.data.jpa.provider.PersistenceProvider;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
import org.springframework.data.repository.query.QueryMethodEvaluationContextProvider;
import org.springframework.lang.Nullable;
public class NativeJpaRepositoryFactory extends JpaRepositoryFactory {
private final EntityManager entityManager;
private final PersistenceProvider extractor;
public NativeJpaRepositoryFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
this.extractor = PersistenceProvider.fromEntityManager(entityManager);
}
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
// TODO Auto-generated method stub
return BaseRepositoryImpl.class;
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getQueryLookupStrategy(org.springframework.data.repository.query.QueryLookupStrategy.Key, org.springframework.data.repository.query.EvaluationContextProvider)
*/
@Override
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(@Nullable Key key,
QueryMethodEvaluationContextProvider evaluationContextProvider) {
return Optional.of(NativeQueryLookupStrategy.create(entityManager, key, extractor, evaluationContextProvider));
}
}
| 36.765957 | 242 | 0.817708 |
fe4e392a6b73c940390f0b78e34106fe8477424d | 2,667 | package A05_Breitensuche;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class BreitensucheTest {
private Breitensuche bs;
@Before
public void setUp() throws Exception {
bs = new Breitensuche();
bs.add(6);
bs.add(3);
bs.add(10);
bs.add(5);
bs.add(2);
bs.add(1);
bs.add(12);
bs.add(11);
bs.add(15);
}
@Test
public void getBreadthFirstOrder1() {
List<Integer> li = bs.getBreadthFirstOrder(bs.find(15));
assertEquals(1, li.size());
assertEquals(15, li.get(0).intValue());
}
@Test
public void getBreadthFirstOrder2() {
List<Integer> li = bs.getBreadthFirstOrder(bs.find(12));
assertEquals(3, li.size());
assertEquals(12, li.get(0).intValue());
assertEquals(11, li.get(1).intValue());
assertEquals(15, li.get(2).intValue());
}
@Test
public void getBreadthFirstOrder3() {
List<Integer> li = bs.getBreadthFirstOrder(bs.getRoot());
assertEquals(9, li.size());
assertEquals(6, li.get(0).intValue());
assertEquals(3, li.get(1).intValue());
assertEquals(10, li.get(2).intValue());
assertEquals(2, li.get(3).intValue());
assertEquals(5, li.get(4).intValue());
assertEquals(12, li.get(5).intValue());
assertEquals(1, li.get(6).intValue());
assertEquals(11, li.get(7).intValue());
assertEquals(15, li.get(8).intValue());
}
@Test
public void getBreadthFirstOrderForLevel1() {
List<Integer> li = bs.getBreadthFirstOrderForLevel(bs.getRoot(), 1);
assertEquals(1, li.size());
assertEquals(6, li.get(0).intValue());
}
@Test
public void getBreadthFirstOrderForLevel2() {
List<Integer> li = bs.getBreadthFirstOrderForLevel(bs.getRoot(), 2);
assertEquals(2, li.size());
assertEquals(3, li.get(0).intValue());
assertEquals(10, li.get(1).intValue());
}
@Test
public void getBreadthFirstOrderForLevel3() {
List<Integer> li = bs.getBreadthFirstOrderForLevel(bs.getRoot(), 3);
assertEquals(3, li.size());
assertEquals(2, li.get(0).intValue());
assertEquals(5, li.get(1).intValue());
assertEquals(12, li.get(2).intValue());
}
@Test
public void getBreadthFirstOrderForLevel4() {
List<Integer> li = bs.getBreadthFirstOrderForLevel(bs.find(3), 2);
assertEquals(2, li.size());
assertEquals(2, li.get(0).intValue());
assertEquals(5, li.get(1).intValue());
}
@Test
public void getBreadthFirstOrderForLevel5() {
List<Integer> li = bs.getBreadthFirstOrderForLevel(bs.find(11), 5);
assertEquals(0, li.size());
li = bs.getBreadthFirstOrderForLevel(bs.find(11), 2);
assertEquals(0, li.size());
}
}
| 26.67 | 71 | 0.661792 |
8dee537ca499ded093423bd45fa4abb8bdda4512 | 1,135 | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. 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.wso2.developerstudio.eclipse.gmf.esb;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Property Group Mediator Output Connector</b></em>'.
* <!-- end-user-doc -->
*
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getPropertyGroupMediatorOutputConnector()
* @model
* @generated
*/
public interface PropertyGroupMediatorOutputConnector extends OutputConnector {
} // PropertyGroupMediatorOutputConnector
| 37.833333 | 101 | 0.735683 |
850f59ceb49ba0cf57e2abb22035a6af4350ecaf | 4,651 | /*
* Copyright (c) 2012, the Last.fm Java Project and Committers
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED 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 de.umass.lastfm;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import de.umass.xml.DomElement;
import static de.umass.util.StringUtilities.isMD5;
import static de.umass.util.StringUtilities.map;
import static de.umass.util.StringUtilities.md5;
/**
* Provides bindings for the authentication methods of the last.fm API.
* See <a href="http://www.last.fm/api/authentication">http://www.last.fm/api/authentication</a> for
* authentication methods.
*
* @author Janni Kovacs
* @see Session
*/
public class Authenticator {
private Authenticator() {
}
private static boolean sessionSuccessful;
/**
* Create a web service session for a user. Used for authenticating a user when the password can be inputted by the user.
*
* @param username last.fm username
* @param password last.fm password in cleartext or 32-char md5 string
* @param apiKey The API key
* @param secret Your last.fm API secret
* @return a Session instance
* @see Session
*/
public static Session getMobileSession(String username, String password, String apiKey, String secret) {
if (!isMD5(password))
password = md5(password);
String authToken = md5(username + password);
Map<String, String> params = map("api_key", apiKey, "username", username, "authToken", authToken);
String sig = createSignature("auth.getMobileSession", params, secret);
Result result = Caller.getInstance()
.call("auth.getMobileSession", apiKey, "username", username, "authToken", authToken, "api_sig", sig);
sessionSuccessful = result.isSuccessful();
DomElement element = result.getContentElement();
return Session.sessionFromElement(element, apiKey, secret);
}
/**
* Whether the session was successful
* @return Flag
*/
public static boolean isSuccessful() {
return sessionSuccessful;
}
/**
* Fetch an unathorized request token for an API account.
*
* @param apiKey A last.fm API key.
* @return a token
*/
public static String getToken(String apiKey) {
Result result = Caller.getInstance().call("auth.getToken", apiKey);
return result.getContentElement().getText();
}
/**
* Fetch a session key for a user.
*
* @param token A token returned by {@link #getToken(String)}
* @param apiKey A last.fm API key
* @param secret Your last.fm API secret
* @return a Session instance
* @see Session
*/
public static Session getSession(String token, String apiKey, String secret) {
String m = "auth.getSession";
Map<String, String> params = new HashMap<String, String>();
params.put("api_key", apiKey);
params.put("token", token);
params.put("api_sig", createSignature(m, params, secret));
Result result = Caller.getInstance().call(m, apiKey, params);
return Session.sessionFromElement(result.getContentElement(), apiKey, secret);
}
static String createSignature(String method, Map<String, String> params, String secret) {
params = new TreeMap<String, String>(params);
params.put("method", method);
StringBuilder b = new StringBuilder(100);
for (Entry<String, String> entry : params.entrySet()) {
b.append(entry.getKey());
b.append(entry.getValue());
}
b.append(secret);
return md5(b.toString());
}
}
| 36.335938 | 122 | 0.733821 |
6714cd525744edab39571cd1454132bd37cd781b | 336 | package com.dimitrov.github.githubclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GithubClientApplication {
public static void main(String[] args) {
SpringApplication.run(GithubClientApplication.class, args);
}
}
| 25.846154 | 68 | 0.833333 |
c5ee91c54b5a2c13c97254716c59e9bcbd150bcb | 2,289 | package com.outlook.octavio.armenta.viewmodels;
import com.google.inject.Inject;
import com.outlook.octavio.armenta.services.contracts.IAuthService;
import de.saxsys.mvvmfx.ViewModel;
import de.saxsys.mvvmfx.utils.commands.Action;
import de.saxsys.mvvmfx.utils.commands.Command;
import de.saxsys.mvvmfx.utils.commands.DelegateCommand;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class SignUpViewModel implements ViewModel {
private final IAuthService authService;
private StringProperty username = new SimpleStringProperty();
private StringProperty email = new SimpleStringProperty();
private StringProperty password = new SimpleStringProperty();
private StringProperty passwordConfirmation = new SimpleStringProperty();
private BooleanProperty terms = new SimpleBooleanProperty();
private Command signUpCommand;
@Inject
public SignUpViewModel(IAuthService authService) {
this.authService = authService;
signUpCommand = new DelegateCommand(() -> new Action() {
@Override
protected void action() throws Exception {
doSignUp();
}
});
}
private void doSignUp() {
this.authService.signUp(username.get(),email.get(), password.get());
}
public String getUsername() {
return username.get();
}
public StringProperty usernameProperty() {
return username;
}
public String getEmail() {
return email.get();
}
public StringProperty emailProperty() {
return email;
}
public String getPassword() {
return password.get();
}
public StringProperty passwordProperty() {
return password;
}
public String getPasswordConfirmation() {
return passwordConfirmation.get();
}
public StringProperty passwordConfirmationProperty() {
return passwordConfirmation;
}
public boolean isTerms() {
return terms.get();
}
public BooleanProperty termsProperty() {
return terms;
}
public Command getSignUpCommand() {
return signUpCommand;
}
}
| 26.011364 | 77 | 0.693316 |
ee52a2fd9d217d48418f48af684da1047d802ed0 | 2,421 | package org.endeavourhealth.core.database.dal.publisherStaging.models;
import org.endeavourhealth.core.database.dal.publisherTransform.models.ResourceFieldMappingAudit;
import java.util.Date;
import java.util.Objects;
public class StagingProcedureCdsCount {
private String exchangeId;
private Date dtReceived;
private int recordChecksum;
private String susRecordType;
private String cdsUniqueIdentifier;
private int procedureCount;
private ResourceFieldMappingAudit audit = null;
@Override
public int hashCode() {
//only calculate the hash from non-primary key fields
return Objects.hash(procedureCount);
}
@Override
public String toString() {
return "CDS Count: ["
+ "exchangeId=" + exchangeId + ", "
+ "dtReceived=" + dtReceived + ", "
+ "recordChecksum=" + recordChecksum + ", "
+ "susRecordType=" + susRecordType + ", "
+ "cdsUniqueIdentifier=" + cdsUniqueIdentifier + ", "
+ "procedureCount=" + procedureCount + ", "
+ "audit=" + audit + "]";
}
public String getExchangeId() {
return exchangeId;
}
public void setExchangeId(String exchangeId) {
this.exchangeId = exchangeId;
}
public Date getDtReceived() {
return dtReceived;
}
public void setDtReceived(Date dtReceived) {
this.dtReceived = dtReceived;
}
public int getRecordChecksum() {
return recordChecksum;
}
public void setRecordChecksum(int recordChecksum) {
this.recordChecksum = recordChecksum;
}
public String getSusRecordType() {
return susRecordType;
}
public void setSusRecordType(String susRecordType) {
this.susRecordType = susRecordType;
}
public String getCdsUniqueIdentifier() {
return cdsUniqueIdentifier;
}
public void setCdsUniqueIdentifier(String cdsUniqueIdentifier) {
this.cdsUniqueIdentifier = cdsUniqueIdentifier;
}
public int getProcedureCount() {
return procedureCount;
}
public void setProcedureCount(int procedureCount) {
this.procedureCount = procedureCount;
}
public ResourceFieldMappingAudit getAudit() {
return audit;
}
public void setAudit(ResourceFieldMappingAudit audit) {
this.audit = audit;
}
}
| 26.032258 | 97 | 0.64684 |
7017d660ce79c27d45a2bde09977ff229a55fec4 | 3,598 | package cn.wowspeeder.encryption.impl;
import cn.wowspeeder.encryption.CryptSteamBase;
import org.bouncycastle.crypto.StreamCipher;
import org.bouncycastle.crypto.engines.ChaCha7539Engine;
//import org.bouncycastle.crypto.modes.ChaCha20Poly1305;
import org.bouncycastle.crypto.engines.ChaChaEngine;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.util.HashMap;
import java.util.Map;
import org.bouncycastle.util.Pack;
public class Chacha20Crypt extends CryptSteamBase {
public final static String CIPHER_CHACHA20 = "chacha20";
public final static String CIPHER_CHACHA20_IETF = "chacha20-ietf";
public final static String CIPHER_CHACHA20_IETF_POLY1305 = "chacha20-ietf-poly1305";
public static Map<String, String> getCiphers() {
Map<String, String> ciphers = new HashMap<>();
// ciphers.put(CIPHER_CHACHA20, Chacha20Crypt.class.getName());
// ciphers.put(CIPHER_CHACHA20_IETF, Chacha20Crypt.class.getName());
// ciphers.put(CIPHER_CHACHA20_IETF_POLY1305, Chacha20Crypt.class.getName());
return ciphers;
}
public Chacha20Crypt(String name, String password) {
super(name, password);
}
@Override
protected StreamCipher getCipher(boolean isEncrypted) throws InvalidAlgorithmParameterException {
if (_name.equals(CIPHER_CHACHA20)) {
return new ChaChaEngine();
}
else if (_name.equals(CIPHER_CHACHA20_IETF)) {
return new ChaCha7539Engine();
}
else if (_name.equals(CIPHER_CHACHA20_IETF_POLY1305)) {
System.out.println(_name);
ChaCha20Poly1305 engine = new ChaCha20Poly1305(new MyChaCha7539Engine());
// final KeyParameter myKey = new KeyParameter(Hex.decode(pTestCase.theKey));
// final byte[] myIV = Hex.decode(pTestCase.theIV);
// final ParametersWithIV myIVParms = new ParametersWithIV(myKey, myIV);
// AEADParameters myAEADParms = new AEADParameters(myKey, 0, myIV, myAAD);
//
return engine;
}
return null;
}
@Override
protected SecretKey getKey() {
return new SecretKeySpec(_ssKey.getEncoded(), "AES");
}
@Override
protected void _encrypt(byte[] data, ByteArrayOutputStream stream) {
int noBytesProcessed;
byte[] buffer = new byte[data.length];
noBytesProcessed = encCipher.processBytes(data, 0, data.length, buffer, 0);
stream.write(buffer, 0, noBytesProcessed);
}
@Override
protected void _decrypt(byte[] data, ByteArrayOutputStream stream) {
int BytesProcessedNum;
byte[] buffer = new byte[data.length];
BytesProcessedNum = decCipher.processBytes(data, 0, data.length, buffer, 0);
stream.write(buffer, 0, BytesProcessedNum);
}
@Override
public int getKeyLength() {
if (_name.equals(CIPHER_CHACHA20) || _name.equals(CIPHER_CHACHA20_IETF) || _name.equals(CIPHER_CHACHA20_IETF_POLY1305)) {
return 32;
}
return 0;
}
@Override
public int getIVLength() {
if (_name.equals(CIPHER_CHACHA20)) {
return 8;
}
else if (_name.equals(CIPHER_CHACHA20_IETF)) {
return 12;
}
else if (_name.equals(CIPHER_CHACHA20_IETF_POLY1305)) {
return 32;
}
return 0;
}
}
| 34.932039 | 129 | 0.682324 |
8e982eefde935d3b62411e7e29202fa13d1489cc | 19,135 | package wwwc.nees.joint.module.kao.retrieve;
import info.aduna.iteration.Iterations;
import wwwc.nees.joint.model.OWLUris;
import wwwc.nees.joint.model.RDFUris;
import wwwc.nees.joint.model.SWRLUris;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openrdf.model.Literal;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.query.Binding;
import org.openrdf.query.BindingSet;
import org.openrdf.query.GraphQuery;
import org.openrdf.query.GraphQueryResult;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.TupleQueryResultHandlerException;
import org.openrdf.query.Update;
import org.openrdf.query.UpdateExecutionException;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFHandlerException;
import wwwc.nees.joint.module.kao.DatatypeManager;
/**
* Class which implements QueryRunner Interface for performing SPARQL queries in
* the repository.
*
* @author Olavo Holanda
* @version 1.0 - 15/01/2012
*/
public class SPARQLQueryRunnerImpl implements QueryRunner {
// VARIABLES
// -------------------------------------------------------------------------
private final DatatypeManager datatypeManager;
// Variable to manager retrieve operations
private final RetrieveOperations retrieveOp;
private static final String CALLRET = "callret-";
// Default namespaces to use in the SPARQL queries
public static final String DEFAULT_PREFIXES = "PREFIX rdf:<" + RDFUris.RDF
+ ">\n PREFIX owl:<" + OWLUris.OWL
+ ">\n PREFIX rdfs:<" + RDFUris.RDFS
+ ">\n PREFIX xsd:<" + RDFUris.XSD
+ ">\n PREFIX swrl:<" + SWRLUris.SWRL + ">\n";
// CONSTRUCTOR
// -------------------------------------------------------------------------
/**
* Simple constructor that receives an object connection of the repository.
*
*/
public SPARQLQueryRunnerImpl() {
this.datatypeManager = DatatypeManager.getInstance();
this.retrieveOp = new RetrieveOperations();
}
// METHODS
// -------------------------------------------------------------------------
/**
* Performs SPARQL queries in the repository, returning a single result.
*
* @param connection receives an object of connection with the repository
* @param query the <code>String</code> with the query to be performed.
* @param contexts <code>URI</code> represent the graphs in which the query
* will be performed.
*
* @return object <code>Object</code> result.
*/
@Override
public Object executeQueryAsSingleResult(RepositoryConnection connection, String query, URI... contexts)
throws Exception {
// Creates the query based on the parameter
TupleQuery tupleQuery = connection.prepareTupleQuery(QueryLanguage.SPARQL, query);
// Performs the query
TupleQueryResult result = tupleQuery.evaluate();
if (!result.hasNext()) {
return null;
}
if (result.getBindingNames().size() > 1) {
List<String> names = result.getBindingNames();
List<String> sortedNames = new ArrayList<>();
Map<Integer, String> positions = new HashMap<>();
String[] realPositions = new String[result.getBindingNames().size()];
for (String string : names) {
Integer index = query.indexOf("?" + string);
if (index == -1) {
realPositions[Integer.getInteger(string.replace(CALLRET, ""))] = string;
} else {
positions.put(index, string);
}
}
List<Integer> listaKeys = new ArrayList<>(positions.keySet());
Collections.sort(listaKeys);
for (Integer integer : listaKeys) {
String value = positions.get(integer);
sortedNames.add(value);
}
for (int i = 0; i < realPositions.length; i++) {
if (realPositions[i] != null) {
sortedNames.add(i, realPositions[i]);
}
}
BindingSet binSet = result.next();
Object[] retorno = new Object[binSet.size()];
int counter = 0;
for (String bName : sortedNames) {
Binding binding = binSet.getBinding(bName);
if (binding == null) {
retorno[counter] = null;
counter++;
continue;
}
Value re = binSet.getBinding(bName).getValue();
if (re instanceof Literal) {
retorno[counter] = datatypeManager.convertLiteralToDataype((Literal) re);
} else {
String className = this.retrieveOp.getClassFromBase(connection, re.stringValue(), contexts);
retorno[counter] = this.retrieveOp.convertOriginalForImpl(connection, re.stringValue(), Class.forName(className), contexts);
}
counter++;
}
return retorno;
} else {
Object returnObject;
BindingSet binSet = result.next();
Value re = binSet.iterator().next().getValue();
if (re == null) {
return null;
} else if (re instanceof Literal) {
returnObject = datatypeManager.convertLiteralToDataype((Literal) re);
} else {
String className = this.retrieveOp.getClassFromBase(connection, re.stringValue(), contexts);
if (className.equals("java.lang.Object")) {
returnObject = re.stringValue();
} else {
returnObject = this.retrieveOp.convertOriginalForImpl(connection, re.stringValue(), Class.forName(className), contexts);
}
}
// Gets the first and only index
return returnObject;
}
}
/**
* Performs SPARQL queries in the repository, returning a java.util.List of
* results.
*
* @param connection receives an object of connection with the repository
* @param query the <code>String</code> with the query to be performed.
* @param contexts <code>URI</code> represent the graphs in which the query
* will be performed.
* @return <code>List</code> a java.util.List with the results.
*/
@Override
public List<Object> executeQueryAsList(RepositoryConnection connection, String query, URI... contexts)
throws Exception {
// Creates a java.util.List
List<Object> resultList = new ArrayList<>();
// Creates the query based on the parameter
TupleQuery tupleQuery = connection.prepareTupleQuery(QueryLanguage.SPARQL, query);
// Performs the query
TupleQueryResult result = tupleQuery.evaluate();
String className;
if (result.getBindingNames().size() > 1) {
List<String> names = result.getBindingNames();
List<String> sortedNames = new ArrayList<>();
Map<Integer, String> positions = new HashMap<>();
String[] realPositions = new String[result.getBindingNames().size()];
for (String string : names) {
Integer index = query.indexOf("?" + string);
if (index == -1) {
realPositions[Integer.parseInt(string.replace(CALLRET, ""))] = string;
} else {
positions.put(index, string);
}
}
List<Integer> listaKeys = new ArrayList<>(positions.keySet());
Collections.sort(listaKeys);
for (Integer integer : listaKeys) {
String value = positions.get(integer);
sortedNames.add(value);
}
for (int i = 0; i < realPositions.length; i++) {
if (realPositions[i] != null) {
sortedNames.add(i, realPositions[i]);
}
}
while (result.hasNext()) {
BindingSet binSet = result.next();
Object[] retorno = new Object[binSet.size()];
int counter = 0;
for (String bName : sortedNames) {
Binding binding = binSet.getBinding(bName);
if (binding == null) {
retorno[counter] = null;
counter++;
continue;
}
Value re = binSet.getBinding(bName).getValue();
if (re instanceof Literal) {
retorno[counter] = datatypeManager.convertLiteralToDataype((Literal) re);
} else {
className = this.retrieveOp.getClassFromBase(connection, re.stringValue(), contexts);
retorno[counter] = this.retrieveOp.convertOriginalForImpl(connection, re.stringValue(), Class.forName(className), contexts);
}
counter++;
}
resultList.add(retorno);
}
} else {
//checks if there is any result
if (result.hasNext()) {
//gets the first result for type checking
BindingSet binSet = result.next();
//gets the value of the first row
Value re = binSet.iterator().next().getValue();
//if the element is a Literal, else it is an instance
if (re instanceof Literal) {
//creates the collection of literal
List<Literal> literals = new ArrayList<>();
//adds the first element
literals.add((Literal) re);
while (result.hasNext()) {
//gets the element in the row and casts its value to Literal
BindingSet binding = result.next();
Literal lit = (Literal) binding.iterator().next().getValue();
//adds in the collection
literals.add(lit);
}
result.close();
//returns the collection already parsed
return this.datatypeManager.convertCollectionOfLiteralToDataypes(literals);
} else {
//checks which class type the element belongs
className = this.retrieveOp.getClassFromBase(connection, re.stringValue(), contexts);
//creates the collection of objects
List<String> instancesURI = new ArrayList<>();
//adds the first element
instancesURI.add(re.stringValue());
while (result.hasNext()) {
//gets the element in the row and casts its value to Literal
BindingSet binding = result.next();
String uri = binding.iterator().next().getValue().stringValue();
//adds in the collection
instancesURI.add(uri);
}
result.close();
return this.retrieveOp.convertCollectionOriginalForImpl(connection, instancesURI, Class.forName(className), contexts);
}
}
}
result.close();
return resultList;
}
@Override
public List<Object> executeQueryAsList2(RepositoryConnection connection, String query, URI... contexts
) throws Exception {
GraphQueryResult result;
String clause_PREFIX = "";
StringBuilder queryBuilder = new StringBuilder();
if (query.startsWith("PREFIX")) {
Pattern patter_PREFIX = Pattern.compile("(([\\s]?)(PREFIX)([\\s]+)([\\w]+)(\\:)(<([a-zA-Z]{3,})://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?>))+");
Matcher matcher_PREFIX = patter_PREFIX.matcher(query);
if (matcher_PREFIX.find()) {
clause_PREFIX = matcher_PREFIX.group();
queryBuilder.append(clause_PREFIX);
query = query.replace(clause_PREFIX, "");
}
}
Pattern pattern_SELECT = Pattern.compile("(\\s+\\?[^\\s]+)");
Matcher matcher_SELECT = pattern_SELECT.matcher(query);
if (matcher_SELECT.find()) {
String group = matcher_SELECT.group();
queryBuilder.append(" CONSTRUCT {").append(group).append(" ?p ?o} WHERE{")
.append(group).append(" ?p ?o{")
.append(query).append("}}");
}
// Creates the query based on the parameter
GraphQuery graphQuery = connection.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString());
// Performs the query
result = graphQuery.evaluate();
List<Statement> resultado = Iterations.asList(result);
result.close();
String className = "";
for (Statement st : resultado) {
if (st.getPredicate().toString().equals(RDF.TYPE.toString())) {
className = retrieveOp.getClassFromBase(st.getObject().stringValue());
result.close();
break;
}
}
return this.retrieveOp.convertCollectionOriginalForImpl3(connection, resultado, Class.forName(className), contexts);
}
@Override
public String executeTupleQueryAsJSON(RepositoryConnection connection, String query
) throws RepositoryException, MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException {
// ByteArrayOutputStream resultsJSON = new ByteArrayOutputStream();
// SPARQLResultsJSONWriter jsonWriter = new SPARQLResultsJSONWriter(resultsJSON);
TupleQueryToJSONImpl jsonWriter = new TupleQueryToJSONImpl();
// Creates the query based on the parameter
TupleQuery tupleQuery = connection.prepareTupleQuery(QueryLanguage.SPARQL, query);
// Performs the query
tupleQuery.evaluate(jsonWriter);
return jsonWriter.toJSONString();
}
/**
* Performs query in the repository, returning the results in an adapted
* format from JSON-LD specification
*
* @param connection receives an object of connection with the repository
* @param query the String with the query to be performed.
* @param features
* @param graphAsJSONArray defines if the <b><code>@graph</code> key</b> is
* a JSON Array. If value is true, then is an array, else, is a JSON Object
* where the <b><code>@id</code> key</b> are the keys of the objects. <b>By
* default it's <code>true</code></b>.
* @return a JSON as String
*/
@Override
public JSONObject executeGraphQueryAsJSONLD(RepositoryConnection connection, String query, Feature... features) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFHandlerException, JSONException {
GraphQueryToJSONLD jsonldWriter = new GraphQueryToJSONLD(connection, features);
// Creates the query based on the parameter
GraphQuery graphQuery = connection.prepareGraphQuery(QueryLanguage.SPARQL, query);
// Performs the query
graphQuery.evaluate(jsonldWriter);
return jsonldWriter.getResults();
}
/**
* Performs SPARQL queries in the repository, returning a java.util.Iterator
* with the results.
*
* @param connection receives an object of connection with the repository
* @param query the <code>String</code> with the query to be performed.
* @param contexts <code>URI</code> represent the graphs in which the query
* will be performed.
* @return <code>Iterator</code> a java.util.List with the results.
*/
@Override
public Iterator<Object> executeQueryAsIterator(RepositoryConnection connection, String query, URI... contexts
) throws Exception {
// Changes the result to a java.util.List
//Gets the iterator of the list
return this.executeQueryAsList(connection, query, contexts).iterator();
}
/**
* Performs SPARQL queries in the repository, returning a boolean with the
* result.
*
* @param connection receives an object of connection with the repository
* @param query the <code>String</code> with the query to be performed.
*
* @return <code>boolean<Object></code> true or false.
* @throws org.openrdf.repository.RepositoryException if occur repository
* connection error
* @throws org.openrdf.query.MalformedQueryException if occur error in the
* query
* @throws org.openrdf.query.QueryEvaluationException if occur error in the
* query
*/
@Override
public boolean executeBooleanQuery(RepositoryConnection connection, String query)
throws RepositoryException, MalformedQueryException, QueryEvaluationException {
// Creates and performs the query based on the parameter
return connection.prepareBooleanQuery(QueryLanguage.SPARQL, query).evaluate();
}
/**
* Performs SPARQL update queries in the repository, returning a boolean
* true if the query was performed with successful or false otherwise.
*
* @param connection receives an object of connection with the repository
* @param query the <code>String</code> with the query to be performed.
* @throws org.openrdf.repository.RepositoryException
* @throws org.openrdf.query.MalformedQueryException
* @throws org.openrdf.query.UpdateExecutionException
*/
@Override
public void executeUpdateQuery(RepositoryConnection connection, String query)
throws RepositoryException, MalformedQueryException, UpdateExecutionException {
// Creates the update query based on the parameter
Update update = connection.prepareUpdate(QueryLanguage.SPARQL, query);
// Performs the query
update.execute();
}
}
| 41.870897 | 232 | 0.584845 |
ab73b09b34f388bf38d31c78795581c9deab45c3 | 1,712 | package com.tramchester.modules;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.governator.guice.lazy.LazySingleton;
import com.tramchester.config.TramchesterConfig;
import com.tramchester.domain.time.ProvidesLocalNow;
import com.tramchester.domain.time.ProvidesNow;
import com.tramchester.graph.caches.*;
import com.tramchester.metrics.CacheMetrics;
public class MappersAndConfigurationModule extends AbstractModule {
private final TramchesterConfig config;
private final CacheMetrics.RegistersCacheMetrics registersCacheMetrics;
public MappersAndConfigurationModule(TramchesterConfig config, CacheMetrics.RegistersCacheMetrics registersCacheMetrics) {
this.config = config;
this.registersCacheMetrics = registersCacheMetrics;
}
@Override
protected void configure() {
bind(TramchesterConfig.class).toInstance(config);
bind(CacheMetrics.RegistersCacheMetrics.class).toInstance(registersCacheMetrics);
bind(ProvidesNow.class).to(ProvidesLocalNow.class);
bind(NodeContentsRepository.class).to(CachedNodeOperations.class);
}
@SuppressWarnings("unused")
@LazySingleton
@Provides
CsvMapper providesCsvMapper() {
return CsvMapper.builder().addModule(new AfterburnerModule()).build();
}
@SuppressWarnings("unused")
@LazySingleton
@Provides
ObjectMapper providesObjectMapper() {
return new ObjectMapper();
}
}
| 35.666667 | 127 | 0.755841 |
069dad3b2a75e682b827400207f361ad82aed590 | 375 | package org.sunbird.cb.hubservices.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.sunbird.hubservices.dao.IGraphDao;
import org.sunbird.hubservices.daoimpl.GraphDao;
@Configuration
public class GraphConfg {
@Bean
public IGraphDao userGraphDao() {
return new GraphDao("userV2");
}
}
| 23.4375 | 60 | 0.810667 |
fccb043b2938e17dd84cb627d67c7f5c2bd14e4d | 1,487 | package com.example.hzday6_29_robort;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
/**
* Created by Wakesy on 2016/6/29.
*/
public class MyAsynctask extends AsyncTask<String,Void,List<Bean>> {
private List<Bean>datalist;
private ListView listView;
private MainActivity.MyAdapter adapter;
//将LIstView ,datalist和adapter传过来
public MyAsynctask(List<Bean> datalist,ListView listView,MainActivity.MyAdapter adapter) {
this.datalist = datalist;
this.listView=listView;
this.adapter=adapter;
}
@Override
protected List<Bean> doInBackground(String... params) {
String jsonString=HttpJson.getJsonContent(params[0]);//通过url下载Json 数据
try {
JSONObject jsonObject=new JSONObject(jsonString);
String text=jsonObject.getString("text");
Bean bean1=new Bean(text,0);//得到机器回复的信息,加入集合中,并加上标识符0,在左边显示
Log.i("jsonString",text);
datalist.add(bean1);
} catch (JSONException e) {
e.printStackTrace();
}
return datalist;
}
@Override
protected void onPostExecute(List<Bean> datalist) {
super.onPostExecute(datalist);
adapter.notifyDataSetChanged();//更新适配器
listView.setAdapter(adapter);//重新设置设配器
listView.setSelection(datalist.size()-1);//将listView调到最后一行的位置
}
}
| 27.036364 | 94 | 0.675185 |
e7581ac1b09c67797e948ab7ef0bee4f6cee78a1 | 467 | package dragonball.model.exceptions;
public class MapIndexOutOfBoundsException extends IndexOutOfBoundsException{
private int row;
private int column;
public MapIndexOutOfBoundsException(int row, int column){
super("you are trying to ender an invalid of potiion ("+row+","+column+").");
this.column=column;
this.row=row;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}
| 17.296296 | 80 | 0.668094 |
1fbf527f99bb4e1d425a2a1a013e478394b0a44b | 1,353 | package unit.identify;
import identify.JSIdentify;
import unit.TestUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.File;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class JSIdentifyTest {
private static final String JSON_FILE = "package.json";
private static JSIdentify identifyObject;
@BeforeAll
static void init(){
TestUtils.setProjectAbsPath(JSON_FILE);
identifyObject = new JSIdentify(TestUtils.getProjectAbsPath());
}
@Test
void getJson() {
assertEquals(new File(TestUtils.getProjectAbsPath() + File.separator + JSON_FILE), identifyObject.getKeyFile(), "Get package.json");
}
@Test
void getMocha() {
assertEquals("mocha", identifyObject.getMochaArtefactID(), "Find name: mocha");
}
@Test
void checkJson() {
assertEquals(true, identifyObject.checkKeyFile(), "CheckJson returns true");
}
@Test
void checkMocha() {
assertEquals(true, identifyObject.checkMocha(), "CheckMocha returns true");
}
@Test
void checkJasmine() {
assertEquals(false, identifyObject.checkJasmine(), "CheckJasmine returns true");
}
@Test
void checkTape() {
assertEquals(false, identifyObject.checkTape(), "CheckTape returns true");
}
}
| 24.6 | 140 | 0.685144 |
54c16961b6bd9648dc47e33ad2e8b2f24f631697 | 4,843 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.component.external.model;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.NamespaceId;
import org.gradle.api.internal.attributes.ImmutableAttributesFactory;
import org.gradle.internal.component.external.descriptor.Artifact;
import org.gradle.internal.component.external.descriptor.Configuration;
import org.gradle.internal.component.model.Exclude;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class DefaultMutableIvyModuleResolveMetadata extends AbstractMutableModuleComponentResolveMetadata implements MutableIvyModuleResolveMetadata {
private final ImmutableList<Artifact> artifactDefinitions;
private final ImmutableMap<String, Configuration> configurationDefinitions;
private final ImmutableList<IvyDependencyDescriptor> dependencies;
private ImmutableList<Exclude> excludes;
private ImmutableMap<NamespaceId, String> extraAttributes;
private String branch;
public DefaultMutableIvyModuleResolveMetadata(ImmutableAttributesFactory attributesFactory,
ModuleVersionIdentifier id,
ModuleComponentIdentifier componentIdentifier,
List<IvyDependencyDescriptor> dependencies,
Collection<Configuration> configurationDefinitions,
Collection<? extends Artifact> artifactDefinitions,
Collection<? extends Exclude> excludes) {
super(attributesFactory, id, componentIdentifier);
this.configurationDefinitions = toMap(configurationDefinitions);
this.artifactDefinitions = ImmutableList.copyOf(artifactDefinitions);
this.dependencies = ImmutableList.copyOf(dependencies);
this.excludes = ImmutableList.of();
this.extraAttributes = ImmutableMap.of();
this.excludes = ImmutableList.copyOf(excludes);
}
DefaultMutableIvyModuleResolveMetadata(IvyModuleResolveMetadata metadata) {
super(metadata);
this.configurationDefinitions = metadata.getConfigurationDefinitions();
this.artifactDefinitions = metadata.getArtifactDefinitions();
this.dependencies = metadata.getDependencies();
this.excludes = metadata.getExcludes();
this.branch = metadata.getBranch();
this.extraAttributes = metadata.getExtraAttributes();
}
private static ImmutableMap<String, Configuration> toMap(Collection<Configuration> configurations) {
ImmutableMap.Builder<String, Configuration> builder = ImmutableMap.builder();
for (Configuration configuration : configurations) {
builder.put(configuration.getName(), configuration);
}
return builder.build();
}
@Override
public ImmutableMap<String, Configuration> getConfigurationDefinitions() {
return configurationDefinitions;
}
@Override
public ImmutableList<Artifact> getArtifactDefinitions() {
return artifactDefinitions;
}
@Override
public ImmutableList<Exclude> getExcludes() {
return excludes;
}
@Override
public ImmutableMap<NamespaceId, String> getExtraAttributes() {
return extraAttributes;
}
@Override
public void setExtraAttributes(Map<NamespaceId, String> extraAttributes) {
this.extraAttributes = ImmutableMap.copyOf(extraAttributes);
}
@Nullable
@Override
public String getBranch() {
return branch;
}
@Override
public void setBranch(String branch) {
this.branch = branch;
}
@Override
public IvyModuleResolveMetadata asImmutable() {
return new DefaultIvyModuleResolveMetadata(this);
}
@Override
public ImmutableList<IvyDependencyDescriptor> getDependencies() {
return dependencies;
}
}
| 39.373984 | 150 | 0.709891 |
884df3004b4ee0a48116a7a708f19ebba665c6e5 | 3,285 | package de.kjosu.neatdebug.components;
import javafx.application.Platform;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import java.time.Duration;
import java.time.Instant;
public abstract class RenderCanvas extends ResizableCanvas implements Runnable {
private int maxTicksPerSecond = 10;
private int maxFramesPerSecond = 30;
private int ticksPerSecond = 0;
private int framesPerSecond = 0;
private Thread thread;
private boolean running;
public RenderCanvas() {
setOnMousePressed(event -> onMouseDown(event));
setOnMouseReleased(event -> onMouseUp(event));
setOnMouseMoved(event -> onMouseMoved(event));
setOnMouseDragged(event -> onMouseDragged(event));
setOnKeyPressed(event -> onKeyDown(event));
setOnKeyReleased(event -> onKeyUp(event));
}
@Override
public void run() {
Instant lastRefresh = Instant.now();
Instant lastTick = lastRefresh;
int tick = 0;
int frame = 0;
while (running) {
Instant now = Instant.now();
double delta = Duration.between(lastRefresh, now).toMillis();
if (delta >= 1000D / maxTicksPerSecond * tick) {
double updateDelta = Duration.between(lastTick, now).toMillis() / 1000D;
onUpdate(updateDelta);
lastTick = now;
tick++;
}
if (delta >= 1000D / maxFramesPerSecond * frame) {
render();
frame++;
}
if (delta >= 1000D) {
ticksPerSecond = tick;
framesPerSecond = frame;
tick = 0;
frame = 0;
lastRefresh = now;
}
}
}
private void render() {
GraphicsContext g = getGraphicsContext2D();
onRender(g);
}
public abstract void onUpdate(double delta);
public abstract void onRender(GraphicsContext g);
protected abstract void onMouseDown(MouseEvent e);
protected abstract void onMouseUp(MouseEvent e);
protected abstract void onMouseMoved(MouseEvent e);
protected abstract void onMouseDragged(MouseEvent e);
protected abstract void onKeyDown(KeyEvent e);
protected abstract void onKeyUp(KeyEvent e);
public void start() {
if (running) {
throw new IllegalStateException("Already rendering");
}
thread = new Thread(this);
running = true;
thread.start();
}
public void stop() {
running = false;
}
public int getMaxTicksPerSecond() {
return maxTicksPerSecond;
}
public void setMaxTicksPerSecond(int maxTicksPerSecond) {
this.maxTicksPerSecond = maxTicksPerSecond;
}
public int getMaxFramesPerSecond() {
return maxFramesPerSecond;
}
public void setMaxFramesPerSecond(int maxFramesPerSecond) {
this.maxFramesPerSecond = maxFramesPerSecond;
}
public int getTicksPerSecond() {
return ticksPerSecond;
}
public int getFramesPerSecond() {
return framesPerSecond;
}
public boolean isRunning() {
return running;
}
}
| 25.076336 | 88 | 0.616134 |
5fa92a1762afc7b190d0efb8451c856d8feaa407 | 204 | package org.cmdb.entity;
/**
* Created with IntelliJ IDEA.
* User: mq
* Date: 2017/4/19
* Time: 14:28
* To change this template use File | Settings | File Templates.
*/
public interface Idable {
}
| 17 | 64 | 0.671569 |
02221519c9e9d70cb47da63bab616f444dc6f77c | 7,102 | /**
* @filename:DeviceStatusController 2019-05-13
* @project boots V1.0
* Copyright(c) 2019 BAOYUE Co. Ltd.
* All right reserved.
*/
package com.bych.control;
import club.map.core.web.util.Result;
import com.bych.service.ImportData;
import com.bych.t_s_device_status.manager.VSDeviceStatusManager;
import com.bych.t_s_device_status.model.VSPressureStatusData;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//import com.bych.t_s_device_status.manager.TSDeviceStatusManager;
/**
*
* @Description: 设备状态接口层
* @Author: lxl
* @CreateDate: 2019-05-13
* @Version: V1.0
*
*/
@Api(description = "压力设备状态",value="压力设备状态" )
@CrossOrigin
@RestController
@RequestMapping("/devicestatus")
public class DeviceStatusController {
Logger logger = LoggerFactory.getLogger(this.getClass());
public ImportData importData;
public DeviceStatusController(
ImportData importData) {
this.importData=importData;
}
@Autowired
public VSDeviceStatusManager vsDeviceStatusLastManager;
/**
* @explain 查询设备状态对象 <swagger GET请求>
* @time 2019-05-13
*/
@ApiImplicitParams({
@ApiImplicitParam(name = "url", value = "url", dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "type", value = "type", dataType = "Integer", paramType = "query")
})
@GetMapping("/import")
@ApiOperation(value = "导入", notes = "作者:lxl")
public Result importss( @RequestParam(value = "url") String url,
@RequestParam(value = "type") Integer type){
importData.importFromExcel(url,type);
return Result.ok();
}
/**
* @explain 删除设备状态对象
* @param ids
* @return int
* @time 2019-05-13
*/
@ApiOperation("设备状态管理 - 删除设备状态信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "ids", value = "ids", dataType = "string", paramType = "query")
})
@PostMapping("/remove")
public Result remove(
@RequestParam(value = "ids") String ids
) {
// tsDeviceStatusManager.removeByIds(ids);
return Result.ok();
}
// @ApiOperation("查询某设备历史信息")
// @ApiImplicitParams({
// @ApiImplicitParam(name = "pageNo", value = "当前页", dataType = "int", paramType = "query"),
// @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query"),
// @ApiImplicitParam(name = "deviceName", value = "设备名称", dataType = "string", paramType = "query"),
// @ApiImplicitParam(name = "regionCode", value = "区域编号", dataType = "string", paramType = "query"),
//// @ApiImplicitParam(name = "voltageSta", value = "电压状态", dataType = "int", paramType = "query"),
//// @ApiImplicitParam(name = "pressSta", value = "压力状态", dataType = "int", paramType = "query"),
//// @ApiImplicitParam(name = "heartSta", value = "心跳状态", dataType = "int", paramType = "query"),
//// @ApiImplicitParam(name = "batterySta", value = "电池状态", dataType = "int", paramType = "query"),
// @ApiImplicitParam(name = "deviceSta", value = "设备状态", dataType = "int", paramType = "query"),
// @ApiImplicitParam(name = "startTime", value = "开始时间(采集时间)", dataType = "string", paramType = "query"),
// @ApiImplicitParam(name = "endTime", value = "结束时间(采集时间)", dataType = "string", paramType = "query")
// })
// @PostMapping("/flipList")
// public Result flipList(
// @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
// @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
// @RequestParam(value = "deviceName", required = false, defaultValue = "") Integer equId,
// @RequestParam(value = "regionCode", required = false, defaultValue = "") String equStaBattery,
// @RequestParam(value = "equStatus", required = false, defaultValue = "") String equStatus,
// @RequestParam(value = "equId", required = false, defaultValue = "") Integer equId,
// @RequestParam(value = "equStaBattery", required = false, defaultValue = "") String equStaBattery,
// @RequestParam(value = "equStatus", required = false, defaultValue = "") String equStatus,
// @RequestParam(value = "equId", required = false, defaultValue = "") Integer equId,
// @RequestParam(value = "equStaBattery", required = false, defaultValue = "") String equStaBattery,
// @RequestParam(value = "equStatus", required = false, defaultValue = "") String equStatus,
// @RequestParam(value = "startTime", required = false, defaultValue = "") String startTime,
// @RequestParam(value = "endTime", required = false, defaultValue = "") String endTime
// ) {
// Page page = tsDeviceStatusManager.search(equId,equStaBattery,equStatus, pageNo, pageSize,startTime,endTime);
// return Result.ok(page);
// }
@ApiOperation("查询设备最新数据")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNo", value = "当前页", dataType = "int", paramType = "query"),
@ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query"),
@ApiImplicitParam(name = "deviceName", value = "设备名称", dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "regionCode", value = "区域编号", dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "voltageSta", value = "电压状态", dataType = "int", paramType = "query"),
@ApiImplicitParam(name = "pressSta", value = "压力状态", dataType = "int", paramType = "query"),
@ApiImplicitParam(name = "heartSta", value = "心跳状态", dataType = "int", paramType = "query"),
@ApiImplicitParam(name = "batterySta", value = "电池状态", dataType = "int", paramType = "query"),
@ApiImplicitParam(name = "deviceSta", value = "设备状态", dataType = "int", paramType = "query")
})
@PostMapping("/getLastData")
public Result getLastData(
@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize", required = false ) Integer pageSize,
@RequestParam(value = "deviceName", required = false, defaultValue = "") String deviceName,
@RequestParam(value = "regionCode", required = false, defaultValue = "") String regionCode,
@RequestParam(value = "voltageSta", required = false, defaultValue = "") Integer voltageSta,
@RequestParam(value = "pressSta", required = false, defaultValue = "") Integer pressSta,
@RequestParam(value = "heartSta", required = false, defaultValue = "") Integer heartSta,
@RequestParam(value = "batterySta", required = false, defaultValue = "") Integer batterySta,
@RequestParam(value = "deviceSta", required = false, defaultValue = "") Integer deviceSta
) {
if (pageSize != null) {
PageHelper.startPage(pageNo,pageSize);
}
List<VSPressureStatusData> docs = vsDeviceStatusLastManager.getLastData(deviceName,regionCode, voltageSta, pressSta, heartSta, batterySta, deviceSta);
PageInfo page= new PageInfo<>(docs);
return Result.ok(page);
}
} | 46.116883 | 152 | 0.692763 |
f73d3ebb16b6270fc236a40be87de01e738aef88 | 11,198 | /*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.gwtproject.cell.client;
import org.gwtproject.core.client.GWT;
import org.gwtproject.dom.client.Element;
import org.gwtproject.dom.client.EventTarget;
import org.gwtproject.dom.client.InputElement;
import org.gwtproject.dom.client.NativeEvent;
import org.gwtproject.event.dom.client.KeyCodes;
import org.gwtproject.safehtml.client.SafeHtmlTemplates;
import org.gwtproject.safehtml.shared.SafeHtml;
import org.gwtproject.safehtml.shared.SafeHtmlBuilder;
import org.gwtproject.text.shared.SafeHtmlRenderer;
import org.gwtproject.text.shared.SimpleSafeHtmlRenderer;
import java.util.Locale;
import static org.gwtproject.dom.client.BrowserEvents.*;
/**
* An editable text cell. Click to edit, escape to cancel, return to commit.
*/
public class EditTextCell extends
AbstractEditableCell<String, EditTextCell.ViewData> {
interface Template extends SafeHtmlTemplates {
@Template("<input type=\"text\" value=\"{0}\" tabindex=\"-1\"></input>")
SafeHtml input(String value);
}
/**
* The view data object used by this cell. We need to store both the text and
* the state because this cell is rendered differently in edit mode. If we did
* not store the edit state, refreshing the cell with view data would always
* put us in to edit state, rendering a text box instead of the new text
* string.
*/
static class ViewData {
private boolean isEditing;
/**
* If true, this is not the first edit.
*/
private boolean isEditingAgain;
/**
* Keep track of the original value at the start of the edit, which might be
* the edited value from the previous edit and NOT the actual value.
*/
private String original;
private String text;
/**
* Construct a new ViewData in editing mode.
*
* @param text the text to edit
*/
public ViewData(String text) {
this.original = text;
this.text = text;
this.isEditing = true;
this.isEditingAgain = false;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
ViewData vd = (ViewData) o;
return equalsOrBothNull(original, vd.original)
&& equalsOrBothNull(text, vd.text) && isEditing == vd.isEditing
&& isEditingAgain == vd.isEditingAgain;
}
public String getOriginal() {
return original;
}
public String getText() {
return text;
}
@Override
public int hashCode() {
return original.hashCode() + text.hashCode()
+ Boolean.valueOf(isEditing).hashCode() * 29
+ Boolean.valueOf(isEditingAgain).hashCode();
}
public boolean isEditing() {
return isEditing;
}
public boolean isEditingAgain() {
return isEditingAgain;
}
public void setEditing(boolean isEditing) {
boolean wasEditing = this.isEditing;
this.isEditing = isEditing;
// This is a subsequent edit, so start from where we left off.
if (!wasEditing && isEditing) {
isEditingAgain = true;
original = text;
}
}
public void setText(String text) {
this.text = text;
}
private boolean equalsOrBothNull(Object o1, Object o2) {
return (o1 == null) ? o2 == null : o1.equals(o2);
}
}
private static Template template;
private final SafeHtmlRenderer<String> renderer;
/**
* Construct a new EditTextCell that will use a
* {@link SimpleSafeHtmlRenderer}.
*/
public EditTextCell() {
this(SimpleSafeHtmlRenderer.getInstance());
}
/**
* Construct a new EditTextCell that will use a given {@link SafeHtmlRenderer}
* to render the value when not in edit mode.
*
* @param renderer a {@link SafeHtmlRenderer SafeHtmlRenderer<String>}
* instance
*/
public EditTextCell(SafeHtmlRenderer<String> renderer) {
super(CLICK, KEYUP, KEYDOWN, BLUR);
if (template == null) {
template = new EditTextCell_TemplateImpl();
}
if (renderer == null) {
throw new IllegalArgumentException("renderer == null");
}
this.renderer = renderer;
}
@Override
public boolean isEditing(Cell.Context context, Element parent, String value) {
ViewData viewData = getViewData(context.getKey());
return viewData == null ? false : viewData.isEditing();
}
@Override
public void onBrowserEvent(Cell.Context context, Element parent, String value,
NativeEvent event, ValueUpdater<String> valueUpdater) {
Object key = context.getKey();
ViewData viewData = getViewData(key);
if (viewData != null && viewData.isEditing()) {
// Handle the edit event.
editEvent(context, parent, value, viewData, event, valueUpdater);
} else {
String type = event.getType();
int keyCode = event.getKeyCode();
boolean enterPressed = KEYUP.equals(type)
&& keyCode == KeyCodes.KEY_ENTER;
if (CLICK.equals(type) || enterPressed) {
// Go into edit mode.
if (viewData == null) {
viewData = new ViewData(value);
setViewData(key, viewData);
} else {
viewData.setEditing(true);
}
edit(context, parent, value);
}
}
}
@Override
public void render(Cell.Context context, String value, SafeHtmlBuilder sb) {
// Get the view data.
Object key = context.getKey();
ViewData viewData = getViewData(key);
if (viewData != null && !viewData.isEditing() && value != null
&& value.equals(viewData.getText())) {
clearViewData(key);
viewData = null;
}
String toRender = value;
if (viewData != null) {
String text = viewData.getText();
if (viewData.isEditing()) {
/*
* Do not use the renderer in edit mode because the value of a text
* input element is always treated as text. SafeHtml isn't valid in the
* context of the value attribute.
*/
sb.append(template.input(text));
return;
} else {
// The user pressed enter, but view data still exists.
toRender = text;
}
}
if (toRender != null && toRender.trim().length() > 0) {
sb.append(renderer.render(toRender));
} else {
/*
* Render a blank space to force the rendered element to have a height.
* Otherwise it is not clickable.
*/
sb.appendHtmlConstant("\u00A0");
}
}
@Override
public boolean resetFocus(Cell.Context context, Element parent, String value) {
if (isEditing(context, parent, value)) {
getInputElement(parent).focus();
return true;
}
return false;
}
/**
* Convert the cell to edit mode.
*
* @param context the {@link Cell.Context} of the cell
* @param parent the parent element
* @param value the current value
*/
protected void edit(Cell.Context context, Element parent, String value) {
setValue(context, parent, value);
InputElement input = getInputElement(parent);
input.focus();
input.select();
}
/**
* Convert the cell to non-edit mode.
*
* @param context the context of the cell
* @param parent the parent Element
* @param value the value associated with the cell
*/
private void cancel(Cell.Context context, Element parent, String value) {
clearInput(getInputElement(parent));
setValue(context, parent, value);
}
/**
* Clear selected from the input element. Both Firefox and IE fire spurious
* onblur events after the input is removed from the DOM if selection is not
* cleared.
*
* @param input the input element
*/
private native void clearInput(Element input) /*-{
if (input.selectionEnd)
input.selectionEnd = input.selectionStart;
else if ($doc.selection)
$doc.selection.clear();
}-*/;
/**
* Commit the current value.
*
* @param context the context of the cell
* @param parent the parent Element
* @param viewData the {@link ViewData} object
* @param valueUpdater the {@link ValueUpdater}
*/
private void commit(Cell.Context context, Element parent, ViewData viewData,
ValueUpdater<String> valueUpdater) {
String value = updateViewData(parent, viewData, false);
clearInput(getInputElement(parent));
setValue(context, parent, viewData.getOriginal());
if (valueUpdater != null) {
valueUpdater.update(value);
}
}
private void editEvent(Cell.Context context, Element parent, String value,
ViewData viewData, NativeEvent event, ValueUpdater<String> valueUpdater) {
String type = event.getType();
boolean keyUp = KEYUP.equals(type);
boolean keyDown = KEYDOWN.equals(type);
if (keyUp || keyDown) {
int keyCode = event.getKeyCode();
if (keyUp && keyCode == KeyCodes.KEY_ENTER) {
// Commit the change.
commit(context, parent, viewData, valueUpdater);
} else if (keyUp && keyCode == KeyCodes.KEY_ESCAPE) {
// Cancel edit mode.
String originalText = viewData.getOriginal();
if (viewData.isEditingAgain()) {
viewData.setText(originalText);
viewData.setEditing(false);
} else {
setViewData(context.getKey(), null);
}
cancel(context, parent, value);
} else {
// Update the text in the view data on each key.
updateViewData(parent, viewData, true);
}
} else if (BLUR.equals(type)) {
// Commit the change. Ensure that we are blurring the input element and
// not the parent element itself.
EventTarget eventTarget = event.getEventTarget();
if (Element.is(eventTarget)) {
Element target = Element.as(eventTarget);
if ("input".equals(target.getTagName().toLowerCase(Locale.ROOT))) {
commit(context, parent, viewData, valueUpdater);
}
}
}
}
/**
* Get the input element in edit mode.
*/
private InputElement getInputElement(Element parent) {
return parent.getFirstChild().<InputElement> cast();
}
/**
* Update the view data based on the current value.
*
* @param parent the parent element
* @param viewData the {@link ViewData} object to update
* @param isEditing true if in edit mode
* @return the new value
*/
private String updateViewData(Element parent, ViewData viewData,
boolean isEditing) {
InputElement input = (InputElement) parent.getFirstChild();
String value = input.getValue();
viewData.setText(value);
viewData.setEditing(isEditing);
return value;
}
}
| 30.763736 | 99 | 0.649044 |
1435f23c439edbdc6d7660550d58ad710b76f998 | 477 | package com.alibaba.smart.framework.engine.retry.service.command;
import com.alibaba.smart.framework.engine.model.instance.ProcessInstance;
import com.alibaba.smart.framework.engine.retry.model.instance.RetryRecord;
/**
* @author zhenhong.tzh
* @date 2019-04-27
*/
public interface RetryService {
/**
* 保存需要重试的流程记录
* @param retryRecord
* @return
*/
boolean save(RetryRecord retryRecord);
ProcessInstance retry(RetryRecord retryRecord);
}
| 22.714286 | 75 | 0.731656 |
fa861c0259b6bf0cf023ba6fdd3cb7781393011a | 570 | package com.hubspot.smtp.client;
/**
* A base exception that incorporates a connection ID into the exception message.
*
*/
public abstract class SmtpException extends RuntimeException {
public SmtpException(String connectionId, String message) {
super(constructErrorMessage(connectionId, message));
}
private static String constructErrorMessage(String connectionId, String message) {
if (connectionId == null || connectionId.length() == 0) {
return message;
} else {
return String.format("[%s] %s", connectionId, message);
}
}
}
| 28.5 | 84 | 0.714035 |
04506ae8b276a33189ed9b7a3e938cb136b68271 | 3,546 | /*
Copyright [2016] [Jae Hun, Bang]
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.uclab.mm.icl.llc.MachineLearningTools;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import org.uclab.mm.icl.llc.AER.jh.ConvertAudioData;
import mm.icl.llc.MachineLearningTools.Segmentation;
/**
* This Class segment audio data based on seconds
*
* @author Bang Gae
*
*/
public class WindowBasedSegmentation extends
Segmentation<AudioInputStream, AudioInputStream> {
int threshold;
int size;
AudioFormat audioFM;
ConvertAudioData cad = new ConvertAudioData();
boolean segFlag = false;
/**
* Set Window for Segmentation with sample rate and second
*
* @param sec
* @param samplerate
*/
public WindowBasedSegmentation(int sec, int samplerate) {
this.threshold = sec * samplerate;
}
/**
* Segment Audio Data based on setted second
*
* @param input
* @return AudioInputStream
*/
@Override
public AudioInputStream segmentation(AudioInputStream input) {
// TODO Auto-generated method stub
AudioInputStream ais = null;
size = (int) (threshold * input.getFormat().getFrameSize());
if (threshold <= input.getFrameLength()+22) {
audioFM = input.getFormat();
ais = cad.convertAudioInputStream(segmentData(input), audioFM);
segFlag = true;
}
return ais;
}
public AudioInputStream[] divideInputStream(AudioInputStream input,
int divideNumber) {
AudioInputStream[] ais = new AudioInputStream[divideNumber];
for (int i = 0; i < divideNumber; i++) {
try {
AudioFormat audioFM = input.getFormat();
byte[] header = new byte[44];
byte[] data = new byte[(int) (input.getFrameLength()*input.getFormat().getFrameSize()) / divideNumber];
input.read(header);
input.read(data);
ais[i] = cad.convertAudioInputStream(data, audioFM);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return ais;
}
/**
* Segment data by byte read
*
* @param input
* @return byte[]
*/
public byte[] segmentData(AudioInputStream input) {
byte[] header = new byte[44];
byte[] temp = new byte[size];
try {
input.read(header);
input.read(temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return temp;
}
/**
* return remained data
*
* @param input
* @return AudioInputStream
*/
public AudioInputStream returnRemainedData(AudioInputStream input) {
if (segFlag) {
byte[] remained = new byte[(int) (input.getFrameLength()
* input.getFormat().getFrameSize() - size)];
AudioInputStream ais = null;
try {
input.read(remained);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ais = cad.convertAudioInputStream(remained, audioFM);
segFlag = false;
return ais;
}
return input;
}
}
| 25.695652 | 108 | 0.675409 |
6387e75aa75d2af133042539aa986d533f00801e | 2,382 | package com.epam.jdi.httptests.examples.requestparams;
import com.epam.http.response.RestResponse;
import com.epam.jdi.services.JettyService;
import com.epam.jdi.httptests.support.WithJetty;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static com.epam.http.requests.RequestDataFactory.*;
import static com.epam.http.requests.ServiceInit.init;
import static com.epam.jdi.services.JettyService.*;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.testng.Assert.assertEquals;
/**
* This class is using for delete cases for JettyService
* Tests are similar to rest assured cases
*/
public class DeleteTest extends WithJetty {
private static final String TEST_BODY_VALUE = "a body";
private static final String FIRST_NAME = "firstName";
private static final String LAST_NAME = "lastName";
private static final String FIRST_NAME_VALUE = "John";
private static final String LAST_NAME_VALUE = "Doe";
private static final String USERNAME = "username";
private static final String TOKEN = "token";
private static final String TOKEN_VALUE = "1234";
@BeforeTest
public void before() {
init(JettyService.class);
}
@Test
public void requestSpecificationAllowsSpecifyingCookie() {
RestResponse response = deleteCookie.call(cookies().addAll(new Object[][]{
{USERNAME, FIRST_NAME_VALUE},
{TOKEN, TOKEN_VALUE}
}));
assertEquals(response.getBody(), "username, token");
}
@Test
public void bodyHamcrestMatcherWithKey() {
deleteGreet.call(queryParams().addAll(new Object[][] {
{ FIRST_NAME, FIRST_NAME_VALUE },
{ LAST_NAME, LAST_NAME_VALUE }
})).isOk().assertThat().body("greeting", equalTo("Greetings John Doe"));
}
@Test
public void bodyHamcrestMatcherWithOutKey() {
deleteGreet.call(queryParams().addAll(
new Object[][]{{FIRST_NAME, FIRST_NAME_VALUE},
{LAST_NAME, LAST_NAME_VALUE}
})).isOk().assertThat().body(equalTo("{\"greeting\":\"Greetings John Doe\"}"));
}
@Test
public void deleteSupportsStringBody() {
RestResponse response = deleteBody.call(body(TEST_BODY_VALUE));
response.assertThat().body(is(TEST_BODY_VALUE));
}
}
| 35.552239 | 95 | 0.692695 |
b557b93b4883c314bbef02e2b92774d98e680e61 | 4,249 | /*
* Copyright 2018 Confluent Inc.
*
* Licensed under the Confluent Community License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.ksql.serde.delimited;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import io.confluent.ksql.GenericRow;
import io.confluent.ksql.logging.processing.ProcessingLogConfig;
import io.confluent.ksql.logging.processing.ProcessingLogger;
import io.confluent.ksql.serde.SerdeTestUtils;
import io.confluent.ksql.serde.util.SerdeProcessingLogMessageFactory;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Optional;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class KsqlDelimitedDeserializerTest {
private Schema orderSchema;
private final ProcessingLogConfig processingLogConfig
= new ProcessingLogConfig(Collections.emptyMap());
private KsqlDelimitedDeserializer delimitedDeserializer;
@Mock
private ProcessingLogger recordLogger;
@Rule
public final MockitoRule mockitoRule = MockitoJUnit.rule();
@Before
public void before() {
orderSchema = SchemaBuilder.struct()
.field("ordertime".toUpperCase(), org.apache.kafka.connect.data.Schema.OPTIONAL_INT64_SCHEMA)
.field("orderid".toUpperCase(), org.apache.kafka.connect.data.Schema.OPTIONAL_INT64_SCHEMA)
.field("itemid".toUpperCase(), org.apache.kafka.connect.data.Schema.OPTIONAL_STRING_SCHEMA)
.field("orderunits".toUpperCase(), org.apache.kafka.connect.data.Schema.OPTIONAL_FLOAT64_SCHEMA)
.build();
delimitedDeserializer = new KsqlDelimitedDeserializer(
orderSchema,
recordLogger);
}
@Test
public void shouldDeserializeDelimitedCorrectly() {
final String rowString = "1511897796092,1,item_1,10.0\r\n";
final GenericRow genericRow = delimitedDeserializer.deserialize(
"",
rowString.getBytes(StandardCharsets.UTF_8));
assertThat(genericRow.getColumns().size(), equalTo(4));
assertThat(genericRow.getColumns().get(0), equalTo(1511897796092L));
assertThat(genericRow.getColumns().get(1), equalTo(1L));
assertThat(genericRow.getColumns().get(2), equalTo("item_1"));
assertThat(genericRow.getColumns().get(3), equalTo(10.0));
}
@Test
public void shouldLogErrors() {
Throwable cause = null;
final byte[] record = "badnumfields".getBytes(StandardCharsets.UTF_8);
try {
delimitedDeserializer.deserialize("topic", record);
fail("deserialize should have thrown");
} catch (final SerializationException e) {
cause = e.getCause();
}
SerdeTestUtils.shouldLogError(
recordLogger,
SerdeProcessingLogMessageFactory.deserializationErrorMsg(
cause,
Optional.ofNullable(record)).apply(processingLogConfig),
processingLogConfig);
}
@Test
public void shouldDeserializeJsonCorrectlyWithRedundantFields() {
final String rowString = "1511897796092,1,item_1,\r\n";
final GenericRow genericRow = delimitedDeserializer.deserialize(
"",
rowString.getBytes(StandardCharsets.UTF_8));
assertThat(genericRow.getColumns().size(), equalTo(4));
assertThat(genericRow.getColumns().get(0), equalTo(1511897796092L));
assertThat(genericRow.getColumns().get(1), equalTo(1L));
assertThat(genericRow.getColumns().get(2), equalTo("item_1"));
Assert.assertNull(genericRow.getColumns().get(3));
}
}
| 37.60177 | 104 | 0.749823 |
f929b4addf4c84b2f027753c6ebb4b4f82d4cf0d | 2,350 | package de.codescape.jira.plugins.scrumpoker.service;
import com.atlassian.activeobjects.test.TestActiveObjects;
import de.codescape.jira.plugins.scrumpoker.ScrumPokerTestDatabaseUpdater;
import de.codescape.jira.plugins.scrumpoker.ao.ScrumPokerProject;
import net.java.ao.EntityManager;
import net.java.ao.Query;
import net.java.ao.test.converters.NameConverters;
import net.java.ao.test.jdbc.Data;
import net.java.ao.test.jdbc.Hsql;
import net.java.ao.test.jdbc.Jdbc;
import net.java.ao.test.junit.ActiveObjectsJUnitRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(ActiveObjectsJUnitRunner.class)
@Data(ScrumPokerTestDatabaseUpdater.class)
@Jdbc(Hsql.class)
@NameConverters
public class ProjectSettingServiceImplTest {
@SuppressWarnings("unused")
private EntityManager entityManager;
private TestActiveObjects activeObjects;
private ProjectSettingService projectSettingService;
@Before
public void before() {
activeObjects = new TestActiveObjects(entityManager);
projectSettingService = new ProjectSettingServiceImpl(activeObjects);
deleteAllScrumPokerProjectConfigurations();
}
private void deleteAllScrumPokerProjectConfigurations() {
ScrumPokerProject[] scrumPokerProjects = activeObjects.find(ScrumPokerProject.class);
Arrays.stream(scrumPokerProjects).forEach(activeObjects::delete);
}
@Test
public void shouldPersistScrumPokerEnabledFlag() {
projectSettingService.persistScrumPokerEnabled(1L, true);
assertThat(scrumPokerProject(1L).isScrumPokerEnabled(), is(true));
}
@Test
public void scrumPokerEnableFlagReturnsFalseIfProjectHasNoConfiguration() {
assertThat(projectSettingService.loadScrumPokerEnabled(2L), is(false));
}
private ScrumPokerProject scrumPokerProject(Long projectId) {
ScrumPokerProject[] scrumPokerProjects = activeObjects.find(ScrumPokerProject.class,
Query.select().where("PROJECT_ID = ?", 1L).limit(1));
if (scrumPokerProjects.length < 1) {
throw new RuntimeException("ScrumPokerProject with ID " + projectId + " not found.");
}
return scrumPokerProjects[0];
}
}
| 35.074627 | 97 | 0.763404 |
717efb37c1a20da515e44b2b98b12dc18346cf96 | 1,366 | package com.upseil.gdx.box2d.component;
import com.artemis.PooledComponent;
import com.artemis.annotations.DelayedComponentRemoval;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Disposable;
@DelayedComponentRemoval
public class Box2DWorld extends PooledComponent implements Disposable {
private World world;
public Box2DWorld initialize(Vector2 gravity) {
return initialize(gravity, true);
}
public Box2DWorld initialize(Vector2 gravity, boolean allowSleep) {
if (world != null) {
throw new IllegalStateException("Allready initialized");
}
world = new World(gravity, allowSleep);
return this;
}
public World get() {
return world;
}
public void step(float timeStep, int velocityIterations, int positionIterations) {
world.step(timeStep, velocityIterations, positionIterations);
}
public Body createBody(BodyDef bodyDefinition) {
return world.createBody(bodyDefinition);
}
@Override
protected void reset() {
dispose();
world = null;
}
@Override
public void dispose() {
world.dispose();
}
}
| 25.773585 | 86 | 0.673499 |
71fda1ec97148c70e6ef6f7bb567f6e734fd92d9 | 1,119 | package com.darcy.concurrent.c72;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class WaitThread extends Thread {
private volatile boolean fire = false;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
@Override
public void run() {
try {
lock.lock();
try {
while (!fire) {
condition.await();
}
} finally {
lock.unlock();
}
System.out.println("fired");
} catch (InterruptedException e) {
Thread.interrupted();
}
}
public void fire() {
lock.lock();
try {
this.fire = true;
condition.signal();
} finally {
lock.unlock();
}
}
//错误用法,将signal误写为了notify
// public void fire() {
// lock.lock();
// try {
// this.fire = true;
// condition.notify();
// } finally {
// lock.unlock();
// }
// }
public static void main(String[] args) throws InterruptedException {
WaitThread waitThread = new WaitThread();
waitThread.start();
Thread.sleep(1000);
System.out.println("fire");
waitThread.fire();
}
}
| 19.293103 | 69 | 0.651475 |
1b876cee6cd005ee65f8812d601a0474456fa287 | 3,583 | /*
* 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 io.kylin.mdx.insight.server.support;
import io.kylin.mdx.insight.core.model.acl.AclDataset;
import io.kylin.mdx.insight.core.model.acl.AclDependColumn;
import io.kylin.mdx.insight.core.model.acl.AclNamedSet;
import io.kylin.mdx.web.rewriter.SimpleValidator;
import io.kylin.mdx.web.rewriter.utils.ExpFinder;
import io.kylin.mdx.web.rewriter.utils.ExpUtils;
import mondrian.olap.Exp;
import mondrian.olap.Id;
import mondrian.util.Pair;
import java.util.ArrayList;
import java.util.List;
public class DependResolver {
private final SimpleValidator validator = new SimpleValidator();
/**
* 解析一个表达式依赖的实体
*
* @param dataset 数据集模型
* @param dependColumn 表达式
* @return 实体依赖结果
*/
public DependResult resolve(AclDataset dataset, AclDependColumn dependColumn) {
Exp exp = validator.parseExpression(dependColumn.getExpression());
DependResult result = new DependResult();
ExpFinder.traversalAndApply(exp, new ExpFinder.Consumer2FunctionAdapter<>(e -> {
if (!(e instanceof Id)) {
return;
}
Id id = (Id) e;
if (ExpUtils.isMeasures(id)) {
// 判断顺序: 计算度量 -> 普通度量
String measureName = ExpUtils.getSimpleMeasureName(id);
AclDependColumn measure = dataset.getCalculateMeasure(measureName);
if (measure == null) {
measure = dataset.getMeasureByAlias(measureName);
}
if (measure != null) {
result.depends.add(measure);
}
} else {
if (!(id.getElement(0) instanceof Id.NameSegment)) {
return;
}
String dimensionName = ((Id.NameSegment) id.getElement(0)).getName();
AclNamedSet namedSet = dataset.getNamedSet(dimensionName);
if (namedSet != null) {
// 命名集
result.depends.add(namedSet);
} else {
// 普通维度
String dimColName = ExpUtils.getSimpleHierarchyName(id);
if (dimColName != null) {
result.dimNames.add(new Pair<>(dimensionName, dimColName));
}
}
}
}, false), true);
return result;
}
public static class DependResult {
private final List<AclDependColumn> depends = new ArrayList<>();
private final List<Pair<String, String>> dimNames = new ArrayList<>();
public List<AclDependColumn> getDepends() {
return depends;
}
public List<Pair<String, String>> getDimNames() {
return dimNames;
}
}
}
| 35.127451 | 88 | 0.612615 |
d1d072ac4dad81ffdea5c4ba4c69fdcb4b5ee31b | 3,746 | package org.xujin.moss.client.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import javax.annotation.Resource;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;
public class AdminEndpointApplicationRunListener implements SpringApplicationRunListener {
private static final Log logger = LogFactory.getLog(AdminEndpointApplicationRunListener.class);
private static final String SPRINGBOOT_MANAGEMENT_ENABLED_KEY = "management.server.security.enabled";
private static final boolean SPRINGBOOT_MANAGEMENT_ENABLED_VALUE = false;
private static final String SPRINGBOOT_MANAGEMENT_PORT_KEY = "management.server.port";
private static final int SPRINGBOOT_MANAGEMENT_PORT_VALUE = 8081;
private static final String ENDPOINTS_ENABLED = "management.endpoints.enabled-by-default";
private static final String ENDPOINTS_JMX_INCLUDE = "management.endpoints.jmx.exposure.include";
private static final String ENDPOINTS_WEB_INCLUDE = "management.endpoints.web.exposure.include";
private static final String INCLUDE_ALL = "*";
private static final String GIT_MODE="management.info.git.mode";
private static final String GIT_FULL="full";
@Resource
private ManagementServerProperties managementServerProperties;
public AdminEndpointApplicationRunListener(SpringApplication application, String[] args) {
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
}
@Override
public void environmentPrepared(ConfigurableEnvironment env) {
Properties props = new Properties();
if (managementServerProperties == null) {
props.put(SPRINGBOOT_MANAGEMENT_ENABLED_KEY, SPRINGBOOT_MANAGEMENT_ENABLED_VALUE);
props.put(SPRINGBOOT_MANAGEMENT_PORT_KEY, getManagementPort(env));
props.put(ENDPOINTS_ENABLED, true);
props.put(ENDPOINTS_JMX_INCLUDE, INCLUDE_ALL);
props.put(ENDPOINTS_WEB_INCLUDE, INCLUDE_ALL);
props.put(GIT_MODE,GIT_FULL);
}
env.getPropertySources().addLast(new PropertiesPropertySource("endpoint", props));
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
}
private int getManagementPort(ConfigurableEnvironment env) {
if (!"prod".equalsIgnoreCase(env.getProperty("spring.profiles.active"))) {
try {
//不是生产环境,使用Socket去连接如果能连接上表示端口被占用
InetAddress Address = InetAddress.getByName("127.0.0.1");
Socket socket = new Socket(Address, SPRINGBOOT_MANAGEMENT_PORT_VALUE);
logger.info(SPRINGBOOT_MANAGEMENT_PORT_VALUE+":port is used,return:0");
return 0;
} catch (IOException e) {
logger.info(SPRINGBOOT_MANAGEMENT_PORT_VALUE+":port is not used");
}
}
return SPRINGBOOT_MANAGEMENT_PORT_VALUE;
}
@Override
public void running(ConfigurableApplicationContext context) {
}
@Override
public void started(ConfigurableApplicationContext context) {
}
@Override
public void starting() {
}
}
| 37.838384 | 105 | 0.742926 |
d79b6fa323b7d52488bf4e6ce15993d1f70ac418 | 1,344 | /*
* 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 lab4_sergiosuazoalessandroreyes;
/**
*
* @author Sergio
*/
public class Buscador extends Jugador{
private int peso,velocidad;
public Buscador() {
}
public Buscador(int peso, String nombre, String casa, int año, int numero) {
super(nombre, casa, año, numero);
this.peso = peso;
this.velocidad = (200/peso)*7;
}
public int getPeso() {
return peso;
}
public void setPeso(int peso) {
this.peso = peso;
}
public int getVelocidad() {
return velocidad;
}
public void setVelocidad(int velocidad) {
this.velocidad = velocidad;
}
@Override
public String toString() {
return "Buscador: peso=" + peso + ", velocidad=" + velocidad;
}
@Override
public boolean Juego(int j,boolean b) {
if((velocidad/14+14>j))
{
return true;
}
else
{
return false;
}
}
@Override
public boolean Trampa(int i) {
if(i<=5)
{
return true;
}
else
{
return false;
}
}
}
| 18.929577 | 80 | 0.545387 |
27b5b39bb551ab4ecc7ce6b4bb6a8b34a255e57a | 11,908 | /* Copyright 2018 Telstra Open Source
*
* 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.openkilda.pce.janitor;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* FlowJanitor holds methods that facilitate detecting and fixing issues with flows. Examples will be included over
* time.
*/
@SuppressWarnings({"squid:S1192"})
public class FlowJanitor {
/**
* Use to get the flows that share the same cookie (eg 1 cookie, N flows).
*/
private static final String DUPLICATE_COOKIES_QUERY =
"MATCH (:switch) -[rel:flow]-> (:switch)"
+ " WITH rel.cookie as affected_cookie, COUNT(rel.cookie) as cookie_num"
+ " WHERE cookie_num > 1"
+ " MATCH (:switch) -[rel2:flow]-> (:switch)"
+ " WHERE rel2.cookie = affected_cookie"
+ " RETURN affected_cookie, rel2.flowid as affected_flow_id"
+ " ORDER BY affected_cookie ";
/**
* Use to get the flows that have multiple instances (ie N flows .. should be just 1 flow).
*/
private static final String DUPLICATE_FLOWS_QUERY =
"MATCH (:switch) -[rel:flow]-> (:switch)"
+ " WITH rel.flowid as affected_flow_id, COUNT(rel.flowid) as flow_num"
+ " WHERE flow_num > 2"
+ " MATCH (:switch) -[rel2:flow]-> (:switch)"
+ " WHERE rel2.flowid = affected_flow_id"
+ " RETURN affected_flow_id, rel2.cookie as affected_flow_cookie"
+ " ORDER BY affected_flow_id";
@SuppressWarnings("squid:ClassVariableVisibilityCheck")
public static final class Config {
public String neoUrl;
public String neoUser;
public String neoPswd;
public String nbUrl;
public String nbUser;
public String nbPswd;
public String action;
}
/**
* Returns the number of cookies that have more than one flow.
*
* @return the number of cookies that have more than one flow. This shouldn't happen, but this is here to catch
* scenarios where it does. '2' means two cookies have more than 1 flow each.
*/
public int countDuplicateCookies() {
throw new UnsupportedOperationException("Not implemented yet.");
}
/**
* Returns the number of cookies that have more than one flow.
*
* @return the number of cookies that have more than one flow. This shouldn't happen, but this is here to catch
* scenarios where it does. '2' means two cookies have more than 1 flow each.
*/
public List<String> flowsWithDuplicateCookies(boolean verbose) {
throw new UnsupportedOperationException("Not implemented yet.");
}
/**
* Updates flows.
*
* @param config the flow janitor config
* @param flowsToUpdate list of flows to update
*/
@SuppressWarnings("squid:S106")
private static void updateFlows(FlowJanitor.Config config, List<String> flowsToUpdate) {
String authString = config.nbUser + ":" + config.nbPswd;
String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
Client client = ClientBuilder.newClient();
for (String flowid : flowsToUpdate) {
/*
* Get the Flows .. call NB for each
*/
sleep();
System.out.println("RUNNING: flowid = " + flowid);
WebTarget webTarget = client.target(config.nbUrl + "/api/v1/flows").path(flowid);
Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_JSON)
.header("Authorization", "Basic " + authStringEnc);
Response response = invocationBuilder.get(Response.class);
if (response.getStatus() != 200) {
throw new IllegalStateException("Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.readEntity(String.class);
/*
* Call update Flow .. add to description
*/
String[] split = output.split("PUSHED FLOW");
if (split.length == 2) {
output = split[0] + "PUSHED FLOW. FIX cookie dupe." + split[1];
}
// LOOP
response = invocationBuilder.put(Entity.entity(output, MediaType.APPLICATION_JSON));
if (response.getStatus() != 200) {
System.out.println("FAILURE: flowid = " + flowid + "; response = " + response.getStatus());
}
}
}
/**
* With the right URL, username, password, and method keyword, the methods above can be called.
*/
@SuppressWarnings({"squid:S106", "squid:S1135"})
public static void main(String[] args) {
Options options = new Options();
options.addOption(Option.builder("url").required(true).hasArg()
.desc("The URL of the Neo4J DB - i.e. bolt://neo..:7474").build());
options.addOption(Option.builder("u").required(true).hasArg().longOpt("user")
.desc("The Neo4J username - e.g. neo4j").build());
options.addOption(Option.builder("p").required(true).hasArg().longOpt("password")
.desc("The Neo4J password - e.g. neo4j").build());
options.addOption(Option.builder("nburl").required(true).hasArg()
.desc("The URL of the Neo4J DB - i.e. http://northboud..:8080").build());
options.addOption(Option.builder("nbu").required(true).hasArg().longOpt("user")
.desc("The Neo4J username - e.g. kilda").build());
options.addOption(Option.builder("nbp").required(true).hasArg().longOpt("password")
.desc("The Neo4J password - e.g. kilda").build());
options.addOption(Option.builder("a").required(true).hasArg().longOpt("action")
.desc("The action to take - e.g. ountDuplicateCookies").build());
options.addOption(Option.builder("v").required(false).longOpt("verbose")
.desc("Where appropriate, return a verbose response").build());
CommandLine commandLine;
CommandLineParser parser = new DefaultParser();
Driver driver = null;
try {
commandLine = parser.parse(options, args);
FlowJanitor.Config config = new FlowJanitor.Config();
config.neoUrl = commandLine.getOptionValue("url");
config.neoUser = commandLine.getOptionValue("u");
config.neoPswd = commandLine.getOptionValue("p");
config.nbUrl = commandLine.getOptionValue("nburl");
config.nbUser = commandLine.getOptionValue("nbu");
config.nbPswd = commandLine.getOptionValue("nbp");
config.action = commandLine.getOptionValue("a");
driver = GraphDatabase.driver(config.neoUrl, AuthTokens.basic(config.neoUser, config.neoPswd));
if (config.action.equals("DeDupeFlows")) {
Session session = driver.session();
StatementResult result = session.run(DUPLICATE_FLOWS_QUERY);
Map<String, List<Long>> flowsToUpdate = new HashMap<>();
for (Record record : result.list()) {
String flowid = record.get("affected_flow_id").asString();
List<Long> priors = flowsToUpdate.computeIfAbsent(flowid, empty -> new ArrayList<>());
priors.add(record.get("affected_flow_cookie").asLong());
}
session.close();
System.out.println("flowsToUpdate.size() = " + flowsToUpdate.size());
System.out.println("flowsToUpdate = " + flowsToUpdate);
System.out.println("Will De-Dupe the Flows");
String authString = config.nbUser + ":" + config.nbPswd;
String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
Client client = ClientBuilder.newClient();
for (String flowid : flowsToUpdate.keySet()) {
/*
* Get the Flows .. call NB for each
*/
sleep();
System.out.println("RUNNING: flowid = " + flowid);
WebTarget webTarget = client.target(config.nbUrl + "flows").path(flowid);
Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_JSON)
.header("Authorization", "Basic " + authStringEnc);
Response response = invocationBuilder.get(Response.class);
if (response.getStatus() != 200) {
throw new IllegalStateException("Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.readEntity(String.class);
System.out.println("output = " + output);
System.exit(0);
}
} else {
// TODO: switch, based on action
Session session = driver.session();
StatementResult result = session.run(DUPLICATE_COOKIES_QUERY);
List<String> flowsToUpdate = new ArrayList<>();
for (Record record : result.list()) {
flowsToUpdate.add(record.get("affected_flow_id").asString());
}
session.close();
System.out.println("flowsToUpdate.size() = " + flowsToUpdate.size());
System.out.println("flowsToUpdate = " + flowsToUpdate);
System.exit(0);
FlowJanitor.updateFlows(config, flowsToUpdate);
}
} catch (ParseException exception) {
System.out.print("Parse error: ");
System.out.println(exception.getMessage());
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("FlowJanitor", options);
} finally {
if (driver != null) {
driver.close();
}
}
}
private static void sleep() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
//ignore it
}
}
}
| 41.347222 | 115 | 0.59481 |
784fec376125ef6bb7b8e1dcb55c9a5edda157f6 | 4,438 | package org.tinyj.lava.binder;
import org.tinyj.lava.*;
import static java.util.Objects.requireNonNull;
/**
* Enable various forms of currying on {@link LavaBiConsumer}.
* <p>
* To enable a fluent syntax binders wrapping the curried function are returned
* where applicable. This introduces some overhead that might be an issue if
* either the result is invoked many times or many results are produced. Use
* {@code bound()} unwrap these results.
*
* @param <X> the type of the first argument to the operation
* @param <Y> the type of the second argument to the operation
*/
public class LavaBiConsumerBinder<X, Y, E extends Exception>
implements LavaBiConsumer<X, Y, E> {
protected final LavaBiConsumer<X, Y, E> bound;
public LavaBiConsumerBinder(LavaBiConsumer<? super X, ? super Y, ? extends E> bound) {
requireNonNull(bound);
this.bound = LavaBiConsumer.castDown(bound);
}
/**
* Flip the arguments.
*/
public LavaBiConsumerBinder<Y, X, E>
flip() { return new LavaBiConsumerBinder<>((y, x) -> bound.checkedAccept(x, y)); }
/**
* Curries both arguments.
*/
public LavaRunnable<E>
bind(X x, Y y) { return () -> bound.checkedAccept(x, y); }
/**
* Curry the first argument.
*/
public LavaConsumerBinder<Y, E>
bindFirst(X x) { return new LavaConsumerBinder<>(y -> bound.checkedAccept(x, y)); }
/**
* Curry the second argument.
*/
public LavaConsumerBinder<X, E>
bindSecond(Y y) { return new LavaConsumerBinder<>(x -> bound.checkedAccept(x, y)); }
/**
* Link both arguments to supplied values. {@code x} and {@code y} are invoked each
* time the resulting {@link LavaRunnable} is invoked and the results are supplied as
* arguments to the bound {@link LavaBiConsumer}.
*/
public LavaRunnable<?>
link(LavaSupplier<? extends X, ?> x, LavaSupplier<? extends Y, ?> y) {
requireNonNull(x);
requireNonNull(y);
return () -> bound.checkedAccept(x.checkedGet(), y.checkedGet());
}
/**
* Map both arguments. {@code x} and {@code y} are invoked each time the resulting
* {@link LavaBiConsumer} is invoked and the results are supplied as arguments to the
* bound {@link LavaBiConsumer}.
*/
public <U, V> LavaBiConsumerBinder<U, V, ?>
link(LavaFunction<? super U, ? extends X, ?> x, LavaFunction<? super V, ? extends Y, ?> y) {
requireNonNull(x);
requireNonNull(y);
return new LavaBiConsumerBinder<>((u, v) -> bound.checkedAccept(x.checkedApply(u), y.checkedApply(v)));
}
/**
* Link the first argument to supplied value. {@code x} is invoked each time the
* resulting {@link LavaConsumer} is invoked and the results is supplied as first
* argument to the bound {@link LavaBiConsumer}.
*/
public LavaConsumerBinder<Y, ?>
linkFirst(LavaSupplier<? extends X, ?> x) {
requireNonNull(x);
return new LavaConsumerBinder<>(y -> bound.checkedAccept(x.checkedGet(), y));
}
/**
* Map the first argument. {@code x} is invoked each time the resulting
* {@link LavaBiConsumer} is invoked and the result is supplied as first argument
* to the bound {@link LavaBiConsumer}.
*/
public <U> LavaBiConsumerBinder<U, Y, ?>
linkFirst(LavaFunction<? super U, ? extends X, ?> x) {
requireNonNull(x);
return new LavaBiConsumerBinder<>((u, y) -> bound.checkedAccept(x.checkedApply(u), y));
}
/**
* Link the second argument to supplied value. {@code y} is invoked each time the
* resulting {@link LavaConsumer} is invoked and the results is supplied as second
* argument to the bound {@link LavaBiConsumer}.
*/
public LavaConsumerBinder<X, ?>
linkSecond(LavaSupplier<? extends Y, ?> y) {
requireNonNull(y);
return new LavaConsumerBinder<>(x -> bound.checkedAccept(x, y.checkedGet()));
}
/**
* Map the second argument. {@code y} is invoked each time the resulting
* {@link LavaBiConsumer} is invoked and the result is supplied as second argument
* to the bound {@link LavaBiConsumer}.
*/
public <V> LavaBiConsumerBinder<X, V, ?>
linkSecond(LavaFunction<? super V, ? extends Y, ?> y) {
requireNonNull(y);
return new LavaBiConsumerBinder<>((x, v) -> bound.checkedAccept(x, y.checkedApply(v)));
}
/**
* @return the wrapped {@link LavaBiConsumer}
*/
public LavaBiConsumer<X, Y, E>
bound() {
return bound;
}
@Override
public void checkedAccept(X x, Y y) throws E { bound.checkedAccept(x, y); }
}
| 33.877863 | 107 | 0.67598 |
3ba84d37ab4381bf6b5436b20e388d9f5191e94d | 7,329 | package com.swingtech.common.core.util.introspect.core;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Set;
import org.springframework.util.ClassUtils;
public class SpringFileUtilsWrapper {
private static final SpringFileUtilsWrapper instance = new SpringFileUtilsWrapper();
public static SpringFileUtilsWrapper getInstanceinstance() {
return instance;
}
public ClassLoader getDefaultClassLoader() {
return ClassUtils.getDefaultClassLoader();
}
public ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {
return ClassUtils.overrideThreadContextClassLoader(classLoaderToUse);
}
public Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError {
return ClassUtils.forName(name, classLoader);
}
public Class<?> resolveClassName(String className, ClassLoader classLoader) throws IllegalArgumentException {
return ClassUtils.resolveClassName(className, classLoader);
}
public Class<?> resolvePrimitiveClassName(String name) {
return ClassUtils.resolvePrimitiveClassName(name);
}
public boolean isPresent(String className, ClassLoader classLoader) {
return ClassUtils.isPresent(className, classLoader);
}
public Class<?> getUserClass(Object instance) {
return ClassUtils.getUserClass(instance);
}
public Class<?> getUserClass(Class<?> clazz) {
return ClassUtils.getUserClass(clazz);
}
public boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
return ClassUtils.isCacheSafe(clazz, classLoader);
}
public String getShortName(String className) {
return ClassUtils.getShortName(className);
}
public String getShortName(Class<?> clazz) {
return ClassUtils.getShortName(clazz);
}
public String getShortNameAsProperty(Class<?> clazz) {
return ClassUtils.getShortNameAsProperty(clazz);
}
public String getClassFileName(Class<?> clazz) {
return ClassUtils.getClassFileName(clazz);
}
public String getPackageName(Class<?> clazz) {
return ClassUtils.getPackageName(clazz);
}
public String getPackageName(String fqClassName) {
return ClassUtils.getPackageName(fqClassName);
}
public String getQualifiedName(Class<?> clazz) {
return ClassUtils.getQualifiedName(clazz);
}
public String getQualifiedMethodName(Method method) {
return ClassUtils.getQualifiedMethodName(method);
}
public String getDescriptiveType(Object value) {
return ClassUtils.getDescriptiveType(value);
}
public boolean matchesTypeName(Class<?> clazz, String typeName) {
return ClassUtils.matchesTypeName(clazz, typeName);
}
public boolean hasConstructor(Class<?> clazz, Class<?>... paramTypes) {
return ClassUtils.hasConstructor(clazz, paramTypes);
}
public <T> Constructor<T> getConstructorIfAvailable(Class<T> clazz, Class<?>... paramTypes) {
return ClassUtils.getConstructorIfAvailable(clazz, paramTypes);
}
public boolean hasMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
return ClassUtils.hasMethod(clazz, methodName, paramTypes);
}
public Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
return ClassUtils.getMethod(clazz, methodName, paramTypes);
}
public Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
return ClassUtils.getMethodIfAvailable(clazz, methodName, paramTypes);
}
public int getMethodCountForName(Class<?> clazz, String methodName) {
return ClassUtils.getMethodCountForName(clazz, methodName);
}
public boolean hasAtLeastOneMethodWithName(Class<?> clazz, String methodName) {
return ClassUtils.hasAtLeastOneMethodWithName(clazz, methodName);
}
public Method getMostSpecificMethod(Method method, Class<?> targetClass) {
return ClassUtils.getMostSpecificMethod(method, targetClass);
}
public boolean isUserLevelMethod(Method method) {
return ClassUtils.isUserLevelMethod(method);
}
public Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {
return ClassUtils.getStaticMethod(clazz, methodName, args);
}
public boolean isPrimitiveWrapper(Class<?> clazz) {
return ClassUtils.isPrimitiveWrapper(clazz);
}
public boolean isPrimitiveOrWrapper(Class<?> clazz) {
return ClassUtils.isPrimitiveOrWrapper(clazz);
}
public boolean isPrimitiveArray(Class<?> clazz) {
return ClassUtils.isPrimitiveArray(clazz);
}
public boolean isPrimitiveWrapperArray(Class<?> clazz) {
return ClassUtils.isPrimitiveWrapperArray(clazz);
}
public Class<?> resolvePrimitiveIfNecessary(Class<?> clazz) {
return ClassUtils.resolvePrimitiveIfNecessary(clazz);
}
public boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
return ClassUtils.isAssignable(lhsType, rhsType);
}
public boolean isAssignableValue(Class<?> type, Object value) {
return ClassUtils.isAssignableValue(type, value);
}
public String convertResourcePathToClassName(String resourcePath) {
return ClassUtils.convertResourcePathToClassName(resourcePath);
}
public String convertClassNameToResourcePath(String className) {
return ClassUtils.convertClassNameToResourcePath(className);
}
public String addResourcePathToPackagePath(Class<?> clazz, String resourceName) {
return ClassUtils.addResourcePathToPackagePath(clazz, resourceName);
}
public String classPackageAsResourcePath(Class<?> clazz) {
return ClassUtils.classPackageAsResourcePath(clazz);
}
public String classNamesToString(Class<?>... classes) {
return ClassUtils.classNamesToString(classes);
}
public String classNamesToString(Collection<Class<?>> classes) {
return ClassUtils.classNamesToString(classes);
}
public Class<?>[] toClassArray(Collection<Class<?>> collection) {
return ClassUtils.toClassArray(collection);
}
public Class<?>[] getAllInterfaces(Object instance) {
return ClassUtils.getAllInterfaces(instance);
}
public Class<?>[] getAllInterfacesForClass(Class<?> clazz) {
return ClassUtils.getAllInterfacesForClass(clazz);
}
public Class<?>[] getAllInterfacesForClass(Class<?> clazz, ClassLoader classLoader) {
return ClassUtils.getAllInterfacesForClass(clazz, classLoader);
}
public Set<Class<?>> getAllInterfacesAsSet(Object instance) {
return ClassUtils.getAllInterfacesAsSet(instance);
}
public Set<Class<?>> getAllInterfacesForClassAsSet(Class<?> clazz) {
return ClassUtils.getAllInterfacesForClassAsSet(clazz);
}
public Set<Class<?>> getAllInterfacesForClassAsSet(Class<?> clazz, ClassLoader classLoader) {
return ClassUtils.getAllInterfacesForClassAsSet(clazz, classLoader);
}
public Class<?> createCompositeInterface(Class<?>[] interfaces, ClassLoader classLoader) {
return ClassUtils.createCompositeInterface(interfaces, classLoader);
}
public Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) {
return ClassUtils.determineCommonAncestor(clazz1, clazz2);
}
public boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
return ClassUtils.isVisible(clazz, classLoader);
}
public boolean isCglibProxy(Object object) {
return ClassUtils.isCglibProxy(object);
}
public boolean isCglibProxyClass(Class<?> clazz) {
return ClassUtils.isCglibProxyClass(clazz);
}
public boolean isCglibProxyClassName(String className) {
return ClassUtils.isCglibProxyClassName(className);
}
}
| 30.924051 | 110 | 0.782371 |
0f89097853900bc05fc3c72f18553bcdb207847e | 1,375 | /*
* Copyright 2010-2019 Miyamoto Daisuke.
*
* 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 jp.xet.baseunits.util;
import static org.junit.Assert.fail;
import java.util.Iterator;
import jp.xet.baseunits.util.ImmutableIterator;
import org.junit.Test;
/**
* {@link ImmutableIterator}のテストクラス。
*/
public class ImmutableIteratorTest {
/**
* {@link ImmutableIterator}に対して {@link Iterator#remove()}ができないことを確認する。
*
* @throws Exception 例外が発生した場合
*/
@Test
public void test01_Remove() throws Exception {
Iterator<Void> iterator = new ImmutableIterator<Void>() {
@Override
public boolean hasNext() {
return true;
}
@Override
public Void next() {
return null;
}
};
try {
iterator.remove();
fail("remove is unsupported");
} catch (UnsupportedOperationException expected) {
// success
}
}
}
| 23.305085 | 75 | 0.704 |
b3fc8bce1944c090a272e5b9b2c3cedbd36e83e0 | 668 | package mundo;
public class Grafo {
private int cantidadDeNodos;
private int cantidadDeNodosTotal;
private Nodo [] nodos;
public Grafo(int cantidadDeNodosTotal){
cantidadDeNodos = 0;
nodos = new Nodo[cantidadDeNodosTotal];
this.cantidadDeNodosTotal = cantidadDeNodosTotal;
}
public void agregarNodo(Nodo nodo){
nodos [cantidadDeNodos++] = nodo;
}
public void agregarAdyacentes(Nodo nodoUno, Nodo nodoDos){
nodoUno.agregarAdyacente(nodoDos);
}
public Nodo [] obtenerNodos(){
return nodos;
}
public int obtenerCantidadDeNodos(){
return cantidadDeNodos;
}
public int obtenerCantidadDeNodosTotal(){
return cantidadDeNodosTotal;
}
}
| 18.555556 | 59 | 0.754491 |
2d9b58d9b31ef58062c71c7fb79649ae935d1d83 | 5,270 | package com.android.vending.billing.InAppBillingService.LACK.dialogs;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.vending.billing.InAppBillingService.LACK.AlertDlg;
import com.android.vending.billing.InAppBillingService.LACK.listAppsFragment;
import com.chelpus.Utils;
import java.io.PrintStream;
import org.json.JSONException;
import org.json.JSONObject;
public class Ext_Patch_Dialog
{
Dialog dialog = null;
public void dismiss()
{
if (this.dialog != null)
{
this.dialog.dismiss();
this.dialog = null;
}
}
public Dialog onCreateDialog()
{
System.out.println("Ext Patch Dialog create.");
if ((listAppsFragment.frag == null) || (listAppsFragment.frag.getContext() == null)) {
dismiss();
}
LinearLayout localLinearLayout1 = (LinearLayout)View.inflate(listAppsFragment.frag.getContext(), 2130968613, null);
LinearLayout localLinearLayout2 = (LinearLayout)localLinearLayout1.findViewById(2131558550).findViewById(2131558551);
int i = 0;
if (listAppsFragment.str == null) {
listAppsFragment.str = " ";
}
listAppsFragment.CurentSelect = 0;
listAppsFragment.contextext = listAppsFragment.frag.getContext();
Object localObject1 = null;
Object localObject2 = new String[listAppsFragment.str.split("\n").length];
String[] arrayOfString = listAppsFragment.str.split("\n");
int j = 1;
int k;
for (;;)
{
k = 0;
if ((j == 0) || (i >= arrayOfString.length)) {
break;
}
try
{
localObject2 = new JSONObject(arrayOfString[i]).getString("objects");
localObject1 = localObject2;
j = 0;
i = 0;
}
catch (JSONException localJSONException)
{
j = 1;
i += 1;
}
}
j = k;
if (localObject1 != null) {
j = Integer.parseInt((String)localObject1);
}
localObject1 = null;
if (j != 0)
{
localObject3 = new String[j + 1];
localObject1 = localObject3;
if (i < localObject3.length)
{
if (i == 0) {
localObject3[0] = "Please Select";
}
for (;;)
{
i += 1;
break;
localObject3[i] = ("Object N" + i);
}
}
}
Object localObject3 = Utils.getText(2131165448) + " " + j + " " + Utils.getText(2131165449);
listAppsFragment.tvt = (TextView)localLinearLayout2.findViewById(2131558552);
listAppsFragment.tvt.append(Utils.getColoredText((String)localObject3, -16711821, "bold"));
localObject3 = (Spinner)localLinearLayout2.findViewById(2131558553);
if (localObject1 != null)
{
listAppsFragment.CurentSelect = 0;
((Spinner)localObject3).setAdapter(new ArrayAdapter(listAppsFragment.frag.getContext(), 17367048, (Object[])localObject1));
((Spinner)localObject3).setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong)
{
if (paramAnonymousInt != 0) {
listAppsFragment.CurentSelect = paramAnonymousInt;
}
listAppsFragment.tvt.invalidate();
}
public void onNothingSelected(AdapterView<?> paramAnonymousAdapterView) {}
});
}
if (j == 0)
{
((Spinner)localObject3).setEnabled(false);
listAppsFragment.CurentSelect = 0;
}
localObject1 = Utils.getText(2131165450);
listAppsFragment.tvt = (TextView)localLinearLayout2.findViewById(2131558558);
listAppsFragment.tvt.append(Utils.getColoredText((String)localObject1, -990142, "bold"));
if (!listAppsFragment.str.contains("SU Java-Code Running!"))
{
localObject1 = "\n" + Utils.getText(2131165567) + "\n";
listAppsFragment.tvt = (TextView)localLinearLayout2.findViewById(2131558558);
listAppsFragment.tvt.append(Utils.getColoredText((String)localObject1, -16711681, "bold"));
}
localObject1 = new AlertDlg(listAppsFragment.frag.getContext(), true).setView(localLinearLayout1).create();
((Dialog)localObject1).setTitle(Utils.getText(2131165186));
((Dialog)localObject1).setCancelable(true);
((Dialog)localObject1).setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface paramAnonymousDialogInterface) {}
});
return (Dialog)localObject1;
}
public void showDialog()
{
if (this.dialog == null) {
this.dialog = onCreateDialog();
}
if (this.dialog != null) {
this.dialog.show();
}
}
}
/* Location: /Users/sundayliu/Desktop/gamecheat/com.android.vending.billing.InAppBillingService.LACK-1/classes-dex2jar.jar!/com/android/vending/billing/InAppBillingService/LACK/dialogs/Ext_Patch_Dialog.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 34.444444 | 220 | 0.672676 |
241fffcf945ee708278bd699441acdf68fa17205 | 2,436 | /*
* Copyright (c) 2005-2022 Xceptance Software Technologies GmbH
*
* 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.xceptance.xlt.performance.actions;
import com.xceptance.common.util.RegExUtils;
import com.xceptance.xlt.api.actions.AbstractLightWeightPageAction;
import com.xceptance.xlt.performance.util.ParameterUtils;
/**
* This is a simple test class for pulling urls. Fully configurable
* using properties.
*
* @author Rene Schwietzke
*
*/
public class LWSimpleURL extends AbstractLightWeightPageAction
{
private final String url;
private final String regexp;
/**
* @param previousAction
* @param timerName
*/
public LWSimpleURL(final String timerName, final String url, final String regexp)
{
super(timerName);
this.url = url;
this.regexp = regexp;
}
/**
* @param previousAction
* @param timerName
*/
public LWSimpleURL(AbstractLightWeightPageAction prevAction, final String timerName, final String url, final String regexp)
{
super(prevAction, timerName);
this.url = url;
this.regexp = regexp;
}
/* (non-Javadoc)
* @see com.xceptance.xlt.api.actions.AbstractAction#preValidate()
*/
@Override
public void preValidate() throws Exception
{
}
/* (non-Javadoc)
* @see com.xceptance.xlt.api.actions.AbstractAction#execute()
*/
@Override
protected void execute() throws Exception
{
// replace a random value position if needed
loadPage(ParameterUtils.replaceDynamicParameters(url));
}
/* (non-Javadoc)
* @see com.xceptance.xlt.api.actions.AbstractAction#postValidate()
*/
@Override
protected void postValidate() throws Exception
{
// validate response code
final String page = getContent();
RegExUtils.getMatchingCount(page, regexp);
}
}
| 27.370787 | 127 | 0.682677 |
18b889fd1e941fd2a937a1884d6616e9f774c474 | 1,625 | /*
* Copyright (C) 2013-2016 Peng Li<aqnote@qq.com>.
* This library is free software; you can redistribute it and/or modify it under the terms of
* the GNU Lesser General Public License as published by the Free Software Foundation;
*/
package com.aqnote.shared.lang.io;
import java.io.IOException;
import java.io.OutputStream;
/**
* 类OutputEngine.java的实现描述: 增量地将数据源写入到指定输出流的引擎, 本代码移植自IBM developer works精彩文章, 参见文档.
*
* @author "Peng Li"<aqnote@qq.com> May 7, 2012 4:54:12 PM
*/
public interface OutputEngine {
/** 默认的输出流工厂, 直接返回指定的输出流. */
OutputStreamFactory DEFAULT_OUTPUT_STREAM_FACTORY = new OutputStreamFactory() {
public OutputStream getOutputStream(OutputStream out) {
return out;
}};
/**
* 初始化输出引擎, 通常<code>OutputEngine</code>的实现会将一个<code>FilterOutputStream</code>连接到指定的输出流中.
*
* @param out 输出到指定的输出流
* @throws IOException 输入输出异常
*/
void open(OutputStream out) throws IOException;
/**
* 执行一次输出引擎. 此操作在<code>OutputEngine</code>的生命期中会被执行多次, 每次都将少量数据写入到初始化时指定的输出流.
*
* @throws IOException 输入输出异常
*/
void execute() throws IOException;
/**
* 扫尾工作. 当所有的输出都完成以后, 此方法被调用.
*
* @throws IOException 输入输出异常
*/
void close() throws IOException;
/**
* 创建输出流的工厂.
*/
interface OutputStreamFactory {
/**
* 创建输出流, 通常返回一个<code>FilterOutputStream</code>连接到指定的输出流中.
*
* @param out 输出到指定的输出流
* @return 输出流
* @throws IOException 输入输出异常
*/
OutputStream getOutputStream(OutputStream out) throws IOException;
}
}
| 26.639344 | 93 | 0.653538 |
766529b01aeeabae779f23a9a99840c690ee06d7 | 1,463 | package com.ybrain.jsoninterpreter.statements;
import com.ybrain.jsoninterpreter.ClassUtil;
public abstract class CallStmt extends Statement {
/**
* Arguments to pass
*/
Parameter parameters[] = new Parameter[0];
/**
* Cast parameter values to Java native
*
* @param context@return
* @throws Exception
*/
public Object[] getCastedParameterValues(JavaContext context) throws Exception {
Object[] parameterValues = new Object[parameters.length];
for (int idxParam = 0; idxParam < parameters.length; idxParam++) {
Parameter parameter = parameters[idxParam];
parameterValues[idxParam] = parameter.value.execute(context, "idx=" + idxParam);
}
return parameterValues;
}
public Class[] getParameterTypeClasses() throws ClassNotFoundException {
Class[] classes = new Class[parameters.length];
for (int i = 0; i < parameters.length; i++) {
classes[i] = parameters[i].getParameterTypeClass();
}
return classes;
}
/**
* Parameter information.
*/
public static class Parameter {
/**
* Canonical name of parameter type
*/
String type;
/**
* Value Expression.
*/
Statement value;
Class<?> getParameterTypeClass() throws ClassNotFoundException {
return ClassUtil.classForName(type);
}
}
}
| 27.092593 | 92 | 0.608339 |
f3f179f36225e8c2bfdf470b8484339b1433ba04 | 867 | package com.yz.rule.clean.enums;
import lombok.Getter;
/**
* @author yazhong
*/
@Getter
public enum LogisticEventEnums {
PUT_CONTAINER("放箱"),
EMPTY_CONTAINER_OUT("提空箱"),
BOXING("装箱"),
HEAVY_CONTAINER_ENTRY("重箱进港"),
CUSTOMS_INSPECTION("海关查验"),
CUSTOMS_CLEARANCE("海关放行"),
PORT_RELEASE("码头放行"),
BERTHING("靠泊"),
UNLOADING("卸载"),
LOADING("装载"),
UN_BERTHING("离泊"),
RECEIVING_PLACE_HEAVY_OUT("收货地重箱出场"),
RECEIVING_PLACE_EMPTY_ENTRY("收货地空箱返场"),
HEAVY_CONTAINER_IN_YARD("重箱进场"),
HEAVY_CONTAINER_OUT_YARD("重箱出场"),
LOCK_SHIP("船公司加锁"),
UNLOCK_SHIP("船公司解锁"),
SHUT_OUT("退关"),
CHECK("查验"),
PICK_UP_BACK("提退运箱"),
RELOAD("改装"),
RE_BOOKING("改配"),
OVERWEIGHT("超重"),
OVERRUN("超限"),
;
private String desc;
LogisticEventEnums(String desc) {
this.desc = desc;
}
}
| 20.642857 | 43 | 0.628604 |
05c79e9de2e3b73371f20fefe6e23dd9463808b8 | 963 | package com.ai.parts;
import com.ai.application.interfaces.*;
import org.w3c.dom.*;
import java.io.*;
import java.util.*;
import com.ai.application.utils.*;
import com.ai.data.*;
import javax.servlet.http.*;
import com.ai.common.*;
/**
* A sample part to be used for debugging
*
* Additional property file arguments
* None
*
* Expected input args
* name
*
* Output/Behaviour
* 1.resultName: Completed hello word string
* 2. Will write a debug message to the log
*
*/
public class HelloWorldPart extends AFactoryPart
{
protected Object executeRequestForPart(String requestName, Map inArgs)
throws RequestExecutionException
{
String name = (String)inArgs.get("name");
if (name == null)
{
name = "annonymous";
}
String message = "HelloWorld:" + name;
AppObjects.info(this,message);
return message;
}//eof-function
}//eof-class
| 21.886364 | 75 | 0.636552 |
919c41d1eecd0806faaa141fc0eae7528cec4f0e | 2,265 | package com.noelchew.ncutils.demo;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.textfield.TextInputEditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import com.noelchew.ncutils.alert.ToastUtil;
import com.noelchew.ncutils.demo.model.DummyObject;
/**
* Created by noelchew on 04/11/2016.
*/
public class AddDataActivity extends AppCompatActivity {
private static final String TAG = "AddDataActivity";
Context context;
TextInputEditText etTitle, etDescription;
Button btnSave;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_data);
context = this;
setView();
}
private void setView() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Add Data");
setSupportActionBar(toolbar);
etTitle = (TextInputEditText) findViewById(R.id.et_title);
etDescription = (TextInputEditText) findViewById(R.id.et_description);
btnSave = (Button) findViewById(R.id.btn_ok);
btnSave.setOnClickListener(btnSaveOnClickListener);
}
private View.OnClickListener btnSaveOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = etTitle.getText().toString().trim();
String description = etDescription.getText().toString().trim();
if (TextUtils.isEmpty(title)) {
ToastUtil.toastShortMessage(context, "Invalid title.");
return;
}
if (TextUtils.isEmpty(description)) {
ToastUtil.toastShortMessage(context, "Invalid description.");
return;
}
DummyObject dummyObject = new DummyObject(title, description);
if (!dummyObject.save()) {
ToastUtil.toastShortMessage(context, "Error saving data!");
} else {
finish();
}
}
};
}
| 30.608108 | 86 | 0.661369 |
5c017a868202b221b83485570ee76eb08f91e0a5 | 4,877 | package io.github.frogastudios.facecavity.facecavities.types;
import net.tigereye.chestcavity.registration.CCItems;
import io.github.frogastudios.facecavity.registration.FCOrganScores;
import io.github.frogastudios.facecavity.util.FaceCavityUtil;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Identifier;
import io.github.frogastudios.facecavity.facecavities.FaceCavityInventory;
import io.github.frogastudios.facecavity.facecavities.FaceCavityType;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class GhastFaceCavity extends BaseFaceCavity implements FaceCavityType {
@Override
public void fillFaceCavityInventory(FaceCavityInventory faceCavity) {
faceCavity.clear();
faceCavity.setStack(0, new ItemStack(CCItems.ANIMAL_MUSCLE, CCItems.ANIMAL_MUSCLE.getMaxCount()));
faceCavity.setStack(1, new ItemStack(CCItems.GAS_BLADDER, CCItems.GAS_BLADDER.getMaxCount()));
faceCavity.setStack(2, new ItemStack(CCItems.ANIMAL_APPENDIX, CCItems.ANIMAL_APPENDIX.getMaxCount()));
faceCavity.setStack(3, new ItemStack(CCItems.GAS_BLADDER, CCItems.GAS_BLADDER.getMaxCount()));
faceCavity.setStack(4, new ItemStack(CCItems.ANIMAL_HEART, CCItems.ANIMAL_HEART.getMaxCount()));
faceCavity.setStack(5, new ItemStack(CCItems.GAS_BLADDER, CCItems.GAS_BLADDER.getMaxCount()));
faceCavity.setStack(6, ItemStack.EMPTY);
faceCavity.setStack(7, new ItemStack(CCItems.GAS_BLADDER, CCItems.GAS_BLADDER.getMaxCount()));
faceCavity.setStack(8, new ItemStack(CCItems.ANIMAL_MUSCLE, CCItems.ANIMAL_MUSCLE.getMaxCount()));
faceCavity.setStack(9, new ItemStack(CCItems.ANIMAL_MUSCLE, CCItems.ANIMAL_MUSCLE.getMaxCount()));
faceCavity.setStack(10, new ItemStack(CCItems.ANIMAL_RIB, CCItems.ANIMAL_RIB.getMaxCount()));
faceCavity.setStack(11, new ItemStack(CCItems.ANIMAL_SPLEEN, CCItems.ANIMAL_SPLEEN.getMaxCount()));
faceCavity.setStack(12, new ItemStack(CCItems.ANIMAL_KIDNEY, CCItems.ANIMAL_KIDNEY.getMaxCount()));
faceCavity.setStack(13, new ItemStack(CCItems.ANIMAL_SPINE, CCItems.ANIMAL_SPINE.getMaxCount()));
faceCavity.setStack(14, new ItemStack(CCItems.ANIMAL_KIDNEY, CCItems.ANIMAL_KIDNEY.getMaxCount()));
faceCavity.setStack(15, new ItemStack(CCItems.ANIMAL_LIVER, CCItems.ANIMAL_LIVER.getMaxCount()));
faceCavity.setStack(16, new ItemStack(CCItems.ANIMAL_RIB, CCItems.ANIMAL_RIB.getMaxCount()));
faceCavity.setStack(17, new ItemStack(CCItems.ANIMAL_MUSCLE, CCItems.ANIMAL_MUSCLE.getMaxCount()));
faceCavity.setStack(18, new ItemStack(CCItems.ANIMAL_MUSCLE, CCItems.ANIMAL_MUSCLE.getMaxCount()));
faceCavity.setStack(19, new ItemStack(CCItems.ANIMAL_MUSCLE, CCItems.ANIMAL_MUSCLE.getMaxCount()));
faceCavity.setStack(20, new ItemStack(CCItems.ANIMAL_INTESTINE, CCItems.ANIMAL_INTESTINE.getMaxCount()));
faceCavity.setStack(21, new ItemStack(CCItems.ANIMAL_INTESTINE, CCItems.ANIMAL_INTESTINE.getMaxCount()));
faceCavity.setStack(22, new ItemStack(CCItems.VOLATILE_STOMACH, CCItems.VOLATILE_STOMACH.getMaxCount()));
faceCavity.setStack(23, new ItemStack(CCItems.ANIMAL_INTESTINE, CCItems.ANIMAL_INTESTINE.getMaxCount()));
faceCavity.setStack(24, new ItemStack(CCItems.ANIMAL_INTESTINE, CCItems.ANIMAL_INTESTINE.getMaxCount()));
faceCavity.setStack(25, new ItemStack(CCItems.ANIMAL_MUSCLE, CCItems.ANIMAL_MUSCLE.getMaxCount()));
faceCavity.setStack(26, new ItemStack(CCItems.ANIMAL_MUSCLE, CCItems.ANIMAL_MUSCLE.getMaxCount()));
}
@Override
public void loadBaseOrganScores(Map<Identifier, Float> organScores){
organScores.clear();
organScores.put(FCOrganScores.BUOYANT,-4f);
}
@Override
public void generateRareOrganDrops(Random random, int looting, List<ItemStack> loot) {
LinkedList<Item> organPile = new LinkedList<>();
for(int i = 0; i < 4; i++){
organPile.add(CCItems.GAS_BLADDER);
}
for(int i = 0; i < 8; i++){
organPile.add(CCItems.ANIMAL_MUSCLE);
}
for(int i = 0; i < 4; i++){
organPile.add(CCItems.ANIMAL_INTESTINE);
}
organPile.add(CCItems.ANIMAL_APPENDIX);
organPile.add(CCItems.ANIMAL_HEART);
organPile.add(CCItems.ANIMAL_KIDNEY);
organPile.add(CCItems.ANIMAL_KIDNEY);
organPile.add(CCItems.ANIMAL_LIVER);
organPile.add(CCItems.ANIMAL_RIB);
organPile.add(CCItems.ANIMAL_RIB);
organPile.add(CCItems.ANIMAL_SPINE);
organPile.add(CCItems.ANIMAL_SPLEEN);
organPile.add(CCItems.VOLATILE_STOMACH);
int rolls = 1 + random.nextInt(3) + random.nextInt(3);
FaceCavityUtil.drawOrgansFromPile(organPile,rolls,random,loot);
}
}
| 59.47561 | 113 | 0.742875 |
079fa4823e04f3f5570608226559c5b5b462ce9d | 496 | package com.javaprogramto.activemq.activemqstandalonedemo.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class MessageConsumer {
Logger logger = LoggerFactory.getLogger(getClass());
@JmsListener(destination = "standalone-activemq-queue")
public void consume(String message){
logger.info("Message received : "+message);
}
}
| 23.619048 | 67 | 0.772177 |
ee4c39e9d19982ddf812bf0435e4866253a74ffa | 3,299 | package org.aksw.rdfunit.io.writer;
import org.aksw.jena_sparql_api.core.QueryExecutionFactory;
import org.aksw.rdfunit.io.IOUtils;
import org.aksw.rdfunit.services.PrefixNSService;
import org.apache.jena.rdf.model.Model;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* <p>RDFFileWriter class.</p>
*
* @author Dimitris Kontokostas
* Writes a Model to a file
* @since 11/14/13 1:01 PM
* @version $Id: $Id
*/
public class RdfFileWriter implements RdfWriter {
private final String filename;
private final String filetype;
private final boolean skipIfExists;
private final boolean createParentDirectories;
private final boolean overwrite;
/**
* <p>Constructor for RDFFileWriter.</p>
*
* @param filename a {@link java.lang.String} object.
*/
public RdfFileWriter(String filename) {
this(filename, "TURTLE", false, true, true);
}
/**
* <p>Constructor for RDFFileWriter.</p>
*
* @param filename a {@link java.lang.String} object.
* @param filetype a {@link java.lang.String} object.
*/
public RdfFileWriter(String filename, String filetype) {
this(filename, filetype, false, true, true);
}
/**
* <p>Constructor for RDFFileWriter.</p>
*
* @param filename a {@link java.lang.String} object.
* @param skipIfExists a boolean.
*/
public RdfFileWriter(String filename, boolean skipIfExists) {
this(filename, "TURTLE", skipIfExists, true, true);
}
/**
* <p>Constructor for RDFFileWriter.</p>
*
* @param filename a {@link java.lang.String} object.
* @param filetype a {@link java.lang.String} object.
* @param skipIfExists a boolean.
* @param createParentDirectories a boolean.
* @param overwrite a boolean.
*/
public RdfFileWriter(String filename, String filetype, boolean skipIfExists, boolean createParentDirectories, boolean overwrite) {
super();
this.filename = filename;
this.filetype = filetype;
this.skipIfExists = skipIfExists;
this.createParentDirectories = createParentDirectories;
this.overwrite = overwrite;
}
/** {@inheritDoc} */
@Override
public void write(QueryExecutionFactory qef) throws RdfWriterException {
File file = new File(filename);
if (file.exists() && skipIfExists) {
return;
}
if (file.exists() && !overwrite) {
throw new RdfWriterException("Error writing file: File already exists and cannot overwrite");
}
if (createParentDirectories) {
File parentF = file.getParentFile();
if (parentF != null && !parentF.exists() && !parentF.mkdirs()) {
throw new RdfWriterException("Error writing file: Cannot create new directory structure for file: " + filename);
}
}
try (OutputStream fos = new FileOutputStream(file)) {
Model model = IOUtils.getModelFromQueryFactory(qef);
PrefixNSService.setNSPrefixesInModel(model);
model.write(fos, filetype);
} catch (Exception e) {
throw new RdfWriterException("Error writing file: " + e.getMessage(), e);
}
}
}
| 30.546296 | 134 | 0.640497 |
1c1feeac8a11afa919d79344fbe994beae1a2bab | 2,252 | package com.dyn.mall.ware.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
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;
import com.dyn.mall.ware.entity.OmsRefundInfoEntity;
import com.dyn.mall.ware.service.OmsRefundInfoService;
import com.dyn.mall.common.utils.PageUtils;
import com.dyn.mall.common.utils.R;
/**
* 退款信息
*
* @author dyn
* @email 596324727@qq.com
* @date 2020-12-23 23:17:14
*/
@RestController
@RequestMapping("ware/omsrefundinfo")
public class OmsRefundInfoController {
@Autowired
private OmsRefundInfoService omsRefundInfoService;
/**
* 列表
*/
@RequestMapping("/list")
//@RequiresPermissions("ware:omsrefundinfo:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = omsRefundInfoService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("ware:omsrefundinfo:info")
public R info(@PathVariable("id") Long id){
OmsRefundInfoEntity omsRefundInfo = omsRefundInfoService.getById(id);
return R.ok().put("omsRefundInfo", omsRefundInfo);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("ware:omsrefundinfo:save")
public R save(@RequestBody OmsRefundInfoEntity omsRefundInfo){
omsRefundInfoService.save(omsRefundInfo);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("ware:omsrefundinfo:update")
public R update(@RequestBody OmsRefundInfoEntity omsRefundInfo){
omsRefundInfoService.updateById(omsRefundInfo);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("ware:omsrefundinfo:delete")
public R delete(@RequestBody Long[] ids){
omsRefundInfoService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
| 25.022222 | 71 | 0.70071 |
a229ab1df786805fc18214e47043fddd7c257d35 | 537 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package validateinput;
import java.util.Scanner;
/**
*
* @author jameswilliams
*/
public class ValidateInput {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int number;Scanner scan = new Scanner(System.in);
do
{
System.out.print("Enter a number between 1 and 10: ");
number = scan.nextInt();
} while ( number < 1 || number > 10 );
System.out.println("Thank you.");
}
} | 18.517241 | 56 | 0.66108 |
413eb9cb8a89401c562623fb7fdde3644460de25 | 4,530 | /*
* Copyright (c) 2015-2020 Evolveum
*
* 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.evolveum.polygon.connector.ssh;
import org.identityconnectors.framework.common.exceptions.ConfigurationException;
import org.identityconnectors.framework.common.objects.ScriptContext;
import java.util.Map;
public class CommandProcessor {
private final SshConfiguration configuration;
public CommandProcessor(SshConfiguration configuration) {
this.configuration = configuration;
}
public String process(ScriptContext scriptCtx) {
String command = scriptCtx.getScriptText();
if (command == null) {
return null;
}
Map<String, Object> arguments = scriptCtx.getScriptArguments();
if (arguments == null) {
return command;
}
if (configuration.getArgumentStyle() == null) {
return encodeArgumentsAndCommandToString(command, arguments, "-");
}
switch (configuration.getArgumentStyle()) {
case SshConfiguration.ARGUMENT_STYLE_VARIABLES_BASH:
return encodeVariablesAndCommandToString(command, arguments, "", false);
case SshConfiguration.ARGUMENT_STYLE_VARIABLES_POWERSHELL:
return encodeVariablesAndCommandToString(command, arguments, "$", true);
case SshConfiguration.ARGUMENT_STYLE_DASH:
return encodeArgumentsAndCommandToString(command, arguments, "-");
case SshConfiguration.ARGUMENT_STYLE_SLASH:
return encodeArgumentsAndCommandToString(command, arguments, "/");
default:
throw new ConfigurationException("Unknown value of argument style: "+configuration.getArgumentStyle());
}
}
private String encodeArgumentsAndCommandToString(String command, Map<String, Object> arguments, String paramPrefix) {
StringBuilder commandLineBuilder = new StringBuilder();
commandLineBuilder.append(command);
for (Map.Entry<String, Object> argEntry: arguments.entrySet()) {
if (argEntry.getKey() == null) {
// we want this to go last
continue;
}
commandLineBuilder.append(" ");
commandLineBuilder.append(paramPrefix).append(argEntry.getKey());
if (argEntry.getValue() != null) {
commandLineBuilder.append(" ");
commandLineBuilder.append(argEntry.getValue().toString());
}
}
if (arguments.get(null) != null) {
commandLineBuilder.append(" ");
commandLineBuilder.append(arguments.get(null));
}
return commandLineBuilder.toString();
}
private String encodeVariablesAndCommandToString(String command, Map<String, Object> arguments, String variablePrefix, boolean spaces) {
if (arguments == null) {
return command;
}
StringBuilder commandLineBuilder = new StringBuilder();
for (Map.Entry<String, Object> argEntry: arguments.entrySet()) {
if (argEntry.getKey() == null) {
// we want this to go last
continue;
}
commandLineBuilder.append(variablePrefix).append(argEntry.getKey());
if (spaces) {
commandLineBuilder.append(" = ");
} else {
commandLineBuilder.append("=");
}
commandLineBuilder.append(quoteSingle(argEntry.getValue().toString()));
commandLineBuilder.append("; ");
}
commandLineBuilder.append(command);
if (arguments.get(null) != null) {
commandLineBuilder.append(" ");
commandLineBuilder.append(arguments.get(null));
}
return commandLineBuilder.toString();
}
private String quoteSingle(Object value) {
if (value == null) {
return "";
}
return "'" + value.toString().replaceAll("'", "''") + "'";
}
}
| 40.088496 | 140 | 0.633113 |
9ee386342983507f2d1f7607b0a8b52bf3559f1a | 1,127 | package fi.evident.blogular.web.resolvers;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoggingHandlerExceptionResolver implements HandlerExceptionResolver, Ordered {
@NotNull
private static final Logger log = LoggerFactory.getLogger(LoggingHandlerExceptionResolver.class);
@Nullable
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// Log all unhandled exceptions but return null to let other handlers chime in as well
log.warn("Unhandled exception {}", ex, ex);
return null;
}
@Override
public int getOrder() {
return Integer.MIN_VALUE;
}
}
| 33.147059 | 130 | 0.784383 |
18972e02bfb3cf6cca68eb5d075b4e6468d6d739 | 316 | package com.boot.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.boot.pojo.OperationLog;
import org.springframework.stereotype.Repository;
/**
* @author lm
* @version 1.8
* @date 2021/8/17 20:00
*/
@Repository
public interface OperaLogRepository extends BaseMapper<OperationLog> {
}
| 21.066667 | 70 | 0.775316 |
988899b91b33069a84ca0a176ab7c15246cad95d | 2,758 | /*
* Copyright (c) 2013, University of Toronto.
*
* 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 edu.toronto.cs.xcurator.common;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* @author zhuerkan
*/
public class XmlDocumentBuilder {
public Document createDocument() throws ParserConfigurationException {
DocumentBuilder builder = createNsAwareDocumentBuilder();
return builder.newDocument();
}
public Element addRootElement(Document doc, String rootNamespaceUri,
String rootName) {
Element root = doc.createElementNS(rootNamespaceUri, rootName);
doc.appendChild(root);
return root;
}
public DocumentBuilder createNsAwareDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
return builderFactory.newDocumentBuilder();
}
public void addNsContextToEntityElement(Element entity, NsContext nsCtx) {
for (Map.Entry<String, String> ns : nsCtx.getNamespaces().entrySet()) {
String attributeName = XMLConstants.XMLNS_ATTRIBUTE;
if (!ns.getKey().equals("")) {
attributeName += ":" + ns.getKey();
}
entity.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
attributeName, ns.getValue());
}
}
public void addUriBasedAttrToElement(String attrName, String typeUri,
NsContext nsContext, Element element) {
if (typeUri.startsWith("http://")) {
String typeName = typeUri.substring(typeUri.lastIndexOf("/") + 1);
String baseUri = typeUri.substring(0, typeUri.lastIndexOf("/"));
String prefix = nsContext.getPrefix(baseUri);
element.setAttribute(attrName, prefix == null ? typeUri : prefix + ":" + typeName);
} else {
element.setAttribute(attrName, typeUri);
}
}
}
| 37.27027 | 95 | 0.680928 |
1b679eeb8631f00db7b8fa6fd4cd41dea5409bf9 | 318 | package com.gildedrose;
import java.util.Arrays;
import com.gildedrose.goods.Goods;
class GildedRose {
Goods[] goodsItems;
public GildedRose(Goods[] items) {
this.goodsItems = items;
}
public void updateGoodsInfos() {
Arrays.stream(goodsItems).forEach(Goods::updateInfo);
}
}
| 16.736842 | 61 | 0.672956 |
810123ec7316c498115e21ce04567087cd5b0524 | 16,342 | /*
* api.video Java API client
* api.video is an API that encodes on the go to facilitate immediate playback, enhancing viewer streaming experiences across multiple devices and platforms. You can stream live or on-demand online videos within minutes.
*
* The version of the OpenAPI document: 1
* Contact: ecosystem@api.video
*
* NOTE: This class is auto generated.
* Do not edit the class manually.
*/
package video.api.client.api.models;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.io.Serializable;
/**
* PlayerThemeCreationPayload
*/
public class PlayerThemeCreationPayload implements Serializable {
private static final long serialVersionUID = 1L;
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private String name;
public static final String SERIALIZED_NAME_TEXT = "text";
@SerializedName(SERIALIZED_NAME_TEXT)
private String text;
public static final String SERIALIZED_NAME_LINK = "link";
@SerializedName(SERIALIZED_NAME_LINK)
private String link;
public static final String SERIALIZED_NAME_LINK_HOVER = "linkHover";
@SerializedName(SERIALIZED_NAME_LINK_HOVER)
private String linkHover;
public static final String SERIALIZED_NAME_LINK_ACTIVE = "linkActive";
@SerializedName(SERIALIZED_NAME_LINK_ACTIVE)
private String linkActive;
public static final String SERIALIZED_NAME_TRACK_PLAYED = "trackPlayed";
@SerializedName(SERIALIZED_NAME_TRACK_PLAYED)
private String trackPlayed;
public static final String SERIALIZED_NAME_TRACK_UNPLAYED = "trackUnplayed";
@SerializedName(SERIALIZED_NAME_TRACK_UNPLAYED)
private String trackUnplayed;
public static final String SERIALIZED_NAME_TRACK_BACKGROUND = "trackBackground";
@SerializedName(SERIALIZED_NAME_TRACK_BACKGROUND)
private String trackBackground;
public static final String SERIALIZED_NAME_BACKGROUND_TOP = "backgroundTop";
@SerializedName(SERIALIZED_NAME_BACKGROUND_TOP)
private String backgroundTop;
public static final String SERIALIZED_NAME_BACKGROUND_BOTTOM = "backgroundBottom";
@SerializedName(SERIALIZED_NAME_BACKGROUND_BOTTOM)
private String backgroundBottom;
public static final String SERIALIZED_NAME_BACKGROUND_TEXT = "backgroundText";
@SerializedName(SERIALIZED_NAME_BACKGROUND_TEXT)
private String backgroundText;
public static final String SERIALIZED_NAME_ENABLE_API = "enableApi";
@SerializedName(SERIALIZED_NAME_ENABLE_API)
private Boolean enableApi = true;
public static final String SERIALIZED_NAME_ENABLE_CONTROLS = "enableControls";
@SerializedName(SERIALIZED_NAME_ENABLE_CONTROLS)
private Boolean enableControls = true;
public static final String SERIALIZED_NAME_FORCE_AUTOPLAY = "forceAutoplay";
@SerializedName(SERIALIZED_NAME_FORCE_AUTOPLAY)
private Boolean forceAutoplay = false;
public static final String SERIALIZED_NAME_HIDE_TITLE = "hideTitle";
@SerializedName(SERIALIZED_NAME_HIDE_TITLE)
private Boolean hideTitle = false;
public static final String SERIALIZED_NAME_FORCE_LOOP = "forceLoop";
@SerializedName(SERIALIZED_NAME_FORCE_LOOP)
private Boolean forceLoop = false;
public PlayerThemeCreationPayload name(String name) {
this.name = name;
return this;
}
/**
* Add a name for your player theme here.
*
* @return name
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Add a name for your player theme here.")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PlayerThemeCreationPayload text(String text) {
this.text = text;
return this;
}
/**
* RGBA color for timer text. Default: rgba(255, 255, 255, 1)
*
* @return text
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color for timer text. Default: rgba(255, 255, 255, 1)")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public PlayerThemeCreationPayload link(String link) {
this.link = link;
return this;
}
/**
* RGBA color for all controls. Default: rgba(255, 255, 255, 1)
*
* @return link
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color for all controls. Default: rgba(255, 255, 255, 1)")
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public PlayerThemeCreationPayload linkHover(String linkHover) {
this.linkHover = linkHover;
return this;
}
/**
* RGBA color for all controls when hovered. Default: rgba(255, 255, 255, 1)
*
* @return linkHover
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color for all controls when hovered. Default: rgba(255, 255, 255, 1)")
public String getLinkHover() {
return linkHover;
}
public void setLinkHover(String linkHover) {
this.linkHover = linkHover;
}
public PlayerThemeCreationPayload linkActive(String linkActive) {
this.linkActive = linkActive;
return this;
}
/**
* RGBA color for the play button when hovered.
*
* @return linkActive
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color for the play button when hovered.")
public String getLinkActive() {
return linkActive;
}
public void setLinkActive(String linkActive) {
this.linkActive = linkActive;
}
public PlayerThemeCreationPayload trackPlayed(String trackPlayed) {
this.trackPlayed = trackPlayed;
return this;
}
/**
* RGBA color playback bar: played content. Default: rgba(88, 131, 255, .95)
*
* @return trackPlayed
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color playback bar: played content. Default: rgba(88, 131, 255, .95)")
public String getTrackPlayed() {
return trackPlayed;
}
public void setTrackPlayed(String trackPlayed) {
this.trackPlayed = trackPlayed;
}
public PlayerThemeCreationPayload trackUnplayed(String trackUnplayed) {
this.trackUnplayed = trackUnplayed;
return this;
}
/**
* RGBA color playback bar: downloaded but unplayed (buffered) content. Default: rgba(255, 255, 255, .35)
*
* @return trackUnplayed
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color playback bar: downloaded but unplayed (buffered) content. Default: rgba(255, 255, 255, .35)")
public String getTrackUnplayed() {
return trackUnplayed;
}
public void setTrackUnplayed(String trackUnplayed) {
this.trackUnplayed = trackUnplayed;
}
public PlayerThemeCreationPayload trackBackground(String trackBackground) {
this.trackBackground = trackBackground;
return this;
}
/**
* RGBA color playback bar: background. Default: rgba(255, 255, 255, .2)
*
* @return trackBackground
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color playback bar: background. Default: rgba(255, 255, 255, .2)")
public String getTrackBackground() {
return trackBackground;
}
public void setTrackBackground(String trackBackground) {
this.trackBackground = trackBackground;
}
public PlayerThemeCreationPayload backgroundTop(String backgroundTop) {
this.backgroundTop = backgroundTop;
return this;
}
/**
* RGBA color: top 50% of background. Default: rgba(0, 0, 0, .7)
*
* @return backgroundTop
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color: top 50% of background. Default: rgba(0, 0, 0, .7)")
public String getBackgroundTop() {
return backgroundTop;
}
public void setBackgroundTop(String backgroundTop) {
this.backgroundTop = backgroundTop;
}
public PlayerThemeCreationPayload backgroundBottom(String backgroundBottom) {
this.backgroundBottom = backgroundBottom;
return this;
}
/**
* RGBA color: bottom 50% of background. Default: rgba(0, 0, 0, .7)
*
* @return backgroundBottom
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color: bottom 50% of background. Default: rgba(0, 0, 0, .7)")
public String getBackgroundBottom() {
return backgroundBottom;
}
public void setBackgroundBottom(String backgroundBottom) {
this.backgroundBottom = backgroundBottom;
}
public PlayerThemeCreationPayload backgroundText(String backgroundText) {
this.backgroundText = backgroundText;
return this;
}
/**
* RGBA color for title text. Default: rgba(255, 255, 255, 1)
*
* @return backgroundText
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "RGBA color for title text. Default: rgba(255, 255, 255, 1)")
public String getBackgroundText() {
return backgroundText;
}
public void setBackgroundText(String backgroundText) {
this.backgroundText = backgroundText;
}
public PlayerThemeCreationPayload enableApi(Boolean enableApi) {
this.enableApi = enableApi;
return this;
}
/**
* enable/disable player SDK access. Default: true
*
* @return enableApi
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "enable/disable player SDK access. Default: true")
public Boolean getEnableApi() {
return enableApi;
}
public void setEnableApi(Boolean enableApi) {
this.enableApi = enableApi;
}
public PlayerThemeCreationPayload enableControls(Boolean enableControls) {
this.enableControls = enableControls;
return this;
}
/**
* enable/disable player controls. Default: true
*
* @return enableControls
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "enable/disable player controls. Default: true")
public Boolean getEnableControls() {
return enableControls;
}
public void setEnableControls(Boolean enableControls) {
this.enableControls = enableControls;
}
public PlayerThemeCreationPayload forceAutoplay(Boolean forceAutoplay) {
this.forceAutoplay = forceAutoplay;
return this;
}
/**
* enable/disable player autoplay. Default: false
*
* @return forceAutoplay
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "enable/disable player autoplay. Default: false")
public Boolean getForceAutoplay() {
return forceAutoplay;
}
public void setForceAutoplay(Boolean forceAutoplay) {
this.forceAutoplay = forceAutoplay;
}
public PlayerThemeCreationPayload hideTitle(Boolean hideTitle) {
this.hideTitle = hideTitle;
return this;
}
/**
* enable/disable title. Default: false
*
* @return hideTitle
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "enable/disable title. Default: false")
public Boolean getHideTitle() {
return hideTitle;
}
public void setHideTitle(Boolean hideTitle) {
this.hideTitle = hideTitle;
}
public PlayerThemeCreationPayload forceLoop(Boolean forceLoop) {
this.forceLoop = forceLoop;
return this;
}
/**
* enable/disable looping. Default: false
*
* @return forceLoop
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "enable/disable looping. Default: false")
public Boolean getForceLoop() {
return forceLoop;
}
public void setForceLoop(Boolean forceLoop) {
this.forceLoop = forceLoop;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PlayerThemeCreationPayload playerThemeCreationPayload = (PlayerThemeCreationPayload) o;
return Objects.equals(this.name, playerThemeCreationPayload.name)
&& Objects.equals(this.text, playerThemeCreationPayload.text)
&& Objects.equals(this.link, playerThemeCreationPayload.link)
&& Objects.equals(this.linkHover, playerThemeCreationPayload.linkHover)
&& Objects.equals(this.linkActive, playerThemeCreationPayload.linkActive)
&& Objects.equals(this.trackPlayed, playerThemeCreationPayload.trackPlayed)
&& Objects.equals(this.trackUnplayed, playerThemeCreationPayload.trackUnplayed)
&& Objects.equals(this.trackBackground, playerThemeCreationPayload.trackBackground)
&& Objects.equals(this.backgroundTop, playerThemeCreationPayload.backgroundTop)
&& Objects.equals(this.backgroundBottom, playerThemeCreationPayload.backgroundBottom)
&& Objects.equals(this.backgroundText, playerThemeCreationPayload.backgroundText)
&& Objects.equals(this.enableApi, playerThemeCreationPayload.enableApi)
&& Objects.equals(this.enableControls, playerThemeCreationPayload.enableControls)
&& Objects.equals(this.forceAutoplay, playerThemeCreationPayload.forceAutoplay)
&& Objects.equals(this.hideTitle, playerThemeCreationPayload.hideTitle)
&& Objects.equals(this.forceLoop, playerThemeCreationPayload.forceLoop);
}
@Override
public int hashCode() {
return Objects.hash(name, text, link, linkHover, linkActive, trackPlayed, trackUnplayed, trackBackground,
backgroundTop, backgroundBottom, backgroundText, enableApi, enableControls, forceAutoplay, hideTitle,
forceLoop);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PlayerThemeCreationPayload {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" text: ").append(toIndentedString(text)).append("\n");
sb.append(" link: ").append(toIndentedString(link)).append("\n");
sb.append(" linkHover: ").append(toIndentedString(linkHover)).append("\n");
sb.append(" linkActive: ").append(toIndentedString(linkActive)).append("\n");
sb.append(" trackPlayed: ").append(toIndentedString(trackPlayed)).append("\n");
sb.append(" trackUnplayed: ").append(toIndentedString(trackUnplayed)).append("\n");
sb.append(" trackBackground: ").append(toIndentedString(trackBackground)).append("\n");
sb.append(" backgroundTop: ").append(toIndentedString(backgroundTop)).append("\n");
sb.append(" backgroundBottom: ").append(toIndentedString(backgroundBottom)).append("\n");
sb.append(" backgroundText: ").append(toIndentedString(backgroundText)).append("\n");
sb.append(" enableApi: ").append(toIndentedString(enableApi)).append("\n");
sb.append(" enableControls: ").append(toIndentedString(enableControls)).append("\n");
sb.append(" forceAutoplay: ").append(toIndentedString(forceAutoplay)).append("\n");
sb.append(" hideTitle: ").append(toIndentedString(hideTitle)).append("\n");
sb.append(" forceLoop: ").append(toIndentedString(forceLoop)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 32.553785 | 220 | 0.674948 |
8b590f1373d3f52545c7295dce82c890f07fae24 | 881 | package cn.duc.global.until;
import com.common.lang.util.PropertiesUtil;
public interface Constants {
/** 客户端主题 */
public static final String WEB_THEME = "WEB_THEME";
/** 当前用户 */
public static final String CURRENT_USER = "CURRENT_USER";
/** 在线用户数量 */
public static final String ALLUSER_NUMBER = PropertiesUtil.getString("redis.cache.namespace")
+ "ALLUSER_NUMBER";
public static final int REQUEST_SUCCESS = 200;
public static final int REQUEST_ERROR = -1;
public static final int START_PAGE_NUM = 1;
public static final int DEFAULT_PAGE_SIZE = 9;
/**
* 1分钟
*/
public static final int ONE_MINUTES_SECOND = 1 * 60;
/**
* 1分钟
*/
public static final long ONE_MINUTES_MILL = 1 * 60 * 1000;
/**
* 3分钟
*/
public static final long THREE_MINUTES_MILL = 3 * 60 * 1000;
/**
* 一亿
*/
public static final int ONE_HUNDRED_MILLION = 100000000;
}
| 19.577778 | 94 | 0.69807 |
18f1e11d0368e70f044aa7b5c6a4781c96c2d922 | 6,595 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.miwok;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ColorsActivity extends AppCompatActivity {
//Creates current page variable
int current = 0;
ArrayList locations = new ArrayList<String>();
//ArrayList<String> locations = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colors);
//Establishes button from XML file
Button next = findViewById(R.id.next);
//If it is clicked then it moves on to next page (updates current variable and loops around)
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
current++;
updateCurrent();
if(current == 3){
current=-1;
}
}
});
}
//next page function
private void updateCurrent(){
locations.add("Harbor Court Hotel");
locations.add("Grant Plaza Hotel");
locations.add("Hotel Riu Plaza Fisherman's Wharf");
locations.add("Hotel Emblem");
//Establishes the ImageView from XMl file
ImageView picture = findViewById(R.id.imageView);
//Establishes the TextView from XMl file
TextView name = findViewById(R.id.textView);
//Establishes the TextView from XMl file
TextView description = findViewById(R.id.textView2);
//The below loops updates the ImageViews and TextViews based on the "current" variable
if(current == 0){
picture.setImageDrawable(getDrawable(R.drawable.harborcourthotel));
name.setText(locations.get(current).toString());
description.setText("Price: $159/night\n\nSet along the waterfront, this stylish hotel is a 6-minute walk from the Ferry Building Marketplace and the BART Embarcadero rail station. Plush, colorful rooms feature Bay Bridge, city or courtyard views and have free Wi-Fi, iHome docks, minibars and flat-screen TVs. Rooms also have yoga mats, designer toiletries, Italian linens and goose-down duvets. An evening wine hour and morning coffee and tea are free for guests. Other amenities include a sleek, on-site Japanese restaurant and sake lounge, plus valet parking, loaner bikes and access to an adjacent YMCA (both for a fee). \n\n Address: 165 Steuart St, San Francisco, CA 94105 \n\n Phone number: (415) 882-1300\n");
}
else if(current == 1){
picture.setImageDrawable(getDrawable(R.drawable.grantplaza));
name.setText(locations.get(current).toString());
description.setText("Price: $89/night \n\n Dating from the 1920s, this low-key hotel just inside the gateway to Chinatown is a 2-minute walk from a California Street cable-car stop, and a 6-minute walk from the shops, eateries and cultural attractions in lively Union Square. The understated rooms feature black-and-white photographs, plus desks and flat-screen TVs. Rooms also offer free Wi-Fi and private bathrooms; some have plantation shutters and/or bay windows. Amenities include a lobby with chandeliers, mirrored walls and furnishings that evoke the property's 1920s origins. There's also a sitting area under an antique stained-glass window. Guest-use computers are available.\n\n Address: 465 Grant Ave, San Francisco, CA 94108\n");
}
else if(current == 2) {
picture.setImageDrawable(getDrawable(R.drawable.hotelriuplaza));
name.setText(locations.get(current).toString());
description.setText("Price: $107/night \n\n Set in the Fisherman’s Wharf district, this unfussy hotel on a tree-lined street is a 2-minute walk from a tram stop, 6 minutes' walk from dining and entertainment at Pier 39, and 12 minutes on foot from the hairpin turns of Lombard Street. The laid-back rooms provide Wi-Fi and satellite TV, as well as minifridges and coffee makers. Upgraded rooms add sitting areas with sofas. Suites feature separate living rooms with city views. Amenities include an informal restaurant/bar, plus a gym, a heated outdoor pool, and a sundeck with loungers. Parking, event space and a breakfast buffet are available.\n" +
"\n\nAddress: 2500 Mason St, San Francisco, CA 94133\n" +
"\n\nPhone number: (415) 362-5500\n");
}
else if(current == 3) {
picture.setImageDrawable(getDrawable(R.drawable.hotelemblemsf));
name.setText(locations.get(current).toString());
description.setText("Price: $176/night\n\nCheck in and leave the status quo behind. Hotel Emblem San Francisco, a Viceroy Urban Retreat in downtown San Francisco, where Nob Hill meets Union Square and the Theater District, is a haven for those that think as boldly as they live. Inspiring conversation in all the right ways, with plenty of modern provocations, Hotel Emblem will feature a cocktail-focused restaurant and 96 vibrant guestrooms. Every corner is designed to spark creativity, from the bar inspired by the Beat Generation, to the book-filled Writer’s Alcove in the lobby, to the eclectic guestrooms, where patterns play and an expressive vibe thrives. This hotel is a muse – and you will be, too. Lend your voice at the weekly poetry slam. Get lost in the flow of nightly live jazz. Tap out a few thoughts on the lobby typewriter.\n\n Address: 562 Sutter Street, San Francisco CA\n\n Phone number: (415) 433-4434 ");
}
}
//EditText simpleEditText = (EditText) findViewById(R.id.simpleEditText);
//String editTextValue = simpleEditText.getText().toString();
}
| 61.635514 | 941 | 0.714026 |
77f03e1037f8cc0da4ebf5a416ce39ba395fb117 | 6,450 | /*
* Copyright 2013 Sylvain LAURENT
*
* 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 ch.sla.jdbcperflogger.console.ui;
import java.awt.Dimension;
import java.awt.Frame;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import org.eclipse.jdt.annotation.Nullable;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.sla.jdbcperflogger.console.db.LogRepositoryRead;
import ch.sla.jdbcperflogger.console.db.LogRepositoryReadJdbc;
import ch.sla.jdbcperflogger.console.db.LogRepositoryUpdate;
import ch.sla.jdbcperflogger.console.db.LogRepositoryUpdateJdbc;
import ch.sla.jdbcperflogger.console.net.AbstractLogReceiver;
import ch.sla.jdbcperflogger.console.net.ClientLogReceiver;
import ch.sla.jdbcperflogger.console.net.ServerLogReceiver;
public class PerfLoggerGuiMain implements IClientConnectionDelegate {
private static final String LOOK_AND_FEEL_CLASS_NAME_PREF_KEY = "lookAndFeelClassName";
private final static Logger LOGGER = LoggerFactory.getLogger(PerfLoggerGuiMain.class);
private final PerfLoggerGuiMainFrame frmJdbcPerformanceLogger;
private final Map<String, PerfLoggerController> connectionsToLogController = new HashMap<>();
private static final Preferences prefs = Preferences.userNodeForPackage(PerfLoggerGuiMain.class);
/**
* Launch the application.
*/
public static void main(final String[] args) {
LOGGER.debug("PerfLoggerGuiMain starting...");
SwingUtilities.invokeLater(() -> {
installLookAndFeel();
try {
final PerfLoggerGuiMain window = new PerfLoggerGuiMain();
window.frmJdbcPerformanceLogger.setVisible(true);
} catch (final Exception e) {
e.printStackTrace();
}
});
}
private static void installLookAndFeel() {
final String lfClassName = getPreferredLookAndFeel();
try {
if (lfClassName != null) {
UIManager.setLookAndFeel(lfClassName);
} else {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
LOGGER.warn("Error setting LookAndFeel", e);
}
}
@Nullable
static String getPreferredLookAndFeel() {
return prefs.get(LOOK_AND_FEEL_CLASS_NAME_PREF_KEY, null);
}
static void savePreferredLookAndFeel(final @Nullable String lfClassName) {
if (lfClassName == null) {
prefs.remove(LOOK_AND_FEEL_CLASS_NAME_PREF_KEY);
} else {
prefs.put(LOOK_AND_FEEL_CLASS_NAME_PREF_KEY, lfClassName);
}
try {
prefs.sync();
} catch (final BackingStoreException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Create the application.
*/
public PerfLoggerGuiMain() {
ToolTipManager.sharedInstance().setInitialDelay(500);
frmJdbcPerformanceLogger = new PerfLoggerGuiMainFrame();
final JPanel welcomePanel = new WelcomePanel(this);
frmJdbcPerformanceLogger.addTab("Welcome", welcomePanel);
// TODO make server port configurable
final PerfLoggerController serverPerfLoggerController = createServer(4561);
frmJdbcPerformanceLogger.addTab("*:4561", serverPerfLoggerController.getPanel());
frmJdbcPerformanceLogger.pack();
frmJdbcPerformanceLogger.setExtendedState(Frame.MAXIMIZED_BOTH);
frmJdbcPerformanceLogger.setMinimumSize(new Dimension(600, 500));
}
@Override
public void createClientConnection(final String host, final int port) {
final PerfLoggerController clientPerfLoggerController = connectToClient(host, port);
frmJdbcPerformanceLogger.addTab(host + ":" + port, clientPerfLoggerController.getPanel());
}
@Override
public void close(final PerfLoggerController perfLoggerController) {
frmJdbcPerformanceLogger.removeTab(perfLoggerController.getPanel());
connectionsToLogController.entrySet().removeIf(entry -> entry.getValue() == perfLoggerController);
}
private PerfLoggerController connectToClient(final String targetHost, final int targetPort) {
final String hostAndPort = targetHost + "_" + targetPort;
PerfLoggerController perfLoggerController = connectionsToLogController.get(hostAndPort);
if (perfLoggerController == null) {
final LogRepositoryUpdate logRepositoryUpdate = new LogRepositoryUpdateJdbc(hostAndPort);
final LogRepositoryRead logRepositoryRead = new LogRepositoryReadJdbc(hostAndPort);
final AbstractLogReceiver logReceiver = new ClientLogReceiver(targetHost, targetPort, logRepositoryUpdate);
logReceiver.start();
perfLoggerController = new PerfLoggerController(this, logReceiver, logRepositoryUpdate, logRepositoryRead);
connectionsToLogController.put(hostAndPort, perfLoggerController);
}
return perfLoggerController;
}
private PerfLoggerController createServer(final int listeningPort) {
final LogRepositoryUpdate logRepositoryUpdate = new LogRepositoryUpdateJdbc("server_" + listeningPort);
final LogRepositoryRead logRepositoryRead = new LogRepositoryReadJdbc("server_" + listeningPort);
final AbstractLogReceiver logReceiver = new ServerLogReceiver(listeningPort, logRepositoryUpdate);
logReceiver.start();
return new PerfLoggerController(this, logReceiver, logRepositoryUpdate, logRepositoryRead);
}
}
| 40.062112 | 119 | 0.724496 |
d9ea4cdcd4c0505477dbf927eb492654ffedbf62 | 1,042 | package net.petafuel.styx.core.xs2a.entities.serializers;
import net.petafuel.styx.core.xs2a.entities.XS2AJsonKeys;
import net.petafuel.styx.core.xs2a.exceptions.SerializerException;
import javax.json.bind.serializer.DeserializationContext;
import javax.json.bind.serializer.JsonbDeserializer;
import javax.json.stream.JsonParser;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ISODateDeserializer implements JsonbDeserializer<Date> {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext, Type type) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(XS2AJsonKeys.DATE_FORMAT.value());
simpleDateFormat.setLenient(false);
try {
return simpleDateFormat.parse(jsonParser.getString());
} catch (ParseException e) {
throw new SerializerException("Wrong dateformat, must be " + XS2AJsonKeys.DATE_FORMAT.value(), e);
}
}
}
| 40.076923 | 110 | 0.770633 |
6be7f4f6190f86b9fda8bd4e081b7537ab39e1ef | 1,104 | package com.fksm.common.dto;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by root on 16-4-23.
*/
public class ResponseTime extends BaseMassageDto implements Serializable {
private Long end_time;
private Long total_cost;
public Long getEnd_time() {
return end_time;
}
public void setEnd_time(Long end_time) {
this.end_time = end_time;
}
public Long getTotal_cost() {
return total_cost;
}
public void setTotal_cost(Long total_cost) {
this.total_cost = total_cost;
}
/**
* @param begin_time
* @return
*/
public static ResponseTime build(String server_ip, String service_id, String request_id, Long begin_time, Long end_time){
ResponseTime responseTime = new ResponseTime();
responseTime.setServer_ip(server_ip);
responseTime.setService_id(service_id);
responseTime.setRequest_id(request_id);
responseTime.setBegin_time(begin_time);
responseTime.setEnd_time(end_time);
return responseTime;
}
}
| 25.090909 | 125 | 0.680254 |
2da19c1909d9935a2657e8e425ec230d70b802b1 | 3,085 | package mb.tego.strategies.runtime;
import mb.tego.patterns.Pattern;
import mb.tego.sequences.PeekableSeq;
import mb.tego.sequences.Seq;
import mb.tego.sequences.SeqBase;
import mb.tego.strategies.NamedStrategy1;
import mb.tego.utils.ExcludeFromJacocoGeneratedReport;
/**
* Strategy that matches the input against a pattern.
*
* @param <T> the type of input (contravariant)
* @param <R> the type of output (covariant)
*/
public final class MatchStrategy<T, R> extends NamedStrategy1<Pattern<T, R>, T, Seq<R>> {
@SuppressWarnings({"rawtypes", "RedundantSuppression"})
private static final MatchStrategy instance = new MatchStrategy();
@SuppressWarnings({"unchecked", "unused", "RedundantCast", "RedundantSuppression"})
public static <T, R> MatchStrategy<T, R> getInstance() { return (MatchStrategy<T, R>)instance; }
private MatchStrategy() { /* Prevent instantiation. Use getInstance(). */ }
public static <T, R> Seq<R> eval(TegoEngine engine, Pattern<T, R> pattern, T input) {
return new SeqBase<R>() {
// Implementation if `yield` and `yieldBreak` could actually suspend computation
@SuppressWarnings("unused")
@ExcludeFromJacocoGeneratedReport
private void computeNextCoroutine() {
// 0:
final boolean matches = pattern.match(input);
if (matches) {
//noinspection unchecked
this.yield((R)input);
}
// 1:
yieldBreak();
}
// STATE MACHINE
private int state = 0;
// LOCAL VARIABLES
// none
@Override
protected void computeNext() {
while (true) {
switch(state) {
case 0:
final boolean matches = pattern.match(input);
if (matches) {
//noinspection unchecked
this.yield((R)input);
this.state = 1;
return;
}
this.state = 1;
break;
case 1:
yieldBreak();
this.state = -1;
return;
default:
throw new IllegalStateException("Illegal state: " + state);
}
}
}
};
}
@Override public Seq<R> evalInternal(TegoEngine engine, Pattern<T, R> pattern, T input) {
return eval(engine, pattern, input);
}
@Override
public String getName() {
return "match";
}
@SuppressWarnings("SwitchStatementWithTooFewBranches") @Override
public String getParamName(int index) {
switch (index) {
case 0: return "pattern";
default: return super.getParamName(index);
}
}
}
| 34.277778 | 100 | 0.515073 |
92e865c337182ce451d590fb34e3f3632bec069d | 128 | package P3;
public class Position {
public int i;
public int j;
public Position(int x,int y) {
this.i=x;
this.j=y;
}
}
| 11.636364 | 31 | 0.640625 |
0ccb15c01cc2f6485b290a7447a281fd1c8f696d | 10,905 | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.change;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.common.CommitInfo;
import com.google.gerrit.extensions.common.GitPerson;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetAncestor;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.ProjectControl;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevSort;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Singleton
public class GetRelated implements RestReadView<RevisionResource> {
private static final Logger log = LoggerFactory.getLogger(GetRelated.class);
private final GitRepositoryManager gitMgr;
private final Provider<ReviewDb> dbProvider;
@Inject
GetRelated(GitRepositoryManager gitMgr, Provider<ReviewDb> db) {
this.gitMgr = gitMgr;
this.dbProvider = db;
}
@Override
public RelatedInfo apply(RevisionResource rsrc)
throws RepositoryNotFoundException, IOException, OrmException {
Repository git = gitMgr.openRepository(rsrc.getChange().getProject());
try {
Ref ref = git.getRef(rsrc.getChange().getDest().get());
RevWalk rw = new RevWalk(git);
try {
RelatedInfo info = new RelatedInfo();
info.changes = walk(rsrc, rw, ref);
return info;
} finally {
rw.release();
}
} finally {
git.close();
}
}
private List<ChangeAndCommit> walk(RevisionResource rsrc, RevWalk rw, Ref ref)
throws OrmException, IOException {
Map<Change.Id, Change> changes = allOpenChanges(rsrc);
Map<PatchSet.Id, PatchSet> patchSets = allPatchSets(changes.keySet());
Map<String, PatchSet> commits = Maps.newHashMap();
for (PatchSet p : patchSets.values()) {
commits.put(p.getRevision().get(), p);
}
RevCommit rev = rw.parseCommit(ObjectId.fromString(
rsrc.getPatchSet().getRevision().get()));
rw.sort(RevSort.TOPO);
rw.markStart(rev);
if (ref != null && ref.getObjectId() != null) {
try {
rw.markUninteresting(rw.parseCommit(ref.getObjectId()));
} catch (IncorrectObjectTypeException notCommit) {
// Ignore and treat as new branch.
}
}
Set<Change.Id> added = Sets.newHashSet();
List<ChangeAndCommit> parents = Lists.newArrayList();
for (RevCommit c; (c = rw.next()) != null;) {
PatchSet p = commits.get(c.name());
Change g = null;
if (p != null) {
g = changes.get(p.getId().getParentKey());
added.add(p.getId().getParentKey());
}
parents.add(new ChangeAndCommit(g, p, c));
}
List<ChangeAndCommit> list = children(rsrc, rw, changes, patchSets, added);
list.addAll(parents);
if (list.size() == 1) {
ChangeAndCommit r = list.get(0);
if (r._changeNumber != null && r._revisionNumber != null
&& r._changeNumber == rsrc.getChange().getChangeId()
&& r._revisionNumber == rsrc.getPatchSet().getPatchSetId()) {
return Collections.emptyList();
}
}
return list;
}
private Map<Change.Id, Change> allOpenChanges(RevisionResource rsrc)
throws OrmException {
ReviewDb db = dbProvider.get();
return db.changes().toMap(
db.changes().byBranchOpenAll(rsrc.getChange().getDest()));
}
private Map<PatchSet.Id, PatchSet> allPatchSets(Collection<Change.Id> ids)
throws OrmException {
int n = ids.size();
ReviewDb db = dbProvider.get();
List<ResultSet<PatchSet>> t = Lists.newArrayListWithCapacity(n);
for (Change.Id id : ids) {
t.add(db.patchSets().byChange(id));
}
Map<PatchSet.Id, PatchSet> r = Maps.newHashMapWithExpectedSize(n * 2);
for (ResultSet<PatchSet> rs : t) {
for (PatchSet p : rs) {
r.put(p.getId(), p);
}
}
return r;
}
private List<ChangeAndCommit> children(RevisionResource rsrc, RevWalk rw,
Map<Change.Id, Change> changes, Map<PatchSet.Id, PatchSet> patchSets,
Set<Change.Id> added)
throws OrmException, IOException {
// children is a map of parent commit name to PatchSet built on it.
Multimap<String, PatchSet.Id> children = allChildren(changes.keySet());
RevFlag seenCommit = rw.newFlag("seenCommit");
LinkedList<String> q = Lists.newLinkedList();
seedQueue(rsrc, rw, seenCommit, patchSets, q);
ProjectControl projectCtl = rsrc.getControl().getProjectControl();
Set<Change.Id> seenChange = Sets.newHashSet();
List<ChangeAndCommit> graph = Lists.newArrayList();
while (!q.isEmpty()) {
String id = q.remove();
// For every matching change find the most recent patch set.
Map<Change.Id, PatchSet.Id> matches = Maps.newHashMap();
for (PatchSet.Id psId : children.get(id)) {
PatchSet.Id e = matches.get(psId.getParentKey());
if ((e == null || e.get() < psId.get())
&& isVisible(projectCtl, changes, patchSets, psId)) {
matches.put(psId.getParentKey(), psId);
}
}
for (Map.Entry<Change.Id, PatchSet.Id> e : matches.entrySet()) {
Change change = changes.get(e.getKey());
PatchSet ps = patchSets.get(e.getValue());
if (change == null || ps == null || !seenChange.add(e.getKey())) {
continue;
}
RevCommit c = rw.parseCommit(ObjectId.fromString(
ps.getRevision().get()));
if (!c.has(seenCommit)) {
c.add(seenCommit);
q.addFirst(ps.getRevision().get());
if (added.add(ps.getId().getParentKey())) {
rw.parseBody(c);
graph.add(new ChangeAndCommit(change, ps, c));
}
}
}
}
Collections.reverse(graph);
return graph;
}
private boolean isVisible(ProjectControl projectCtl,
Map<Change.Id, Change> changes,
Map<PatchSet.Id, PatchSet> patchSets,
PatchSet.Id psId) throws OrmException {
Change c = changes.get(psId.getParentKey());
PatchSet ps = patchSets.get(psId);
if (c != null && ps != null) {
ChangeControl ctl = projectCtl.controlFor(c);
return ctl.isVisible(dbProvider.get())
&& ctl.isPatchVisible(ps, dbProvider.get());
}
return false;
}
private void seedQueue(RevisionResource rsrc, RevWalk rw,
RevFlag seenCommit, Map<PatchSet.Id, PatchSet> patchSets,
LinkedList<String> q) throws IOException {
RevCommit tip = rw.parseCommit(ObjectId.fromString(
rsrc.getPatchSet().getRevision().get()));
tip.add(seenCommit);
q.add(tip.name());
Change.Id cId = rsrc.getChange().getId();
for (PatchSet p : patchSets.values()) {
if (cId.equals(p.getId().getParentKey())) {
try {
RevCommit c = rw.parseCommit(ObjectId.fromString(
p.getRevision().get()));
if (!c.has(seenCommit)) {
c.add(seenCommit);
q.add(c.name());
}
} catch (IOException e) {
log.warn(String.format(
"Cannot read patch set %d of %d",
p.getPatchSetId(), cId.get()), e);
}
}
}
}
private Multimap<String, PatchSet.Id> allChildren(Collection<Change.Id> ids)
throws OrmException {
ReviewDb db = dbProvider.get();
List<ResultSet<PatchSetAncestor>> t =
Lists.newArrayListWithCapacity(ids.size());
for (Change.Id id : ids) {
t.add(db.patchSetAncestors().byChange(id));
}
Multimap<String, PatchSet.Id> r = ArrayListMultimap.create();
for (ResultSet<PatchSetAncestor> rs : t) {
for (PatchSetAncestor a : rs) {
r.put(a.getAncestorRevision().get(), a.getPatchSet());
}
}
return r;
}
private static GitPerson toGitPerson(PersonIdent id) {
GitPerson p = new GitPerson();
p.name = id.getName();
p.email = id.getEmailAddress();
p.date = new Timestamp(id.getWhen().getTime());
p.tz = id.getTimeZoneOffset();
return p;
}
public static class RelatedInfo {
public List<ChangeAndCommit> changes;
}
public static class ChangeAndCommit {
public String changeId;
public CommitInfo commit;
public Integer _changeNumber;
public Integer _revisionNumber;
public Integer _currentRevisionNumber;
ChangeAndCommit(@Nullable Change change, @Nullable PatchSet ps, RevCommit c) {
if (change != null) {
changeId = change.getKey().get();
_changeNumber = change.getChangeId();
_revisionNumber = ps != null ? ps.getPatchSetId() : null;
PatchSet.Id curr = change.currentPatchSetId();
_currentRevisionNumber = curr != null ? curr.get() : null;
}
commit = new CommitInfo();
commit.commit = c.name();
commit.parents = Lists.newArrayListWithCapacity(c.getParentCount());
for (int i = 0; i < c.getParentCount(); i++) {
CommitInfo p = new CommitInfo();
p.commit = c.getParent(i).name();
commit.parents.add(p);
}
commit.author = toGitPerson(c.getAuthorIdent());
commit.subject = c.getShortMessage();
}
}
}
| 34.400631 | 82 | 0.664374 |
23c1df5eaebe372b693a86f541ff203703081baa | 2,392 | package com.hbm.items.machine;
import java.util.List;
import com.hbm.items.ModItems;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ItemFluidIcon extends Item {
public ItemFluidIcon(String s) {
this.setUnlocalizedName(s);
this.setRegistryName(s);
this.setHasSubtypes(true);
this.setMaxDamage(0);
ModItems.ALL_ITEMS.add(this);
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) {
if(tab == this.getCreativeTab())
for(Fluid f : FluidRegistry.getRegisteredFluids().values())
items.add(getStack(f));
}
@Override
public void addInformation(ItemStack stack, World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
if(stack.hasTagCompound())
if(stack.getTagCompound().getInteger("fill") > 0)
tooltip.add(stack.getTagCompound().getInteger("fill") + "mB");
}
@Override
public String getItemStackDisplayName(ItemStack stack) {
String s;
Fluid f = getFluid(stack);
if(f != null)
s = (f.getLocalizedName(new FluidStack(f, 1000)).trim());
else
s = null;
if (s != null)
{
return s;
}
return "Unknown";
}
public static ItemStack getStack(Fluid f){
ItemStack stack = new ItemStack(ModItems.fluid_icon, 1, 0);
stack.setTagCompound(new NBTTagCompound());
stack.getTagCompound().setString("type", f.getName());
return stack;
}
public static ItemStack getStackWithQuantity(Fluid f, int amount){
ItemStack stack = new ItemStack(ModItems.fluid_icon, 1, 0);
stack.setTagCompound(new NBTTagCompound());
stack.getTagCompound().setString("type", f.getName());
stack.getTagCompound().setInteger("fill", amount);
return stack;
}
public static Fluid getFluid(ItemStack stack){
if(stack == null || !stack.hasTagCompound())
return null;
return FluidRegistry.getFluid(stack.getTagCompound().getString("type"));
}
}
| 28.47619 | 104 | 0.726171 |
45d92b53cdd41c946c56f8d2d186ec03711d7057 | 859 | package com.passing.challenge.mapper;
import com.passing.challenge.model.PassingChallenge;
import com.passing.challenge.types.GetPassingChallengesResponse;
import com.passing.challenge.types.PassingChallengeDetail;
import org.mapstruct.Mapper;
import java.util.List;
@Mapper(componentModel = "spring")
public interface PassingChallengeMapper {
default GetPassingChallengesResponse passingChallengeDetailsToGetPassingChallengeResponse(List<PassingChallengeDetail> passingChallengeDetails) {
GetPassingChallengesResponse getPassingChallengesResponse = new GetPassingChallengesResponse();
getPassingChallengesResponse.setPassingChallenges(passingChallengeDetails);
return getPassingChallengesResponse;
}
List<PassingChallengeDetail> passingChallengesToPassingChallengeDetails(List<PassingChallenge> passingChallenges);
}
| 40.904762 | 149 | 0.845169 |
6f60a74b844c4197e6ff7fff027467db20aa4f06 | 2,892 | package ru.i_novus.ms.rdm;
import net.n2oapp.framework.api.metadata.io.IOProcessorAware;
import net.n2oapp.framework.api.metadata.reader.NamespaceReaderFactory;
import net.n2oapp.framework.config.N2oApplicationBuilder;
import net.n2oapp.framework.config.io.IOProcessorImpl;
import net.n2oapp.framework.config.metadata.compile.N2oCompileProcessor;
import net.n2oapp.framework.config.metadata.pack.*;
import net.n2oapp.framework.config.reader.XmlMetadataLoader;
import net.n2oapp.framework.config.register.scanner.XmlInfoScanner;
import net.n2oapp.framework.config.test.N2oTestBase;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import static java.util.Arrays.asList;
/**
* Тестирование валидности файлов N2O
*/
public class RdmMetadataTest extends N2oTestBase {
private static final Logger logger = LoggerFactory.getLogger(RdmMetadataTest.class);
private static final List<String> RDM_CUSTOM_PROPERTIES = asList(
"server.servlet.context-path= ",
"rdm.context-path=/#",
"rdm.backend.path=http://localhost:8080/rdm/api",
"rdm.user.admin.url=http://docker.one:8182/",
"rdm.permissions.refbook.status.list= ",
"rdm.l10n.support=false"
);
@Override
@Before
public void setUp() throws Exception {
super.setUp();
}
@Override
protected void configure(N2oApplicationBuilder builder) {
super.configure(builder);
customProperties(builder);
builder.loaders(new XmlMetadataLoader(builder.getEnvironment().getNamespaceReaderFactory()));
builder.packs(new N2oAllDataPack(), new N2oAllPagesPack(), new N2oAllValidatorsPack(), new N2oApplicationPack());
builder.scanners(new XmlInfoScanner());
builder.scan();
new N2oCompileProcessor(builder.getEnvironment());
}
@Test
public void validate() {
builder.getEnvironment().getMetadataRegister()
.find(i -> !"rdm".equals(i.getId()))
.forEach(i -> {
try {
builder.read().validate().get(i.getId(), i.getBaseSourceClass());
} catch (Exception e) {
logger.error(e.getMessage(), e);
assert false : "Fail on id=" + i.getId() + ", class=" + i.getBaseSourceClass().getSimpleName();
}
});
}
private void customProperties(N2oApplicationBuilder builder) {
RDM_CUSTOM_PROPERTIES.forEach(builder::properties);
NamespaceReaderFactory readerFactory = builder.getEnvironment().getNamespaceReaderFactory();
IOProcessorImpl processor = new IOProcessorImpl(readerFactory);
((IOProcessorAware) readerFactory).setIOProcessor(processor);
processor.setSystemProperties(builder.getEnvironment().getSystemProperties());
}
}
| 36.15 | 121 | 0.691909 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.